javascript / expert
Snippet
Compiler AST Element Node Sanitization for Template Injections
Vue SFC compilation parses template strings into an Abstract Syntax Tree (AST). By tapping into compiler nodeTransforms options, security infrastructure can strip hazardous inline event attributes during compile-time transformation prior to code generation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { compile } from 'vue/compiler-sfc';function sanitizeAstNode(node) {if (node.type === 1) {node.props = node.props.filter(prop => {if (prop.type === 6 && prop.name.startsWith('on')) {return !/^on\w+/i.test(prop.name);}return true;});node.children.forEach(sanitizeAstNode);}}export function compileSecureTemplate(template) {return compile(template, {nodeTransforms: [(node) => {sanitizeAstNode(node);}]});}
vue
Breakdown
1
if (node.type === 1) {
Checks if the AST node represents an element node in the template structure.
2
if (prop.type === 6 && prop.name.startsWith('on')) {
Identifies plain HTML attributes that attempt inline event handling.
3
return !/^on\w+/i.test(prop.name);
Strips potential inline event handler vectors like onload or onerror.
4
nodeTransforms: [
Hooks a custom compiler transform into Vue template compilation lifecycle.