fix(javascript): resolve HTML script URLs after URL whitespace and percent decoding

An HTML script src or base href with percent-encoded letters or
surrounding whitespace was looked up literally, so an inventoried script
was reported as not-found. Apply HTML attribute and URL parser
whitespace handling, then percent-decode the path as the URL standard
does. Encoded dot and separator bytes are still rejected, and paths that
decode to NUL or non-UTF-8 bytes are rejected explicitly.

Closes #1236

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-09 13:52:55 +00:00
co-authored by Claude Opus 5.5
parent 0c6852b392
commit 502528c58d
5 changed files with 156 additions and 10 deletions
+49
View File
@@ -32,3 +32,52 @@ export const admitsCanonicalPathSyntax = (value: string): boolean =>
!value.includes("\0") &&
!value.includes("\\") &&
!/%(?:2e|2f|5c)/iu.test(value);
/** C0 controls and space, which the URL parser strips around its input. */
const isUrlTrimmed = (code: number): boolean => code <= 0x20;
/**
* The URL text a browser parses from an HTML URL attribute: HTML strips
* surrounding ASCII whitespace, and the URL parser strips surrounding C0
* controls and spaces and removes every tab and newline.
*/
export const htmlUrlText = (value: string): string => {
let start = 0;
let end = value.length;
while (start < end && isUrlTrimmed(value.charCodeAt(start))) start += 1;
while (end > start && isUrlTrimmed(value.charCodeAt(end - 1))) end -= 1;
return value.slice(start, end).replace(/[\t\n\r]/gu, "");
};
const UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
const UTF8_ENCODER = new TextEncoder();
/**
* Percent-decode a URL path as the URL standard does: valid `%XX` sequences
* become bytes and any other `%` stays literal. Returns null when the bytes
* are not UTF-8 or include NUL, because no canonical artifact path can match
* them. Callers refuse encoded dot and separator bytes before decoding.
*/
export const percentDecodeUrlPath = (value: string): string | null => {
if (!/%[0-9a-f]{2}/iu.test(value)) return value;
const bytes: number[] = [];
for (let index = 0; index < value.length;) {
const escape = value.slice(index, index + 3);
if (/^%[0-9a-f]{2}$/iu.test(escape)) {
bytes.push(Number.parseInt(escape.slice(1), 16));
index += 3;
continue;
}
const character = String.fromCodePoint(value.codePointAt(index) ?? 0);
bytes.push(...UTF8_ENCODER.encode(character));
index += character.length;
}
try {
const decoded = UTF8.decode(new Uint8Array(bytes));
return decoded.includes("\0") ? null : decoded;
} catch (cause: unknown) {
// Invalid UTF-8 cannot name an inventoried path.
void cause;
return null;
}
};