Merge pull request #1287 from morluto/fix/javascript-html-script-url-decoding
fix(javascript): resolve HTML script URLs after URL whitespace and percent decoding
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user