javascript / expert
Snippet
Dynamische Bereinigung von Direktiven-Argumenten gegen Prototype Pollution
Benutzerdefinierte Direktiven mit dynamischen Argumenten (z. B. `v-secure-attr:[dynamicKey]`) müssen gegen Prototype-Pollution-Schlüssel wie `__proto__` oder `constructor` abgesichert werden. Die Überprüfung der Schlüssel vor der DOM-Attributzuweisung verhindert böswillige Attribut-Injektionen.
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
Erklärung
1
const rawKey = String(binding.arg || '');
Extrahiert das dynamische Direktiven-Argument aus der Syntax v-directive:[arg].
2
if (Object.prototype.hasOwnProperty.call(Object.prototype, rawKey)) {
Prüft, ob der Schlüssel mit gefährlichen Namen der Prototypen-Kette übereinstimmt.
3
const safeKey = sanitizeHtmlKey(rawKey);
Bereinigt den String-Schlüssel, damit nur gültige HTML-Dataset-Attributnamen erstellt werden.