25 行
989 B
TypeScript
25 行
989 B
TypeScript
|
|
const SAFE_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);
|
||
|
|
|
||
|
|
/** Placeholder base used to resolve relative hrefs without a real origin. */
|
||
|
|
const RESOLUTION_BASE = "https://astrbot.invalid/";
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Assistant messages come from a remote AstrBot instance and are untrusted.
|
||
|
|
* Only well-known navigation protocols may reach an anchor href; anything else
|
||
|
|
* (`javascript:`, `data:`, `file:`, custom schemes) is rejected so the caller
|
||
|
|
* can render the original markdown as plain text.
|
||
|
|
*/
|
||
|
|
export function safeLinkHref(raw: string): string | null {
|
||
|
|
const candidate = raw.trim();
|
||
|
|
if (!candidate) return null;
|
||
|
|
try {
|
||
|
|
const parsed = new URL(candidate, RESOLUTION_BASE);
|
||
|
|
if (!SAFE_LINK_PROTOCOLS.has(parsed.protocol)) return null;
|
||
|
|
// Relative inputs resolve against the placeholder base and must not be
|
||
|
|
// presented as if they pointed at a real destination.
|
||
|
|
return parsed.href.startsWith(RESOLUTION_BASE) ? null : parsed.href;
|
||
|
|
} catch {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|