~james/core

core/web/src/lib/safeHref.ts -rw-r--r-- 812 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// links taken from records (repo website, profile links, .gitmodules) are written by
// whoever owns them, and svelte puts any scheme into href. only the schemes a browser
// would run as code are dropped; everything else is returned exactly as written.
// parsed with URL rather than matched as text, because browsers strip tabs, newlines
// and leading spaces first, so "java\tscript:" still runs
const EXECUTABLE = new Set(["javascript:", "vbscript:", "data:"]);

export const safeHref = (raw: string | null | undefined): string | undefined => {
	if (!raw) return undefined;
	try {
		const { protocol } = new URL(raw, "https://relative.invalid/");
		return EXECUTABLE.has(protocol) ? undefined : raw;
	} catch {
		// nothing that fails to parse can be a script url, so leave it as it was
		return raw;
	}
};