javascript / expert
Snippet
Dynamic Directive Argument Sanitization Against Prototype Pollution
Custom directives receiving dynamic binding arguments (e.g. `v-secure-attr:[dynamicKey]`) must guard against prototype injection vector keys such as `__proto__` or `constructor`. Verifying keys against Object.prototype properties before DOM attribute mapping prevents malicious attribute insertion.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { sanitizeHtmlKey } from './security-utils';export const vSecureAttr = {mounted(el, binding) {const rawKey = String(binding.arg || '');if (Object.prototype.hasOwnProperty.call(Object.prototype, rawKey)) {throw new SecurityError('Potential prototype pollution in directive argument.');}const safeKey = sanitizeHtmlKey(rawKey);el.setAttribute(`data-${safeKey}`, String(binding.value));},updated(el, binding) {if (binding.value !== binding.oldValue) {const safeKey = sanitizeHtmlKey(String(binding.arg || ''));el.setAttribute(`data-${safeKey}`, String(binding.value));}}};
vue
Breakdown
1
const rawKey = String(binding.arg || '');
Extracts the dynamic directive argument passed via syntax v-directive:[arg].
2
if (Object.prototype.hasOwnProperty.call(Object.prototype, rawKey)) {
Checks whether the argument key matches dangerous prototype chain property names.
3
const safeKey = sanitizeHtmlKey(rawKey);
Sanitizes the string key to ensure only valid HTML dataset attribute names are constructed.