0 Tage Serie
javascript / intermediate
Snippet

Bereinigung dynamischer Hyperlinks gegen Skript-Injektion

Das direkte Binden dynamischer URLs an `href`-Attribute in Vorlagen kann Anwendungen für Cross-Site-Scripting-Angriffe (XSS) über `javascript:`- oder `data:`-Schemata öffnen. Durch Kapselung des URL-Parsings in einer reaktiven Computed Property wird die Protokollvalidierung erzwungen, bevor unsichere Strings die DOM-Ebene erreichen.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { computed } from 'vue';
export function useSafeLink(rawUrlRef) {
const allowedProtocols = new Set(['http:', 'https:', 'mailto:']);
const sanitizedUrl = computed(() => {
try {
const parsed = new URL(rawUrlRef.value, window.location.origin);
return allowedProtocols.has(parsed.protocol) ? parsed.href : '#';
} catch {
return '#';
}
});
return { sanitizedUrl };
}
vue
Erklärung
1
const allowedProtocols = new Set(['http:', 'https:', 'mailto:']);
Initialisiert eine strikte Whitelist sicherer URI-Schemata mithilfe einer effizienten Set-Datenstruktur.
2
const parsed = new URL(rawUrlRef.value, window.location.origin);
Erzeugt ein natives URL-Objekt zur sicheren Analyse absoluter oder relativer Pfade bezogen auf den aktuellen Ursprung.
3
return allowedProtocols.has(parsed.protocol) ? parsed.href : '#';
Gleicht das Protokoll mit der Whitelist ab und liefert bei ungültigen Schemata einen neutralen Platzhalter zurück.