diff --git a/src/application/WebModuleTraceService.ts b/src/application/WebModuleTraceService.ts index aae56f0b97..d42593491d 100644 --- a/src/application/WebModuleTraceService.ts +++ b/src/application/WebModuleTraceService.ts @@ -17,7 +17,7 @@ import { jsonObjectSchema } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; import { collectWebModuleImports, - matchCapturedModules, + createCapturedModuleMatcher, } from "../domain/webModuleImports.js"; import { webModuleTraceInputSchema, @@ -204,6 +204,7 @@ export class WebModuleTraceService { ); } let literalIndex = 0; + const matchCaptured = createCapturedModuleMatcher(data.manifest.scripts); const imports: WebModuleTraceResult["imports"] = []; for (const reference of syntax.imports) { let resolved: @@ -226,9 +227,7 @@ export class WebModuleTraceService { ...reference, resolution: resolved, captured_candidates: - resolved.state === "resolved" - ? matchCapturedModules(resolved.url, data.manifest.scripts) - : [], + resolved.state === "resolved" ? matchCaptured(resolved.url) : [], execution: "unknown", }); } diff --git a/src/browser/history/HarCapture.test.ts b/src/browser/history/HarCapture.test.ts index 9632524eb1..b6c2deb493 100644 --- a/src/browser/history/HarCapture.test.ts +++ b/src/browser/history/HarCapture.test.ts @@ -8,6 +8,7 @@ import { import { decodeCaptureText } from "./CaptureJson.js"; import { CaptureFormatError } from "./CaptureFormatError.js"; import { decodeHarCapture } from "./HarCapture.js"; +import { createHarValidator } from "./HarSchema.js"; it.each([ { timings: null, field: "" }, @@ -1070,3 +1071,29 @@ it.each([ ); }, ); + +it("reuses the compiled HAR validator across failing and valid calls without error leakage", () => { + const validate = createHarValidator(); + const bad = historicalHar(); + bad.log.entries[0]!.time = -1; + expect(() => validate(bad)).toThrow("HAR schema validation failed:"); + + const good = historicalHar(); + const secondValidate = createHarValidator(); + expect(secondValidate(good)).toEqual({ + bracketedIpv6: null, + emptyServerAddress: null, + failedRequests: null, + }); + + const ipv6Doc = historicalHar(); + ipv6Doc.log.creator = { name: "Playwright", version: "1.64.1" }; + Object.assign(ipv6Doc.log.entries[0]!, { + serverIPAddress: "[2001:db8::1]", + }); + expect(secondValidate(ipv6Doc)).toEqual({ + bracketedIpv6: { producer: "Playwright 1.64.1", entries: [0] }, + emptyServerAddress: null, + failedRequests: null, + }); +}); diff --git a/src/browser/history/HarSchema.ts b/src/browser/history/HarSchema.ts index 30063351c2..7ee006b49d 100644 --- a/src/browser/history/HarSchema.ts +++ b/src/browser/history/HarSchema.ts @@ -1,10 +1,12 @@ import { createRequire } from "node:module"; import { isIP } from "node:net"; -import { Ajv } from "ajv"; +import { Ajv, type ValidateFunction } from "ajv"; import { z } from "zod"; import { CaptureFormatError } from "./CaptureFormatError.js"; import { captureObject } from "./CaptureRedaction.js"; +const REQUIRED_TIMING_FIELDS = ["send", "wait", "receive"] as const; + const durationSchema = { type: "number", minimum: 0 }; const optionalDurationSchema = { anyOf: [durationSchema, { const: -1 }], @@ -77,10 +79,9 @@ interface HarProducerAdaptations { readonly failedRequests: HarEntryAdaptation | null; } -/** Validate with pinned HAR 1.2 draft-06 schemas and the owned schema corrections. */ -export const createHarValidator = (): (( - value: unknown, -) => HarProducerAdaptations) => { +let compiledHarValidator: ValidateFunction | undefined; + +const compileHarValidator = (): ValidateFunction => { const require = createRequire(import.meta.url); const schemas = z .record(z.string(), z.record(z.string(), z.unknown())) @@ -124,6 +125,14 @@ export const createHarValidator = (): (( const validate = ajv.getSchema("har.json#"); if (validate === undefined) throw new Error("Pinned HAR root schema is unavailable"); + return validate; +}; + +/** Validate with pinned HAR 1.2 draft-06 schemas and the owned schema corrections. */ +export const createHarValidator = (): (( + value: unknown, +) => HarProducerAdaptations) => { + const validate = (compiledHarValidator ??= compileHarValidator()); return (value) => { const adaptations = allowObservedProducerRepresentations(value); if (!validate(value)) { @@ -142,6 +151,72 @@ export const createHarValidator = (): (( }; }; +const findProducerProfile = ( + name: unknown, + version: unknown, +): HarProducerProfile | undefined => { + for (let i = 0; i < HAR_PRODUCER_PROFILES.length; i += 1) { + const profile = HAR_PRODUCER_PROFILES[i]!; + if (profile.name === name && profile.version === version) return profile; + } + return undefined; +}; + +const adaptFailedTiming = ( + candidate: Record, + ordinal: number, + failedRequests: number[], +): void => { + const response = candidate.response; + const timings = candidate.timings; + if ( + !captureObject(response) || + typeof response._failureText !== "string" || + response._failureText.length === 0 || + !captureObject(timings) + ) + return; + let adapted = false; + for (let i = 0; i < REQUIRED_TIMING_FIELDS.length; i += 1) { + const field = REQUIRED_TIMING_FIELDS[i]!; + if (timings[field] === -1) { + timings[field] = 0; + adapted = true; + } + } + if (adapted) failedRequests.push(ordinal); +}; + +const adaptServerIpAddress = ( + profile: HarProducerProfile, + candidate: Record, + ordinal: number, + sets: { adaptedEntries: number[]; emptyAddressEntries: number[] }, +): void => { + const address = candidate.serverIPAddress; + if ( + profile.bracketedIpv6 && + typeof address === "string" && + address.length > 2 && + address.charCodeAt(0) === 0x5b && + address.charCodeAt(address.length - 1) === 0x5d && + !address.includes("%") + ) { + const unwrapped = address.slice(1, -1); + if (isIP(unwrapped) === 6) { + candidate.serverIPAddress = unwrapped; + sets.adaptedEntries.push(ordinal); + } + } else if (profile.emptyServerAddress && address === "") { + // DevTools writes request.remoteAddress(), which stays "" when a request + // has no remote endpoint (a failed connection, an aborted or internally + // redirected request). serverIPAddress is optional, so only the + // validation copy omits that empty value. + delete candidate.serverIPAddress; + sets.emptyAddressEntries.push(ordinal); + } +}; + /** Adapt only observed producer representations in the disposable validation copy. */ const allowObservedProducerRepresentations = ( value: unknown, @@ -155,56 +230,22 @@ const allowObservedProducerRepresentations = ( const log = value.log; const creator = log.creator; if (!captureObject(creator) || !Array.isArray(log.entries)) return none; - const profile = HAR_PRODUCER_PROFILES.find( - ({ name, version }) => creator.name === name && creator.version === version, - ); + const profile = findProducerProfile(creator.name, creator.version); if (profile === undefined) return none; const failedRequests: number[] = []; const adaptedEntries: number[] = []; const emptyAddressEntries: number[] = []; - for (const [ordinal, entry] of log.entries.entries()) { - const candidate: unknown = entry; + const addressSets = { adaptedEntries, emptyAddressEntries }; + const entries = log.entries; + for (let ordinal = 0; ordinal < entries.length; ordinal += 1) { + const candidate: unknown = entries[ordinal]; if (!captureObject(candidate)) continue; // Playwright leaves required durations at -1 when a request fails before // response timing is available. Adapt only this observed sentinel in the // disposable validation copy; the recorded values remain unchanged. - const response = candidate.response; - const timings = candidate.timings; - if ( - profile.unavailableFailedRequestTimings && - captureObject(response) && - typeof response._failureText === "string" && - response._failureText.length > 0 && - captureObject(timings) - ) { - let adapted = false; - for (const field of ["send", "wait", "receive"]) - if (timings[field] === -1) { - timings[field] = 0; - adapted = true; - } - if (adapted) failedRequests.push(ordinal); - } - const address = candidate.serverIPAddress; - if ( - profile.bracketedIpv6 && - typeof address === "string" && - address.startsWith("[") && - address.endsWith("]") && - !address.includes("%") && - isIP(address.slice(1, -1)) === 6 - ) { - candidate.serverIPAddress = address.slice(1, -1); - adaptedEntries.push(ordinal); - } - // DevTools writes request.remoteAddress(), which stays "" when a request - // has no remote endpoint (a failed connection, an aborted or internally - // redirected request). serverIPAddress is optional, so only the - // validation copy omits that empty value. - if (profile.emptyServerAddress && address === "") { - delete candidate.serverIPAddress; - emptyAddressEntries.push(ordinal); - } + if (profile.unavailableFailedRequestTimings) + adaptFailedTiming(candidate, ordinal, failedRequests); + adaptServerIpAddress(profile, candidate, ordinal, addressSets); if (!profile.nullPostDataText) continue; const request = candidate.request; if (!captureObject(request)) continue; diff --git a/src/domain/webModuleImports.test.ts b/src/domain/webModuleImports.test.ts index 2f75b85120..a78eaec285 100644 --- a/src/domain/webModuleImports.test.ts +++ b/src/domain/webModuleImports.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { collectWebModuleImports, + createCapturedModuleMatcher, matchCapturedModules, } from "./webModuleImports.js"; import { exportedWebScriptSchema } from "./webScriptExport.js"; @@ -235,3 +236,135 @@ it.each(["main.mjs", "main.js", "view.jsx"])( } }, ); + +describe("keyword-indexed traversal and indexed candidate matching", () => { + it("handles sources without module keywords and out-of-order nested dynamic imports", () => { + expect(collectWebModuleImports("const x = 1 + 2;", "main.mjs")).toEqual({ + imports: [], + state: "parsed", + diagnostics: [], + }); + expect( + collectWebModuleImports('const s = "import export";', "main.mjs").imports, + ).toEqual([]); + const nested = collectWebModuleImports( + 'import(wrap(import("./inner.js")));', + "main.mjs", + ); + expect( + nested.imports.map((item) => [item.expression, item.specifier]), + ).toEqual([ + ['wrap(import("./inner.js"))', null], + ['"./inner.js"', "./inner.js"], + ]); + + const decorated = collectWebModuleImports( + 'class C { m(@dec(import("./inner.js")) x) {} }', + "main.mjs", + ); + expect(decorated.state).toBe("parsed"); + expect( + decorated.imports.map((item) => [item.kind, item.specifier]), + ).toEqual([["dynamic-import", "./inner.js"]]); + }); + + it.each([ + [ + "TS typed parameter with default", + 'class C { m(@dec(import("./id.js")) x: any = 1) {} }', + "main.ts", + ["./id.js"], + ], + [ + "TS destructured object parameter", + 'class C { m(@dec(import("./obj.js")) { a }: any) {} }', + "main.ts", + ["./obj.js"], + ], + [ + "TS destructured object parameter with default", + 'class C { m(@dec(import("./objd.js")) { a }: any = {}) {} }', + "main.ts", + ["./objd.js"], + ], + [ + "TS setter parameter with default", + 'class C { set x(@dec(import("./setp.js")) v: any = 1) {} }', + "main.ts", + ["./setp.js"], + ], + [ + "object-literal method", + 'const o = { @dec(import("./om.js")) m() {} };', + "main.mjs", + ["./om.js"], + ], + [ + "object-literal property", + 'const o = { @dec(import("./op.js")) p: 1 };', + "main.mjs", + ["./op.js"], + ], + ])( + "retains dynamic imports inside decorators on %s", + (_label, source, path, expectedSpecifiers) => { + const result = collectWebModuleImports(source, path); + expect(result.state).toBe("parsed"); + expect(result.diagnostics).toEqual([]); + expect(result.imports.map((item) => item.specifier)).toEqual( + expectedSpecifiers, + ); + for (const item of result.imports) + expect(source.slice(item.start.offset, item.end.offset)).toBe( + item.expression, + ); + }, + ); + + it("preserves ascending script_index order across exact and fragment-stripped matches", () => { + const scripts = [ + script("https://app.test/a.js", "scenario-response"), + script("https://app.test/a.js#one", "page-script"), + script("https://app.test/a.js", "scenario-response", "b".repeat(64)), + ]; + const expected = [ + { + script_index: 0, + match: "response-url-without-fragment", + script: scripts[0], + }, + { script_index: 1, match: "exact-reported-url", script: scripts[1] }, + { + script_index: 2, + match: "response-url-without-fragment", + script: scripts[2], + }, + ]; + expect(matchCapturedModules("https://app.test/a.js#one", scripts)).toEqual( + expected, + ); + expect( + matchCapturedModules( + "https://app.test/a.js#one", + Object.freeze([...scripts]), + ), + ).toEqual(expected); + + const matcher = createCapturedModuleMatcher(scripts); + // 1st call (linear) and 2nd+ calls (indexed) must return identical order. + expect(matcher("https://app.test/a.js#one")).toEqual(expected); + expect(matcher("https://app.test/a.js#one")).toEqual(expected); + expect(matcher("https://APP.test/a.js")).toEqual([ + { + script_index: 0, + match: "response-url-without-fragment", + script: scripts[0], + }, + { + script_index: 2, + match: "response-url-without-fragment", + script: scripts[2], + }, + ]); + }); +}); diff --git a/src/domain/webModuleImports.ts b/src/domain/webModuleImports.ts index 3c6f528b91..7defda2dc5 100644 --- a/src/domain/webModuleImports.ts +++ b/src/domain/webModuleImports.ts @@ -13,6 +13,181 @@ import { semanticStaticModuleSource, } from "./javascript/javascriptModuleDeclaration.js"; +const SKIPPABLE_AST_LEAF_TYPES = new Set([ + "StringLiteral", + "NumericLiteral", + "BooleanLiteral", + "NullLiteral", + "BigIntLiteral", + "RegExpLiteral", + "ThisExpression", + "Super", + "ImportSpecifier", + "ImportDefaultSpecifier", + "ImportNamespaceSpecifier", + "ImportAttribute", + "ExportSpecifier", +]); + +const collectModuleKeywordOffsets = (source: string): number[] => { + const offsets: number[] = []; + for ( + let index = source.indexOf("import"); + index >= 0; + index = source.indexOf("import", index + 6) + ) + offsets.push(index); + for ( + let index = source.indexOf("export"); + index >= 0; + index = source.indexOf("export", index + 6) + ) + offsets.push(index); + if (offsets.length > 1) offsets.sort((a, b) => a - b); + return offsets; +}; + +const rangeContainsKeyword = ( + offsets: readonly number[], + start: number, + end: number, +): boolean => { + let lo = 0; + let hi = offsets.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (offsets[mid]! < start) lo = mid + 1; + else hi = mid; + } + return lo < offsets.length && offsets[lo]! < end; +}; + +const addImportedReference = ( + source: string, + expression: Node, + kind: WebModuleImport["kind"], + imports: WebModuleImport[], +): void => { + if ( + expression.start === null || + expression.start === undefined || + expression.end === null || + expression.end === undefined || + expression.loc === null || + expression.loc === undefined + ) + return; + let specifier: string | null; + if (expression.type === "StringLiteral") { + specifier = expression.value; + } else { + const literal = readExactJavaScriptLiteral(expression); + specifier = + literal.found && typeof literal.value === "string" ? literal.value : null; + } + imports.push({ + kind, + specifier, + expression: source.slice(expression.start, expression.end), + start: { + offset: expression.start, + line: expression.loc.start.line, + column: expression.loc.start.column, + }, + end: { + offset: expression.end, + line: expression.loc.end.line, + column: expression.loc.end.column, + }, + }); +}; + +const minDecoratorStart = (node: Node, start: number): number => { + const decorators = (node as { readonly decorators?: readonly Node[] | null }) + .decorators; + if ( + decorators === undefined || + decorators === null || + decorators.length === 0 + ) + return start; + for (let i = 0; i < decorators.length; i += 1) { + const decoratorStart = decorators[i]?.start; + if (decoratorStart != null && decoratorStart < start) + start = decoratorStart; + } + return start; +}; + +// Babel's `decorators-legacy` plugin places `node.start` after leading +// decorators on patterns, object members, and `AssignmentPattern.left`. +const effectiveNodeStart = (node: Node, nodeStart: number): number => { + let start = minDecoratorStart(node, nodeStart); + let current: Node = node; + while (current.type === "AssignmentPattern") { + current = current.left; + start = minDecoratorStart(current, start); + if (current.start != null && current.start < start) start = current.start; + } + return start; +}; + +const traverseModuleImports = ( + ast: Node, + source: string, + keywordOffsets: readonly number[], +): WebModuleImport[] => { + const imports: WebModuleImport[] = []; + let lastOffset = -1; + let needsSort = false; + const record = (kind: WebModuleImport["kind"], expression: Node): void => { + const before = imports.length; + addImportedReference(source, expression, kind, imports); + if (imports.length > before) { + const startOffset = imports[before]!.start.offset; + if (startOffset < lastOffset) needsSort = true; + lastOffset = startOffset; + } + }; + traverseJavaScriptAst(ast, { + skip: (node) => { + if (node.type === "File" || node.type === "Program") return false; + if (node.type === "Identifier" && (node.decorators?.length ?? 0) === 0) + return true; + if (SKIPPABLE_AST_LEAF_TYPES.has(node.type)) return true; + return ( + node.start != null && + node.end != null && + !rangeContainsKeyword( + keywordOffsets, + effectiveNodeStart(node, node.start), + node.end, + ) + ); + }, + enter: (node) => { + switch (node.type) { + case "ImportDeclaration": + case "ExportAllDeclaration": + case "ExportNamedDeclaration": { + const moduleSource = semanticStaticModuleSource(node); + if (moduleSource !== null) + record( + node.type === "ImportDeclaration" ? "static-import" : "re-export", + moduleSource, + ); + break; + } + case "ImportExpression": + record("dynamic-import", node.source); + break; + } + }, + }); + if (needsSort) imports.sort((a, b) => a.start.offset - b.start.offset); + return imports; +}; + /** Collect module declarations, omitting whole-statement type-only forms. */ export const collectWebModuleImports = ( source: string, @@ -29,49 +204,11 @@ export const collectWebModuleImports = ( state: "unparseable", diagnostics: ["Source could not be parsed; imports are unknown."], }; - const imports: WebModuleImport[] = []; - const add = (kind: WebModuleImport["kind"], expression: Node): void => { - if ( - expression.start === null || - expression.start === undefined || - expression.end === null || - expression.end === undefined || - expression.loc === null || - expression.loc === undefined - ) - return; - const literal = readExactJavaScriptLiteral(expression); - const specifier = - literal.found && typeof literal.value === "string" ? literal.value : null; - imports.push({ - kind, - specifier, - expression: source.slice(expression.start, expression.end), - start: { - offset: expression.start, - line: expression.loc.start.line, - column: expression.loc.start.column, - }, - end: { - offset: expression.end, - line: expression.loc.end.line, - column: expression.loc.end.column, - }, - }); - }; - traverseJavaScriptAst(ast, { - enter: (node) => { - const moduleSource = semanticStaticModuleSource(node); - if (moduleSource !== null) { - add( - node.type === "ImportDeclaration" ? "static-import" : "re-export", - moduleSource, - ); - } else if (node.type === "ImportExpression") - add("dynamic-import", node.source); - }, - }); - imports.sort((a, b) => a.start.offset - b.start.offset); + const keywordOffsets = collectModuleKeywordOffsets(source); + const imports = + keywordOffsets.length > 0 + ? traverseModuleImports(ast, source, keywordOffsets) + : []; const loaderCondition = javaScriptSourceLoaderCondition(ast.program); return { imports, @@ -79,37 +216,173 @@ export const collectWebModuleImports = ( diagnostics: [ ...(loaderCondition === undefined ? [] : [loaderCondition]), ...(ast.errors?.map((error) => error.message) ?? []), - ...(hasUncertainTypeOnlyModuleSideEffect(ast.program) + ...(keywordOffsets.length > 0 && + hasUncertainTypeOnlyModuleSideEffect(ast.program) ? [TYPE_ONLY_MODULE_SIDE_EFFECT_LIMITATION] : []), ], }; }; +export interface CapturedModuleCandidate { + readonly script_index: number; + readonly match: "exact-reported-url" | "response-url-without-fragment"; + readonly script: ExportedWebScript; +} + +interface CapturedModuleIndex { + readonly byUrl: Map; + readonly responseByUrl: Map; +} + +const pushIndex = ( + map: Map, + key: string, + index: number, +): void => { + let bucket = map.get(key); + if (bucket === undefined) { + bucket = []; + map.set(key, bucket); + } + bucket.push(index); +}; + +const buildCapturedModuleIndex = ( + scripts: readonly ExportedWebScript[], +): CapturedModuleIndex => { + const byUrl = new Map(); + const responseByUrl = new Map(); + for (let i = 0; i < scripts.length; i += 1) { + const script = scripts[i]!; + pushIndex(byUrl, script.url, i); + if (script.source.kind === "scenario-response") + pushIndex(responseByUrl, script.url, i); + } + return { byUrl, responseByUrl }; +}; + +const normalizedResponseUrl = (url: string): string | undefined => { + const transport = URL.parse(url); + if (transport === null) return undefined; + transport.hash = ""; + return transport.href; +}; + +const matchLinear = ( + url: string, + scripts: readonly ExportedWebScript[], +): CapturedModuleCandidate[] => { + const candidates: CapturedModuleCandidate[] = []; + let transportHref: string | undefined; + let transportParsed = false; + for (let script_index = 0; script_index < scripts.length; script_index += 1) { + const script = scripts[script_index]!; + if (script.url === url) { + candidates.push({ script_index, match: "exact-reported-url", script }); + continue; + } + if (script.source.kind !== "scenario-response") continue; + if (!transportParsed) { + transportParsed = true; + transportHref = normalizedResponseUrl(url); + } + if (transportHref === script.url) + candidates.push({ + script_index, + match: "response-url-without-fragment", + script, + }); + } + return candidates; +}; + +const matchIndexed = ( + url: string, + scripts: readonly ExportedWebScript[], + index: CapturedModuleIndex, +): CapturedModuleCandidate[] => { + const exactIndices = index.byUrl.get(url); + let responseIndices: readonly number[] | undefined; + if (index.responseByUrl.size > 0) { + const normalized = normalizedResponseUrl(url); + if (normalized !== undefined && normalized !== url) + responseIndices = index.responseByUrl.get(normalized); + } + if (exactIndices === undefined && responseIndices === undefined) return []; + if (responseIndices === undefined) + return exactIndices!.map((script_index) => ({ + script_index, + match: "exact-reported-url", + script: scripts[script_index]!, + })); + if (exactIndices === undefined) + return responseIndices.map((script_index) => ({ + script_index, + match: "response-url-without-fragment", + script: scripts[script_index]!, + })); + const candidates: CapturedModuleCandidate[] = []; + let ei = 0; + let ri = 0; + while (ei < exactIndices.length && ri < responseIndices.length) { + const eIdx = exactIndices[ei]!; + const rIdx = responseIndices[ri]!; + if (eIdx < rIdx) { + candidates.push({ + script_index: eIdx, + match: "exact-reported-url", + script: scripts[eIdx]!, + }); + ei += 1; + } else { + candidates.push({ + script_index: rIdx, + match: "response-url-without-fragment", + script: scripts[rIdx]!, + }); + ri += 1; + } + } + while (ei < exactIndices.length) { + const script_index = exactIndices[ei++]!; + candidates.push({ + script_index, + match: "exact-reported-url", + script: scripts[script_index]!, + }); + } + while (ri < responseIndices.length) { + const script_index = responseIndices[ri++]!; + candidates.push({ + script_index, + match: "response-url-without-fragment", + script: scripts[script_index]!, + }); + } + return candidates; +}; + +/** Create a reusable matcher for repeated queries against one captured script inventory. */ +export const createCapturedModuleMatcher = ( + scripts: readonly ExportedWebScript[], +): ((url: string) => CapturedModuleCandidate[]) => { + let index: CapturedModuleIndex | undefined; + let lookups = 0; + return (url) => { + if (scripts.length === 0) return []; + if (lookups === 0) { + lookups = 1; + return matchLinear(url, scripts); + } + index ??= buildCapturedModuleIndex(scripts); + return matchIndexed(url, scripts, index); + }; +}; + /** Match reported URLs without collapsing query or module fragment identity. */ export const matchCapturedModules = ( url: string, scripts: readonly ExportedWebScript[], -) => { - const transport = URL.parse(url); - if (transport !== null) transport.hash = ""; - const candidates: { - script_index: number; - match: "exact-reported-url" | "response-url-without-fragment"; - script: ExportedWebScript; - }[] = []; - scripts.forEach((script, script_index) => { - if (script.url === url) - candidates.push({ script_index, match: "exact-reported-url", script }); - else if ( - script.source.kind === "scenario-response" && - transport?.href === script.url - ) - candidates.push({ - script_index, - match: "response-url-without-fragment", - script, - }); - }); - return candidates; -}; +): CapturedModuleCandidate[] => + scripts.length === 0 ? [] : matchLinear(url, scripts); diff --git a/src/evm/SolidityMetadata.test.ts b/src/evm/SolidityMetadata.test.ts index 5a5bf22a6e..d6bbd9f1b7 100644 --- a/src/evm/SolidityMetadata.test.ts +++ b/src/evm/SolidityMetadata.test.ts @@ -206,3 +206,49 @@ it.each(["", "60006000f3", "000000", "00010001"])( entries: [], }), ); + +it("keeps distinct scalar key types separate and validates large ASCII/UTF-8 metadata maps", () => { + // Map keys: text "1" (6131), uint 1 (01), bytes h'31' (4131), true (f5), false (f4), null (f6) + const distinct = inspectSolidityMetadata( + bytecode("a66131010102413103f504f405f606"), + ); + expect(distinct.status).toBe("decoded"); + expect(distinct.entries.map(({ key }) => key)).toEqual([ + { kind: "text", value: "1" }, + { kind: "integer", value: "1" }, + { kind: "bytes", value: "31" }, + { kind: "boolean", value: true }, + { kind: "boolean", value: false }, + { kind: "null" }, + ]); + + // Repeated scalar keys of each kind must still fail with repeated_map_key. + for (const hex of ["a2f501f502", "a2f601f602", "a201010102"]) { + expect(inspectSolidityMetadata(bytecode(hex))).toMatchObject({ + status: "not-decoded", + diagnostic: "repeated_map_key", + admission: { code: "repeated_map_key" }, + }); + } + + // Valid non-ASCII UTF-8 text (e.g. 2-byte Γ©) alongside ASCII + solc + bytes. + const utf8Hex = "a364736f6c634300081e62c3a962c3a9636b657944deadbeef"; + expect(inspectSolidityMetadata(bytecode(utf8Hex))).toMatchObject({ + status: "decoded", + compiler_version: { representation: "release-bytes", value: "0.8.30" }, + entries: [ + { + key: { kind: "text", value: "solc" }, + value: { kind: "bytes", value: "00081e" }, + }, + { + key: { kind: "text", value: "Γ©" }, + value: { kind: "text", value: "Γ©" }, + }, + { + key: { kind: "text", value: "key" }, + value: { kind: "bytes", value: "deadbeef" }, + }, + ], + }); +}); diff --git a/src/evm/SolidityMetadata.ts b/src/evm/SolidityMetadata.ts index f7b9e1af7f..8caba769c6 100644 --- a/src/evm/SolidityMetadata.ts +++ b/src/evm/SolidityMetadata.ts @@ -18,77 +18,120 @@ const decodeOptions = { allowInfinity: false, allowNaN: false, rejectDuplicateMapKeys: false, - retainStringBytes: true, + retainStringBytes: false, } as const; +const uint8ArrayToHex = (bytes: Uint8Array): string => + Buffer.isBuffer(bytes) + ? bytes.toString("hex") + : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString( + "hex", + ); + +const stringPrefixBytes = (minor: number): number => { + if (minor < 24) return 1; + if (minor === 24) return 2; + if (minor === 25) return 3; + if (minor === 26) return 5; + if (minor === 27) return 9; + return -1; +}; + +const decodeStrictTokenText = ( + data: Uint8Array, + startPos: number, + token: Token, +): void => { + const encodedLength = token.encodedLength; + const prefix = + startPos < data.length ? stringPrefixBytes(data[startPos]! & 31) : -1; + if (encodedLength === undefined || prefix < 0) + throw new EvmAdmissionError("text_bytes_unavailable"); + const byteLength = encodedLength - prefix; + const text = token.value as string; + // cborg uses non-fatal TextDecoder and may strip BOM; pure ASCII is exact + // whenever byte length matches UTF-16 length and has no U+FFFD. + if (byteLength !== text.length || text.includes("\uFFFD")) + token.value = utf8.decode( + data.subarray(startPos + prefix, startPos + encodedLength), + ); +}; + +const fastScalarKey = (value: unknown): string => { + if (typeof value === "string") return `s:${value}`; + if (typeof value === "bigint") return `i:${value.toString()}`; + if (typeof value === "number" && Number.isSafeInteger(value)) + return `i:${String(value)}`; + if (typeof value === "boolean") return value ? "T" : "F"; + if (value === null) return "N"; + if (value instanceof Uint8Array) return `b:${uint8ArrayToHex(value)}`; + throw new EvmAdmissionError("value_outside_profile"); +}; + /** Bound recursive decoder entry before collection interpretation/allocation. */ class BoundedMetadataTokenizer extends Tokenizer { readonly remaining: number[] = []; readonly #mapKeys: Array | undefined> = []; + hasContainerKey = false; + constructor(bytes: Uint8Array) { super(bytes, decodeOptions); } override next(): Token { - while (this.remaining.at(-1) === 0) { + while ( + this.remaining.length > 0 && + this.remaining[this.remaining.length - 1] === 0 + ) { this.remaining.pop(); this.#mapKeys.pop(); } + const startPos = this.pos(); const token = super.next(); - if ( - Type.equals(token.type, Type.tag) || - Type.equals(token.type, Type.float) - ) + const type = token.type; + if (Type.equals(type, Type.tag) || Type.equals(type, Type.float)) throw new EvmAdmissionError("tag_or_float"); - if (Type.equals(token.type, Type.string)) { - if (token.byteValue !== undefined) - token.value = utf8.decode(token.byteValue); - // cborg answers the shortest-form empty text (0x60) with a shared token that has no - // bytes; it can only mean "", which is already its value. - else if (token.value !== "" || token.encodedLength !== 1) - throw new EvmAdmissionError("text_bytes_unavailable"); - } - const parent = this.remaining.length - 1; - const mapKeys = parent >= 0 ? this.#mapKeys[parent] : undefined; - const onKey = - mapKeys !== undefined && parent >= 0 && this.remaining[parent]! % 2 === 0; - if (parent >= 0) this.remaining[parent]!--; - if ( - onKey && - mapKeys !== undefined && - !Type.equals(token.type, Type.map) && - !Type.equals(token.type, Type.array) - ) { - const identity = keyIdentity(token.value); - if (mapKeys.has(identity)) throw repeatedMapKey(identity); - mapKeys.add(identity); - } - if ( - Type.equals(token.type, Type.map) || - Type.equals(token.type, Type.array) - ) { - const count: unknown = token.value; - const children = - typeof count === "number" - ? count * (Type.equals(token.type, Type.map) ? 2 : 1) - : NaN; - if ( - !Number.isSafeInteger(children) || - children < 0 || - children > this.data.length - ) - throw new EvmAdmissionError("collection_exceeds_bound"); - if (this.remaining.length >= MAX_DEPTH) - throw new EvmAdmissionError("nesting_exceeds_profile", { - max_depth: MAX_DEPTH, - }); - this.#mapKeys.push( - Type.equals(token.type, Type.map) ? new Set() : undefined, - ); - this.remaining.push(children); - } + if (Type.equals(type, Type.string)) + decodeStrictTokenText(this.data, startPos, token); + const isMap = Type.equals(type, Type.map); + const isArray = !isMap && Type.equals(type, Type.array); + this.#trackMapKey(token, isMap, isArray); + if (isMap || isArray) this.#enterCollection(token, isMap); return token; } + + #trackMapKey(token: Token, isMap: boolean, isArray: boolean): void { + const parent = this.remaining.length - 1; + if (parent < 0) return; + const mapKeys = this.#mapKeys[parent]; + const onKey = mapKeys !== undefined && this.remaining[parent]! % 2 === 0; + this.remaining[parent]!--; + if (!onKey || mapKeys === undefined) return; + if (isMap || isArray) { + this.hasContainerKey = true; + return; + } + const fast = fastScalarKey(token.value); + if (mapKeys.has(fast)) throw repeatedMapKey(keyIdentity(token.value)); + mapKeys.add(fast); + } + + #enterCollection(token: Token, isMap: boolean): void { + const count: unknown = token.value; + const children = typeof count === "number" ? count * (isMap ? 2 : 1) : NaN; + if ( + !Number.isSafeInteger(children) || + children < 0 || + children > this.data.length + ) + throw new EvmAdmissionError("collection_exceeds_bound"); + if (this.remaining.length >= MAX_DEPTH) + throw new EvmAdmissionError("nesting_exceeds_profile", { + max_depth: MAX_DEPTH, + }); + this.#mapKeys.push(isMap ? new Set() : undefined); + this.remaining.push(children); + } } const scalar = (value: unknown): SolidityMetadataScalar => { @@ -100,7 +143,7 @@ const scalar = (value: unknown): SolidityMetadataScalar => { if (typeof value === "boolean") return { kind: "boolean", value }; if (value === null) return { kind: "null" }; if (value instanceof Uint8Array) - return { kind: "bytes", value: Buffer.from(value).toString("hex") }; + return { kind: "bytes", value: uint8ArrayToHex(value) }; if (value instanceof Map) return { kind: "uninterpreted", container: "map" }; if (Array.isArray(value)) return { kind: "uninterpreted", container: "array" }; @@ -191,33 +234,36 @@ export const inspectSolidityMetadata = ( cbor_bytes: length, }; try { + const tokenizer = new BoundedMetadataTokenizer(selected); const raw: unknown = decode(selected, { ...decodeOptions, - tokenizer: new BoundedMetadataTokenizer(selected), + tokenizer, }); if (!(raw instanceof Map)) throw new EvmAdmissionError("root_not_map"); - validateMapKeys(raw); + if (tokenizer.hasContainerKey) validateMapKeys(raw); // cborg compares Map keys by identity, so repeated byte-string or container // keys (each its own object) pass its duplicate check; compare by value at // every map boundary before projecting any entries. + let hasUninterpreted = false; for (const [key, value] of raw as Map) { - result.entries.push({ key: scalar(key), value: scalar(value) }); + const projectedKey = scalar(key); + const projectedValue = scalar(value); + if ( + projectedKey.kind === "uninterpreted" || + projectedValue.kind === "uninterpreted" + ) + hasUninterpreted = true; + result.entries.push({ key: projectedKey, value: projectedValue }); } - result.status = result.entries.some( - ({ key, value }) => - key.kind === "uninterpreted" || value.kind === "uninterpreted", - ) - ? "partial" - : "decoded"; - result.diagnostic = - result.status === "partial" - ? "Nested containers are uninterpreted; their exact bytes remain at the recorded range in original bytecode." - : null; + result.status = hasUninterpreted ? "partial" : "decoded"; + result.diagnostic = hasUninterpreted + ? "Nested containers are uninterpreted; their exact bytes remain at the recorded range in original bytecode." + : null; const version: unknown = raw.get("solc"); if (version instanceof Uint8Array && version.length === 3) result.compiler_version = { representation: "release-bytes", - value: [...version].join("."), + value: `${version[0]}.${version[1]}.${version[2]}`, }; else if (typeof version === "string" && version.length > 0) result.compiler_version = { diff --git a/src/frida/FridaInstrumentationManager.test.ts b/src/frida/FridaInstrumentationManager.test.ts index 8981e61401..d812b81475 100644 --- a/src/frida/FridaInstrumentationManager.test.ts +++ b/src/frida/FridaInstrumentationManager.test.ts @@ -2053,3 +2053,173 @@ it.each([{}, { session_bytes: 12345 }, { session_bytes: -1 }])( ); }, ); + +it("accounts exact JSON byte charges across unicode, surrogates, control chars, and binary data", async () => { + const token = "secret-tok"; + const bindings = new FakeDeviceManager(); + const manager = new FridaInstrumentationManager({ deviceManager: bindings }); + onTestFinished(() => manager.closeAll()); + const started = await manager.startSession({ + mode: "attach", + remote: { address: "127.0.0.1:27042", token }, + pid: 512, + }); + if (!started.ok) throw started.error; + const loaded = await manager.loadScript(started.value.sessionId, { + sourceKind: "inline", + source: "send('probe');", + }); + if (!loaded.ok) throw loaded.error; + const script = bindings.device.session.scripts[0]!; + // Emit a rich message exercising 0x7f (DEL, 1 JSON byte), control chars, + // 2/3-byte UTF-8, surrogate pair (πŸ˜€), lone surrogate, secret redaction, + // nested arrays/objects, line/column numbers, and base64 binary data. + const richPayload = { + del: "\x7f", + ctrl: '\x00\n"\\', + utf8: "Γ©δΈ­πŸ˜€\ud800", + list: [1, true, null, { [token]: "keep" }], + secretText: `before-${token}-after`, + }; + script.message.emit( + { + type: "error", + payload: richPayload, + description: `err ${token} \x7f πŸ˜€`, + stack: "stack line 1", + fileName: "hook.js", + lineNumber: 42, + columnNumber: 7, + }, + Buffer.from([1, 2, 3, 4]), + ); + const loadedObserved = manager.status(started.value.sessionId)?.messages[0]; + const loadedCharge = Buffer.byteLength(JSON.stringify(loadedObserved)); + const firstObserved = manager.status(started.value.sessionId) + ?.messages[1] as Record; + expect(firstObserved.payload).toEqual({ + del: "\x7f", + ctrl: '\x00\n"\\', + utf8: "Γ©δΈ­πŸ˜€\ud800", + list: [1, true, null, { "[redacted]": "keep" }], + secretText: "before-[redacted]-after", + }); + expect(firstObserved.description).toBe("err [redacted] \x7f πŸ˜€"); + expect(firstObserved.data_base64).toBe( + Buffer.from([1, 2, 3, 4]).toString("base64"), + ); + + // Verify exact byte-for-byte charge parity above MAX_MESSAGE_METADATA_BYTES (128 KiB): + // emit 9 copies of a 20 KiB message (~185 KiB total, each < remaining per-message budget) + // so at `exactFit`, all messages stay untruncated; at `exactFit - 1`, the first is evicted. + const paddedPayload = { ...richPayload, pad: "x".repeat(20_000) }; + script.message.emit( + { + type: "error", + payload: paddedPayload, + description: `err ${token} \x7f πŸ˜€`, + stack: "stack line 1", + fileName: "hook.js", + lineNumber: 42, + columnNumber: 7, + }, + Buffer.from([1, 2, 3, 4]), + ); + const paddedObserved = manager.status(started.value.sessionId)?.messages[2]; + const paddedCharge = Buffer.byteLength(JSON.stringify(paddedObserved)); + const secondMessageCharge = Buffer.byteLength( + JSON.stringify({ + script_id: loaded.value.scriptId, + type: "send", + payload: "ok", + }), + ); + const copies = 9; + const exactFit = loadedCharge + copies * paddedCharge + secondMessageCharge; + + for (const [sessionBytes, expectedCount, expectedTruncated] of [ + [exactFit, copies + 2, false], + [exactFit - 1, copies + 1, true], + ] as const) { + const tightBindings = new FakeDeviceManager(); + const tightManager = new FridaInstrumentationManager({ + deviceManager: tightBindings, + }); + onTestFinished(() => tightManager.closeAll()); + const tightSession = await tightManager.startSession({ + mode: "attach", + remote: { address: "127.0.0.1:27042", token }, + pid: 512, + captureLimits: { session_bytes: sessionBytes }, + }); + if (!tightSession.ok) throw tightSession.error; + const tightLoad = await tightManager.loadScript( + tightSession.value.sessionId, + { + sourceKind: "inline", + source: "send('probe');", + }, + ); + if (!tightLoad.ok) throw tightLoad.error; + const tightScript = tightBindings.device.session.scripts[0]!; + for (let i = 0; i < copies; i += 1) { + tightScript.message.emit( + { + type: "error", + payload: paddedPayload, + description: `err ${token} \x7f πŸ˜€`, + stack: "stack line 1", + fileName: "hook.js", + lineNumber: 42, + columnNumber: 7, + }, + Buffer.from([1, 2, 3, 4]), + ); + } + tightScript.message.emit({ type: "send", payload: "ok" }, null); + const tightStatus = tightManager.status(tightSession.value.sessionId)!; + expect(tightStatus.messages).toHaveLength(expectedCount); + expect(tightStatus.messagesTruncated).toBe(expectedTruncated); + } +}); + +it("evicts at exact session_bytes charge parity with Buffer.byteLength(JSON.stringify)", async () => { + const bindings = new FakeDeviceManager(); + const manager = new FridaInstrumentationManager({ deviceManager: bindings }); + onTestFinished(() => manager.closeAll()); + const started = await manager.startSession({ + mode: "attach", + pid: 512, + captureLimits: { session_bytes: 65_536 }, + }); + if (!started.ok) throw started.error; + const loaded = await manager.loadScript(started.value.sessionId, { + sourceKind: "inline", + source: "send('base');", + }); + if (!loaded.ok) throw loaded.error; + const script = bindings.device.session.scripts[0]!; + // Fill budget with messages containing non-ASCII, DEL, surrogates, and binary data. + for (let i = 0; i < 40; i += 1) { + script.message.emit( + { + type: "error", + description: `d_${i}_\x7f_Γ©_πŸ˜€`, + stack: "s".repeat(1200), + fileName: "a.js", + lineNumber: i, + columnNumber: 1, + payload: { i, text: "p".repeat(1200) }, + }, + Buffer.alloc(256, i), + ); + } + const status = manager.status(started.value.sessionId)!; + expect(status.messagesTruncated).toBe(true); + const totalJsonBytes = status.messages.reduce( + (sum, msg) => sum + Buffer.byteLength(JSON.stringify(msg)), + 0, + ); + expect(totalJsonBytes).toBeLessThanOrEqual(65_536); + expect(totalJsonBytes).toBeGreaterThan(60_000); +}); diff --git a/src/frida/FridaInstrumentationManager.ts b/src/frida/FridaInstrumentationManager.ts index 9c6ea239b8..aadee842e1 100644 --- a/src/frida/FridaInstrumentationManager.ts +++ b/src/frida/FridaInstrumentationManager.ts @@ -37,7 +37,10 @@ import { import { AnalysisError } from "../domain/analysisErrorBase.js"; import { isValidFridaRemoteAddress } from "../domain/fridaRemoteAddress.js"; import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js"; -import { explicitValueSpans } from "../domain/explicitSensitiveValues.js"; +import { + explicitValueSpans, + explicitValuesOccurIn, +} from "../domain/explicitSensitiveValues.js"; import { providerCleanupErrorFromFailures } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { AnalysisCleanupLease } from "../resources/index.js"; @@ -102,6 +105,7 @@ interface PendingStartupCleanup extends ManagedRemoteConnection { interface ManagedSession extends ManagedRemoteConnection { readonly captureLimits: FridaCapturePolicy; + readonly secrets: readonly string[]; readonly id: string; readonly device: Device; readonly session: Session; @@ -358,6 +362,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { const managed: ManagedSession = { id, captureLimits: policy.data, + secrets: remoteSecrets(input.remote), device, deviceManager: manager, remote: input.remote, @@ -1094,141 +1099,16 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { message: FridaMessage, data: Buffer | null, ): void { - const limits = managed.captureLimits; - const payload = message.payload; - const secrets = [managed.remote?.token, managed.remote?.certificate].filter( - (value): value is string => value !== undefined && value.length > 0, - ); - let payloadResult: - | { - readonly value: JsonValue; - readonly truncated: boolean; - readonly bytes: number; - readonly limit?: FridaOwnedCaptureLimit; - } - | undefined; - if (payload !== undefined) { - try { - payloadResult = boundedJsonValue( - payload, - Math.max(0, limits.session_bytes - MAX_MESSAGE_METADATA_BYTES), - secrets, - limits, - ); - } catch { - payloadResult = { - value: { payload_unavailable: true }, - truncated: true, - bytes: Buffer.byteLength('{"payload_unavailable":true}'), - limit: "unrepresentable", - }; - } - } - let binaryResult: Record = {}; - if (data !== null) { - const payloadBytes = payloadResult?.bytes ?? 0; - const remainingMessageBytes = Math.max( - 0, - limits.session_bytes - MAX_MESSAGE_METADATA_BYTES - payloadBytes - 4096, - ); - const messageBinaryLimit = Math.floor((remainingMessageBytes * 3) / 4); - if (secrets.some((secret) => data.includes(secret, 0, "utf8"))) { - binaryResult = { data_redacted: true }; - } else if (data.byteLength > messageBinaryLimit) { - binaryResult = { - data_truncated: true, - data_bytes: data.byteLength, - data_capture_limit: "session_bytes", - }; - markMessageTruncated(managed, scriptId); - } else { - binaryResult = { data_base64: data.toString("base64") }; - } - } - const type = boundedRedactedString( - message.type, - limits.message_type_bytes, - secrets, - ); - const description = - message.description === undefined - ? undefined - : boundedRedactedString( - message.description, - limits.message_text_bytes, - secrets, - ); - const stack = - message.stack === undefined - ? undefined - : boundedRedactedString( - message.stack, - limits.message_text_bytes, - secrets, - ); - const fileName = - message.fileName === undefined - ? undefined - : boundedRedactedString( - message.fileName, - limits.message_text_bytes, - secrets, - ); - const observation: JsonValue = { - script_id: scriptId, - type: type.value, - ...(type.truncated ? { type_truncated: true } : {}), - ...(payloadResult === undefined - ? {} - : { - payload: payloadResult.value, - ...(payloadResult.truncated - ? { - payload_truncated: true, - ...(payloadResult.limit === undefined - ? {} - : { payload_capture_limit: payloadResult.limit }), - } - : {}), - }), - ...(description === undefined - ? {} - : { - description: description.value, - ...(description.truncated ? { description_truncated: true } : {}), - }), - ...(stack === undefined - ? {} - : { - stack: stack.value, - ...(stack.truncated ? { stack_truncated: true } : {}), - }), - ...(fileName === undefined - ? {} - : { - file_name: fileName.value, - ...(fileName.truncated ? { file_name_truncated: true } : {}), - }), - ...(typeof message.lineNumber === "number" && - Number.isSafeInteger(message.lineNumber) && - message.lineNumber >= 0 - ? { line_number: message.lineNumber } - : {}), - ...(typeof message.columnNumber === "number" && - Number.isSafeInteger(message.columnNumber) && - message.columnNumber >= 0 - ? { column_number: message.columnNumber } - : {}), - ...binaryResult, - }; - const charge = Buffer.byteLength(JSON.stringify(observation)); - if (charge > limits.session_bytes) { + const built = buildCapturedObservation(managed, scriptId, message, data); + if (built.binaryTruncated) markMessageTruncated(managed, scriptId); + const { observation, charge } = built; + if (charge > managed.captureLimits.session_bytes) { markMessageTruncated(managed, scriptId); return; } while ( managed.messages.size > 0 && - managed.capturedBytes + charge > limits.session_bytes + managed.capturedBytes + charge > managed.captureLimits.session_bytes ) { const removed = managed.messages.shift(); if (removed !== undefined) { @@ -1389,65 +1269,476 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { } } -/** Redact declared values, then keep what fits `maximumBytes` of JSON string body. */ +const FIELD_PREFIX_BYTES = { + base: Buffer.byteLength('{"script_id":}'), + type: Buffer.byteLength(',"type":'), + typeTruncated: Buffer.byteLength(',"type_truncated":true'), + payload: Buffer.byteLength(',"payload":'), + payloadTruncated: Buffer.byteLength(',"payload_truncated":true'), + payloadLimit: Buffer.byteLength(',"payload_capture_limit":'), + description: Buffer.byteLength(',"description":'), + descriptionTruncated: Buffer.byteLength(',"description_truncated":true'), + stack: Buffer.byteLength(',"stack":'), + stackTruncated: Buffer.byteLength(',"stack_truncated":true'), + fileName: Buffer.byteLength(',"file_name":'), + fileNameTruncated: Buffer.byteLength(',"file_name_truncated":true'), + lineNumber: Buffer.byteLength(',"line_number":'), + columnNumber: Buffer.byteLength(',"column_number":'), + dataRedacted: Buffer.byteLength(',"data_redacted":true'), + dataTruncatedPrefix: Buffer.byteLength( + ',"data_truncated":true,"data_bytes":', + ), + dataTruncatedSuffix: Buffer.byteLength( + ',"data_capture_limit":"session_bytes"', + ), + dataBase64: Buffer.byteLength(',"data_base64":'), +} as const; + +const PAYLOAD_UNAVAILABLE_BYTES = Buffer.byteLength( + '{"payload_unavailable":true}', +); + +const remoteSecrets = (remote?: FridaRemoteConnection): readonly string[] => { + const secrets: string[] = []; + if (remote?.token !== undefined && remote.token.length > 0) + secrets.push(remote.token); + if (remote?.certificate !== undefined && remote.certificate.length > 0) + secrets.push(remote.certificate); + return secrets; +}; + +const captureBoundedPayload = ( + payload: unknown, + limits: FridaCapturePolicy, + secrets: readonly string[], +): BoundedJson | undefined => { + if (payload === undefined) return undefined; + try { + return boundedJsonValue( + payload, + Math.max(0, limits.session_bytes - MAX_MESSAGE_METADATA_BYTES), + secrets, + limits, + ); + } catch { + return { + value: { payload_unavailable: true }, + truncated: true, + bytes: PAYLOAD_UNAVAILABLE_BYTES, + limit: "unrepresentable", + }; + } +}; + +const captureBinaryData = ( + data: Buffer | null, + payloadBytes: number, + limits: FridaCapturePolicy, + secrets: readonly string[], +): { + readonly fields: Record; + readonly bytes: number; + readonly truncated: boolean; +} => { + if (data === null) return { fields: {}, bytes: 0, truncated: false }; + const remainingMessageBytes = Math.max( + 0, + limits.session_bytes - MAX_MESSAGE_METADATA_BYTES - payloadBytes - 4096, + ); + const messageBinaryLimit = Math.floor((remainingMessageBytes * 3) / 4); + if (secrets.some((secret) => data.includes(secret, 0, "utf8"))) { + return { + fields: { data_redacted: true }, + bytes: FIELD_PREFIX_BYTES.dataRedacted, + truncated: false, + }; + } + if (data.byteLength > messageBinaryLimit) { + return { + fields: { + data_truncated: true, + data_bytes: data.byteLength, + data_capture_limit: "session_bytes", + }, + bytes: + FIELD_PREFIX_BYTES.dataTruncatedPrefix + + String(data.byteLength).length + + FIELD_PREFIX_BYTES.dataTruncatedSuffix, + truncated: true, + }; + } + const encoded = data.toString("base64"); + return { + fields: { data_base64: encoded }, + bytes: FIELD_PREFIX_BYTES.dataBase64 + 2 + encoded.length, + truncated: false, + }; +}; + +const REDACTED_MARKER = "[redacted]"; +const REDACTED_BODY_BYTES = 10; + +const CONTROL_CHAR_JSON_BYTES = (unit: number): number => + unit === 0x08 || + unit === 0x09 || + unit === 0x0a || + unit === 0x0c || + unit === 0x0d + ? 2 + : 6; + +const jsonCharByteSize = ( + input: string, + cursor: number, +): { readonly charBytes: number; readonly step: number } => { + const unit = input.charCodeAt(cursor); + if (unit >= 0x20 && unit < 0x80) + return { charBytes: unit === 0x22 || unit === 0x5c ? 2 : 1, step: 1 }; + if (unit < 0x20) return { charBytes: CONTROL_CHAR_JSON_BYTES(unit), step: 1 }; + if (unit < 0x800) return { charBytes: 2, step: 1 }; + if (unit >= 0xd800 && unit <= 0xdbff) { + const next = input.charCodeAt(cursor + 1); + return next >= 0xdc00 && next <= 0xdfff + ? { charBytes: 4, step: 2 } + : { charBytes: 6, step: 1 }; + } + return { + charBytes: unit >= 0xdc00 && unit <= 0xdfff ? 6 : 3, + step: 1, + }; +}; + +const scanBoundedJsonBody = ( + input: string, + start: number, + end: number, + remainingBytes: number, +): { readonly cursor: number; readonly bytes: number } => { + let cursor = start; + let bytes = 0; + while (cursor < end) { + const { charBytes, step } = jsonCharByteSize(input, cursor); + if (cursor + step > end || bytes + charBytes > remainingBytes) break; + bytes += charBytes; + cursor += step; + } + return { cursor, bytes }; +}; + +const isSafeNonNegativeInt = (value: unknown): value is number => + typeof value === "number" && Number.isSafeInteger(value) && value >= 0; + +const assignTextField = ( + target: Record, + key: string, + field: BoundedRedactedText | undefined, + prefixBytes: number, + truncatedBytes: number, +): number => { + if (field === undefined) return 0; + target[key] = field.value; + if (!field.truncated) return prefixBytes + field.bytes; + target[`${key}_truncated`] = true; + return prefixBytes + field.bytes + truncatedBytes; +}; + +const assignPayloadField = ( + target: Record, + payload: BoundedJson | undefined, +): number => { + if (payload === undefined) return 0; + target.payload = payload.value; + let bytes = FIELD_PREFIX_BYTES.payload + payload.bytes; + if (!payload.truncated) return bytes; + target.payload_truncated = true; + bytes += FIELD_PREFIX_BYTES.payloadTruncated; + if (payload.limit !== undefined) { + target.payload_capture_limit = payload.limit; + bytes += FIELD_PREFIX_BYTES.payloadLimit + 2 + payload.limit.length; + } + return bytes; +}; + +const buildCapturedObservation = ( + managed: ManagedSession, + scriptId: string, + message: FridaMessage, + data: Buffer | null, +): { + readonly observation: JsonValue; + readonly charge: number; + readonly binaryTruncated: boolean; +} => { + const limits = managed.captureLimits; + const secrets = managed.secrets; + const payload = captureBoundedPayload(message.payload, limits, secrets); + const binary = captureBinaryData(data, payload?.bytes ?? 0, limits, secrets); + const type = boundedRedactedString( + message.type, + limits.message_type_bytes, + secrets, + ); + const description = + message.description === undefined + ? undefined + : boundedRedactedString( + message.description, + limits.message_text_bytes, + secrets, + ); + const stack = + message.stack === undefined + ? undefined + : boundedRedactedString( + message.stack, + limits.message_text_bytes, + secrets, + ); + const fileName = + message.fileName === undefined + ? undefined + : boundedRedactedString( + message.fileName, + limits.message_text_bytes, + secrets, + ); + const observation: Record = { + script_id: scriptId, + type: type.value, + ...(type.truncated ? { type_truncated: true } : {}), + }; + let charge = + FIELD_PREFIX_BYTES.base + + jsonStringByteLength(scriptId) + + FIELD_PREFIX_BYTES.type + + type.bytes + + (type.truncated ? FIELD_PREFIX_BYTES.typeTruncated : 0); + charge += assignPayloadField(observation, payload); + charge += assignTextField( + observation, + "description", + description, + FIELD_PREFIX_BYTES.description, + FIELD_PREFIX_BYTES.descriptionTruncated, + ); + charge += assignTextField( + observation, + "stack", + stack, + FIELD_PREFIX_BYTES.stack, + FIELD_PREFIX_BYTES.stackTruncated, + ); + charge += assignTextField( + observation, + "file_name", + fileName, + FIELD_PREFIX_BYTES.fileName, + FIELD_PREFIX_BYTES.fileNameTruncated, + ); + if (isSafeNonNegativeInt(message.lineNumber)) { + observation.line_number = message.lineNumber; + charge += FIELD_PREFIX_BYTES.lineNumber + String(message.lineNumber).length; + } + if (isSafeNonNegativeInt(message.columnNumber)) { + observation.column_number = message.columnNumber; + charge += + FIELD_PREFIX_BYTES.columnNumber + String(message.columnNumber).length; + } + Object.assign(observation, binary.fields); + return { + observation, + charge: charge + binary.bytes, + binaryTruncated: binary.truncated, + }; +}; + +type BoundedRedactedText = { + readonly value: string; + readonly truncated: boolean; + readonly bytes: number; +}; + const boundedRedactedString = ( input: string, maximumBytes: number, secrets: readonly string[], -): { readonly value: string; readonly truncated: boolean } => { - const replacement = "[redacted]"; - const replacementBytes = jsonStringByteLength(replacement) - 2; +): BoundedRedactedText => { + if (secrets.length === 0 || !explicitValuesOccurIn(input, secrets)) { + if (input.length * 6 <= maximumBytes) + return { + value: input, + truncated: false, + bytes: jsonStringByteLength(input), + }; + const fit = scanBoundedJsonBody(input, 0, input.length, maximumBytes); + return fit.cursor === input.length + ? { value: input, truncated: false, bytes: fit.bytes + 2 } + : { + value: input.slice(0, fit.cursor), + truncated: true, + bytes: fit.bytes + 2, + }; + } const chunks: string[] = []; let outputBytes = 0; let cursor = 0; - const keep = (end: number): boolean => { - const start = cursor; - while (cursor < end) { - const codePoint = input.codePointAt(cursor); - if (codePoint === undefined) break; - const character = String.fromCodePoint(codePoint); - const characterBytes = jsonStringByteLength(character) - 2; - if ( - cursor + character.length > end || - outputBytes + characterBytes > maximumBytes - ) - break; - outputBytes += characterBytes; - cursor += character.length; - } - chunks.push(input.slice(start, cursor)); - return cursor === end; - }; for (const span of explicitValueSpans(input, secrets)) { - if (!keep(span.start)) return { value: chunks.join(""), truncated: true }; - if (outputBytes + replacementBytes > maximumBytes) - return { value: chunks.join(""), truncated: true }; - chunks.push(replacement); - outputBytes += replacementBytes; + const kept = scanBoundedJsonBody( + input, + cursor, + span.start, + maximumBytes - outputBytes, + ); + chunks.push(input.slice(cursor, kept.cursor)); + outputBytes += kept.bytes; + cursor = kept.cursor; + if ( + cursor !== span.start || + outputBytes + REDACTED_BODY_BYTES > maximumBytes + ) + return { + value: chunks.join(""), + truncated: true, + bytes: outputBytes + 2, + }; + chunks.push(REDACTED_MARKER); + outputBytes += REDACTED_BODY_BYTES; cursor = span.end; } - const complete = keep(input.length); - return { value: chunks.join(""), truncated: !complete }; + const tail = scanBoundedJsonBody( + input, + cursor, + input.length, + maximumBytes - outputBytes, + ); + chunks.push(input.slice(cursor, tail.cursor)); + outputBytes += tail.bytes; + return { + value: chunks.join(""), + truncated: tail.cursor !== input.length, + bytes: outputBytes + 2, + }; }; type BoundedJson = { readonly value: JsonValue; readonly truncated: boolean; + readonly bytes: number; readonly limit?: FridaOwnedCaptureLimit; }; const clipped = (limit: FridaOwnedCaptureLimit): BoundedJson => ({ value: null, truncated: true, + bytes: 4, limit, }); +const boundedJsonArray = ( + value: readonly unknown[], + budget: number, + depth: number, + visit: (value: unknown, budget: number, depth: number) => BoundedJson, +): BoundedJson => { + const output: JsonValue[] = []; + let usedBytes = 2; + let limit: FridaOwnedCaptureLimit | undefined; + for (let index = 0; index < value.length; index += 1) { + const separatorBytes = output.length === 0 ? 0 : 1; + const remaining = budget - usedBytes - separatorBytes - 1; + if (remaining < 8) { + limit ??= "payload_bytes"; + break; + } + const item = visit(value[index] ?? null, remaining, depth + 1); + if (item.bytes > remaining) { + limit ??= "payload_bytes"; + break; + } + output.push(item.value); + usedBytes += separatorBytes + item.bytes; + if (item.truncated) { + limit ??= item.limit; + break; + } + } + if (output.length < value.length) limit ??= "payload_bytes"; + return limit === undefined + ? { value: output, truncated: false, bytes: usedBytes } + : { value: output, truncated: true, bytes: usedBytes, limit }; +}; + +const boundedJsonObject = ( + value: object, + budget: number, + depth: number, + context: { + readonly secrets: readonly string[]; + readonly visit: ( + value: unknown, + budget: number, + depth: number, + ) => BoundedJson; + }, +): BoundedJson => { + const output: Record = {}; + let usedBytes = 2; + let entries = 0; + let limit: FridaOwnedCaptureLimit | undefined; + for (const rawKey in value) { + if (!Object.hasOwn(value, rawKey)) continue; + const separatorBytes = entries === 0 ? 0 : 1; + const keyLimit = Math.max(0, budget - usedBytes - separatorBytes - 10); + const boundedKey = boundedRedactedString(rawKey, keyLimit, context.secrets); + if (boundedKey.truncated) { + limit ??= "payload_bytes"; + break; + } + const key = boundedKey.value; + // Redaction can collapse source names; never replace a retained fact. + if (Object.hasOwn(output, key)) { + limit ??= "unrepresentable"; + break; + } + const keyBytes = boundedKey.bytes + 1; + const remaining = budget - usedBytes - separatorBytes - keyBytes - 1; + if (remaining < 8) { + limit ??= "payload_bytes"; + break; + } + const entry = context.visit( + Reflect.get(value, rawKey), + remaining, + depth + 1, + ); + if (entry.bytes > remaining) { + limit ??= "payload_bytes"; + break; + } + Object.defineProperty(output, key, { + value: entry.value, + configurable: true, + enumerable: true, + writable: true, + }); + entries += 1; + usedBytes += separatorBytes + keyBytes + entry.bytes; + if (entry.truncated) { + limit ??= entry.limit; + break; + } + } + return limit === undefined + ? { value: output, truncated: false, bytes: usedBytes } + : { value: output, truncated: true, bytes: usedBytes, limit }; +}; + const boundedJsonValue = ( input: unknown, maximumBytes: number, secrets: readonly string[], limits: FridaCapturePolicy, -): BoundedJson & { readonly bytes: number } => { +): BoundedJson => { const seen = new WeakSet(); let remainingNodes = limits.json_nodes; const visit = ( @@ -1459,11 +1750,12 @@ const boundedJsonValue = ( if (remainingNodes < 0) return clipped("json_nodes"); if (depth > limits.json_depth) return clipped("json_depth"); if (budget < 8) return clipped("payload_bytes"); - if (value === null) return { value: null, truncated: false }; - if (typeof value === "boolean" || typeof value === "number") { - if (typeof value === "number" && !Number.isFinite(value)) - return clipped("unrepresentable"); - return { value, truncated: false }; + if (value === null) return { value: null, truncated: false, bytes: 4 }; + if (typeof value === "boolean") + return { value, truncated: false, bytes: value ? 4 : 5 }; + if (typeof value === "number") { + if (!Number.isFinite(value)) return clipped("unrepresentable"); + return { value, truncated: false, bytes: String(value).length }; } if (typeof value === "string") { const bounded = boundedRedactedString( @@ -1472,103 +1764,29 @@ const boundedJsonValue = ( secrets, ); return bounded.truncated - ? { value: bounded.value, truncated: true, limit: "payload_bytes" } - : { value: bounded.value, truncated: false }; + ? { + value: bounded.value, + truncated: true, + bytes: bounded.bytes, + limit: "payload_bytes", + } + : { value: bounded.value, truncated: false, bytes: bounded.bytes }; } if (typeof value !== "object") return clipped("unrepresentable"); if (seen.has(value)) return clipped("unrepresentable"); seen.add(value); try { - if (Array.isArray(value)) { - const output: JsonValue[] = []; - let usedBytes = 2; - let limit: FridaOwnedCaptureLimit | undefined; - for (let index = 0; index < value.length; index += 1) { - const separatorBytes = output.length === 0 ? 0 : 1; - const remaining = budget - usedBytes - separatorBytes - 1; - if (remaining < 8) { - limit ??= "payload_bytes"; - break; - } - const item = visit(value[index] ?? null, remaining, depth + 1); - const itemBytes = Buffer.byteLength(JSON.stringify(item.value)); - if (itemBytes > remaining) { - limit ??= "payload_bytes"; - break; - } - output.push(item.value); - usedBytes += separatorBytes + itemBytes; - if (item.truncated) { - limit ??= item.limit; - break; - } - } - if (output.length < value.length) limit ??= "payload_bytes"; - return limit === undefined - ? { value: output, truncated: false } - : { value: output, truncated: true, limit }; - } - const output: Record = {}; - let usedBytes = 2; - let entries = 0; - let limit: FridaOwnedCaptureLimit | undefined; - for (const rawKey in value) { - if (!Object.hasOwn(value, rawKey)) continue; - const separatorBytes = entries === 0 ? 0 : 1; - const keyLimit = Math.max(0, budget - usedBytes - separatorBytes - 10); - const boundedKey = boundedRedactedString(rawKey, keyLimit, secrets); - if (boundedKey.truncated) { - limit ??= "payload_bytes"; - break; - } - const key = boundedKey.value; - // Redaction can collapse source names; never replace a retained fact. - if (Object.hasOwn(output, key)) { - limit ??= "unrepresentable"; - break; - } - const keyBytes = jsonStringByteLength(key) + 1; - const remaining = budget - usedBytes - separatorBytes - keyBytes - 1; - if (remaining < 8) { - limit ??= "payload_bytes"; - break; - } - const entry = visit(Reflect.get(value, rawKey), remaining, depth + 1); - const entryBytes = Buffer.byteLength(JSON.stringify(entry.value)); - if (entryBytes > remaining) { - limit ??= "payload_bytes"; - break; - } - Object.defineProperty(output, key, { - value: entry.value, - configurable: true, - enumerable: true, - writable: true, - }); - entries += 1; - usedBytes += separatorBytes + keyBytes + entryBytes; - if (entry.truncated) { - limit ??= entry.limit; - break; - } - } - return limit === undefined - ? { value: output, truncated: false } - : { value: output, truncated: true, limit }; + return Array.isArray(value) + ? boundedJsonArray(value, budget, depth, visit) + : boundedJsonObject(value, budget, depth, { secrets, visit }); } finally { seen.delete(value); } }; const result = visit(input, maximumBytes, 0); - const bytes = Buffer.byteLength(JSON.stringify(result.value)); - return bytes > maximumBytes - ? { - value: null, - truncated: true, - bytes: Buffer.byteLength("null"), - limit: result.limit ?? "payload_bytes", - } - : { ...result, bytes }; + return result.bytes > maximumBytes + ? clipped(result.limit ?? "payload_bytes") + : result; }; const remoteOptions = (remote: FridaRemoteConnection): RemoteDeviceOptions => ({ diff --git a/src/wasm/WabtInterface.test.ts b/src/wasm/WabtInterface.test.ts index 2817148555..8d8a63e9b2 100644 --- a/src/wasm/WabtInterface.test.ts +++ b/src/wasm/WabtInterface.test.ts @@ -1,4 +1,5 @@ import { expect, it } from "vitest"; +import { parseWabtInterface } from "./WabtInterface.js"; import { parseWabtWat } from "./WabtWat.js"; it("resolves imported index spaces and decoded escaped names without depending on body/type numbering", () => { @@ -244,3 +245,57 @@ it("rejects a second module after a CR-terminated line comment", () => { }), ); }); + +it("resolves repeated typed signatures across many functions while stopping at bodies", () => { + const functions = Array.from( + { length: 200 }, + (_, i) => + `(func $f${i} (type $sig) (local i32 i64) local.get 0 i64.extend_i32_s)`, + ).join("\n"); + const exports = Array.from( + { length: 200 }, + (_, i) => `(export "e${i}" (func $f${i}))`, + ).join("\n"); + const report = parseWabtWat(`(module + (type $sig (func\u00a0(param i32) (result i64))) + (import "env" "imp" (func (type $sig))) + ${functions} + ${exports})`).interface; + expect(report.state).toBe("complete"); + expect(report.entries).toHaveLength(201); + expect(report.entries[0]?.signature).toEqual({ + kind: "func", + params: ["i32"], + results: ["i64"], + }); + expect(report.entries[200]?.signature).toEqual({ + kind: "func", + params: ["i32"], + results: ["i64"], + }); +}); + +it("marks type index space unknown for commented rec forms and enforces tight interface budgets", () => { + const commentedRec = parseWabtInterface([ + "( (; block comment before head ;) rec (type $a (func)))", + "(type (func (param i32)))", + "(func $f (type 0))", + '(export "f" (func $f))', + ]); + expect(commentedRec.state).toBe("complete"); + expect(commentedRec.entries[0]).toMatchObject({ + name: "f", + signature: null, + issue: expect.any(String), + }); + + const manyFunctions = Array.from( + { length: 50 }, + (_, i) => + `(func $f${i} (param i32) (result i64)) (export "e${i}" (func $f${i}))`, + ).join("\n"); + const budgeted = parseWabtWat(`(module ${manyFunctions})`, 512).interface; + expect(budgeted.state).toBe("partial"); + expect(budgeted.entries.length).toBeLessThan(50); + expect(budgeted.issues.length).toBeGreaterThan(0); +}); diff --git a/src/wasm/WabtInterface.ts b/src/wasm/WabtInterface.ts index b4eb9c2117..c39554d214 100644 --- a/src/wasm/WabtInterface.ts +++ b/src/wasm/WabtInterface.ts @@ -1,7 +1,10 @@ import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; import { WabtAdmissionError } from "./WabtAdmissionError.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; -import { wasmInterfaceEntryRepresentationBytes } from "../domain/wasm/wasmInterface.js"; +import { + DEFAULT_WASM_INTERFACE_REPRESENTATION_BYTES, + wasmInterfaceEntryRepresentationBytes, +} from "../domain/wasm/wasmInterface.js"; import { WasmInterfaceBudget } from "../domain/wasm/wasmInterfaceBudget.js"; import type { WasmInterface, @@ -12,45 +15,82 @@ import type { import { watString, watStringEnd } from "./WabtString.js"; import { watCommentEnd } from "./WabtComment.js"; +const isWatWhitespace = (text: string, index: number): boolean => { + const code = text.charCodeAt(index); + if (code === 0x20 || (code >= 0x09 && code <= 0x0d)) return true; + return code >= 0x80 && /\s/u.test(text[index] ?? ""); +}; + +const scanCommentEnd = (text: string, index: number): number | undefined => { + const code = text.charCodeAt(index); + if (code !== 0x3b && !(code === 0x28 && text.charCodeAt(index + 1) === 0x3b)) + return undefined; + return watCommentEnd(text, index); +}; + +const scanNestedFormEnd = (form: string, start: number): number => { + let depth = 1; + let i = start + 1; + while (i < form.length && depth > 0) { + const commentEnd = scanCommentEnd(form, i); + if (commentEnd !== undefined) { + i = commentEnd; + continue; + } + const code = form.charCodeAt(i); + if (code === 0x22) i = watStringEnd(form, i + 1); + else { + if (code === 0x28) depth++; + else if (code === 0x29) depth--; + i++; + } + } + return i; +}; + +const scanAtomEnd = (form: string, start: number): number => { + let i = start; + while (i < form.length) { + const code = form.charCodeAt(i); + if (code === 0x28 || code === 0x29 || isWatWhitespace(form, i)) break; + i++; + } + return i; +}; + /** Split direct WAT children only; function instruction bodies are never materialized. */ -const splitParts = (form: string, maximumBytes?: number): string[] => { - const budget = new WasmInterfaceBudget(maximumBytes); +const splitParts = (form: string, maximumBytes?: number): readonly string[] => { + const limit = maximumBytes ?? DEFAULT_WASM_INTERFACE_REPRESENTATION_BYTES; + if (!Number.isSafeInteger(limit) || limit < 0) + new WasmInterfaceBudget(maximumBytes); + let remaining = limit; const items: string[] = []; let i = 1; - while (i < form.length - 1) { - if (/\s/u.test(form[i] ?? "")) { + const last = form.length - 1; + while (i < last) { + if (isWatWhitespace(form, i)) { i++; continue; } - const commentEnd = watCommentEnd(form, i); + const commentEnd = scanCommentEnd(form, i); if (commentEnd !== undefined) { i = commentEnd; continue; } const start = i; - if (form[i] === '"') { + const code = form.charCodeAt(i); + if (code === 0x22) { i = watStringEnd(form, i + 1); - } else if (form[i] === "(") { - let depth = 1; - i++; - while (i < form.length && depth > 0) { - const commentEnd = watCommentEnd(form, i); - if (commentEnd !== undefined) i = commentEnd; - else if (form[i] === '"') i = watStringEnd(form, i + 1); - else { - if (form[i] === "(") depth++; - else if (form[i] === ")") depth--; - i++; - } - } + } else if (code === 0x28) { + i = scanNestedFormEnd(form, i); } else { - while (i < form.length && !/[\s()]/u.test(form[i] ?? "")) i++; - const atom = form.slice(start, i); - if (items[0] === "func" && items.length > 1 && !atom.startsWith("$")) + i = scanAtomEnd(form, i); + if (i > start && items[0] === "func" && items.length > 1 && code !== 0x24) break; } if (i <= start) throw new WabtAdmissionError("malformed_form"); - budget.reserve(64 + (i - start) * 2); + remaining -= 64 + (i - start) * 2; + if (remaining < 0) new WasmInterfaceBudget(maximumBytes).reserve(limit + 1); items.push(form.slice(start, i)); } return items; @@ -65,6 +105,13 @@ const integer = (text: string): string | null => { return BigInt(text).toString(); }; +const DEFINITION_KINDS = new Set(["func", "table", "memory", "global", "tag"]); + +const toDefinitionKind = (rawKind: string): WasmInterfaceEntry["kind"] => + DEFINITION_KINDS.has(rawKind) + ? (rawKind as WasmInterfaceEntry["kind"]) + : "unknown"; + const admittedValues = new Set([ "i32", "i64", @@ -77,247 +124,388 @@ const admittedValues = new Set([ const isValueType = (type: string): type is WasmInterfaceValueType => admittedValues.has(type); +const collectCategoryValues = ( + bodyParts: readonly string[], + category: string, + getGroupParts: (index: number) => readonly string[], +): WasmInterfaceValueType[] | null => { + const values: WasmInterfaceValueType[] = []; + for (let i = 1; i < bodyParts.length; i++) { + if (bodyParts[i]!.charCodeAt(0) !== 0x28) continue; + const group = getGroupParts(i); + if (group[0] !== category) continue; + for (let j = 1; j < group.length; j++) { + const type = group[j]!; + if (type.charCodeAt(0) === 0x24) continue; + if (!isValueType(type)) return null; + values.push(type); + } + } + return values; +}; + +const parseFunctionType = ( + bodyParts: readonly string[], + kind: "func" | "tag", + splitGroup: (group: string) => readonly string[], + initialChildren?: readonly (readonly string[] | undefined)[], +): WasmInterfaceSignature | null => { + const children: (readonly string[] | undefined)[] = initialChildren + ? [...initialChildren] + : Array(bodyParts.length); + const getGroupParts = (index: number): readonly string[] => { + let group = children[index]; + if (group === undefined) { + group = splitGroup(bodyParts[index]!); + children[index] = group; + } + return group; + }; + const params = collectCategoryValues(bodyParts, "param", getGroupParts); + const results = collectCategoryValues(bodyParts, "result", getGroupParts); + return params === null || results === null ? null : { kind, params, results }; +}; + +const collectSignatureTokens = ( + kind: "memory" | "table", + parts: readonly string[], + splitGroup: (group: string) => readonly string[], +): { readonly pageSize: string; readonly tokens: string[] } | null => { + let pageSize = "65536"; + const tokens: string[] = []; + for (let i = 1; i < parts.length; i++) { + const token = parts[i]!; + const first = token.charCodeAt(0); + if (first === 0x28) { + const declaration = splitGroup(token); + if ( + kind !== "memory" || + declaration[0] !== "pagesize" || + declaration.length !== 2 + ) + return null; + const parsedPageSize = integer(declaration[1] ?? ""); + if (parsedPageSize === null) return null; + pageSize = parsedPageSize; + } else if (first !== 0x24) { + tokens.push(token); + } + } + return { pageSize, tokens }; +}; + +const parseMemoryOrTableSignature = ( + kind: "memory" | "table", + parts: readonly string[], + splitGroup: (group: string) => readonly string[], +): WasmInterfaceSignature | null => { + const collected = collectSignatureTokens(kind, parts, splitGroup); + if (collected === null) return null; + const { pageSize, tokens } = collected; + let cursor = 0; + const firstToken = tokens[cursor]; + const address_type = firstToken === "i64" ? "i64" : "i32"; + if (firstToken === "i64" || firstToken === "i32") cursor++; + const minimum = integer(tokens[cursor++] ?? ""); + const possibleMaximum = + cursor < tokens.length ? integer(tokens[cursor]!) : null; + if (possibleMaximum !== null) cursor++; + const shared = tokens[cursor] === "shared"; + if (shared) cursor++; + if (minimum === null) return null; + if (kind === "memory") + return cursor === tokens.length + ? { + kind, + page_size: pageSize, + address_type, + minimum, + maximum: possibleMaximum, + shared, + } + : null; + const element = tokens[cursor++]; + return cursor === tokens.length && + (element === "funcref" || element === "externref") + ? { + kind, + address_type, + minimum, + maximum: possibleMaximum, + shared, + element, + } + : null; +}; + +const parseGlobalSignature = ( + parts: readonly string[], + splitGroup: (group: string) => readonly string[], +): WasmInterfaceSignature | null => { + const declaration = parts[1]?.startsWith("$") === true ? parts[2] : parts[1]; + const group = + declaration?.startsWith("(") === true ? splitGroup(declaration) : undefined; + const mutable = group?.[0] === "mut"; + const value_type = mutable ? group?.[1] : declaration; + return value_type !== undefined && isValueType(value_type) + ? { kind: "global", value_type, mutable } + : null; +}; + +const parseFormSignature = ( + ctx: DecoderContext, + parts: readonly string[], +): WasmInterfaceSignature | null => { + const kind = parts[0]; + if (kind === "func" || kind === "tag") { + // Interpret group heads through the same comment/whitespace framing as + // their values; raw prefixes can mistake an explicit type for no type. + const childGroups: (readonly string[] | undefined)[] = Array(parts.length); + let typeUse: readonly string[] | undefined; + for (let i = 1; i < parts.length; i++) { + const token = parts[i]!; + if (token.charCodeAt(0) !== 0x28) continue; + const group = ctx.splitGroup(token); + childGroups[i] = group; + if (group[0] === "type") { + typeUse = group; + break; + } + } + if (typeUse === undefined) + return parseFunctionType(parts, kind, ctx.splitGroup, childGroups); + const reference = typeUse[1]; + const index = + reference === undefined + ? undefined + : reference.startsWith("$") + ? ctx.typeNames.get(reference) + : Number(reference); + const type = + index == null || ctx.typeSpaceUnknown ? undefined : ctx.types[index]; + return type?.kind === "func" ? { ...type, kind } : null; + } + if (kind === "memory" || kind === "table") + return parseMemoryOrTableSignature(kind, parts, ctx.splitGroup); + if (kind === "global") return parseGlobalSignature(parts, ctx.splitGroup); + return null; +}; + +interface DecoderContext { + readonly forms: readonly string[]; + readonly result: WasmInterface; + readonly budget: WasmInterfaceBudget; + readonly splitGroup: (form: string) => readonly string[]; + readonly getFormParts: (index: number) => readonly string[]; + readonly types: (WasmInterfaceSignature | null)[]; + readonly typeNames: Map; + readonly definitionNames: Map>; + readonly definitions: Map< + string, + { signature: WasmInterfaceSignature | null }[] + >; + readonly ambiguousSpaces: Set; + readonly typeSpaceUnknown: boolean; +} + +const indexLabel = ( + ctx: DecoderContext, + label: string, + space: string, + index: number, +): void => { + let labels: Map; + if (space === "type") { + labels = ctx.typeNames; + } else { + let existing = ctx.definitionNames.get(space); + if (existing === undefined) { + existing = new Map(); + ctx.definitionNames.set(space, existing); + } + labels = existing; + } + if (!labels.has(label)) { + labels.set(label, index); + return; + } + if (!ctx.ambiguousSpaces.has(space)) { + ctx.ambiguousSpaces.add(space); + ctx.result.issues.push( + `Ambiguous WABT identifiers in the ${space} index space; named references have unknown identity`, + ); + } + labels.set(label, null); +}; + +const addDefinition = ( + ctx: DecoderContext, + p: readonly string[], +): { + index: number; + kind: WasmInterfaceEntry["kind"]; + signature: WasmInterfaceSignature | null; +} => { + const kind = toDefinitionKind(p[0] ?? "unknown"); + let space = ctx.definitions.get(kind); + if (space === undefined) { + space = []; + ctx.definitions.set(kind, space); + } + const item = { + signature: parseFormSignature(ctx, p), + }; + const label = p[1]?.startsWith("$") === true ? p[1] : undefined; + ctx.budget.reserve(256); + const index = space.length; + space.push(item); + if (label !== undefined) indexLabel(ctx, label, kind, index); + return { index, kind, signature: item.signature }; +}; + +const appendImportEntry = (ctx: DecoderContext, formIndex: number): void => { + const p = ctx.getFormParts(formIndex); + const body = p[3]; + if (body === undefined) throw new WabtAdmissionError("incomplete_import"); + const observed = addDefinition(ctx, ctx.splitGroup(body)); + const entry: WasmInterfaceEntry = { + direction: "import", + module: name(p[1]), + name: name(p[2]), + ...observed, + wat_form: ctx.forms[formIndex]!, + issue: + observed.signature === null + ? "Import type is outside admitted core signature semantics" + : null, + }; + ctx.budget.reserve(wasmInterfaceEntryRepresentationBytes(entry)); + ctx.result.entries.push(entry); +}; + +const appendExportEntry = (ctx: DecoderContext, formIndex: number): void => { + const p = ctx.getFormParts(formIndex); + const body = p[2]; + if (body === undefined) throw new WabtAdmissionError("incomplete_export"); + const descriptor = ctx.splitGroup(body); + const kind = toDefinitionKind(descriptor[0] ?? "unknown"); + const reference = descriptor[1]; + const space = ctx.definitions.get(kind); + const index = + reference === undefined + ? -1 + : reference.startsWith("$") + ? (ctx.definitionNames.get(kind)?.get(reference) ?? -1) + : Number(reference); + const observed = + space !== undefined && Number.isSafeInteger(index) && index >= 0 + ? space[index] + : undefined; + const entry: WasmInterfaceEntry = { + direction: "export", + module: null, + name: name(p[1]), + kind, + index: observed === undefined ? null : index, + signature: observed?.signature ?? null, + wat_form: ctx.forms[formIndex]!, + issue: + observed?.signature == null + ? "Export type/index is outside admitted core signature semantics" + : null, + }; + ctx.budget.reserve(wasmInterfaceEntryRepresentationBytes(entry)); + ctx.result.entries.push(entry); +}; + +/** Read only the leading WAT form keyword without splitting or retaining children. */ +const readFormHead = (form: string): string | undefined => { + let i = 1; + const last = form.length - 1; + while (i < last) { + if (isWatWhitespace(form, i)) { + i++; + continue; + } + const commentEnd = scanCommentEnd(form, i); + if (commentEnd !== undefined) { + i = commentEnd; + continue; + } + const code = form.charCodeAt(i); + if (code === 0x22 || code === 0x28) return undefined; + const end = scanAtomEnd(form, i); + return end > i ? form.slice(i, end) : undefined; + } + return undefined; +}; + /** Resolve index spaces at the producer, not from retained raw WAT in consumers. */ const decodeWabtInterface = ( forms: readonly string[], result: WasmInterface, maximumBytes: number | undefined, ): WasmInterface => { - const budget = new WasmInterfaceBudget(maximumBytes); - const parts = (form: string) => splitParts(form, maximumBytes); - const head = (form: string): string | undefined => parts(form)[0]; - const values = ( - form: string, - category: string, - ): WasmInterfaceValueType[] | null => { - const result: WasmInterfaceValueType[] = []; - for (const item of parts(form)) { - if (!item.startsWith("(")) continue; - const group = parts(item); - if (group[0] !== category) continue; - for (const type of group.slice(1).filter((t) => !t.startsWith("$"))) { - if (!isValueType(type)) return null; - result.push(type); - } + const shortGroupCache = new Map(); + const splitGroup = (form: string): readonly string[] => { + if (form.length > 256) return splitParts(form, maximumBytes); + let cached = shortGroupCache.get(form); + if (cached === undefined) { + cached = splitParts(form, maximumBytes); + if (shortGroupCache.size < 4096) shortGroupCache.set(form, cached); } - return result; + return cached; }; - const functionType = ( - form: string, - kind: "func" | "tag", - ): WasmInterfaceSignature | null => { - const params = values(form, "param"); - const results = values(form, "result"); - return params === null || results === null - ? null - : { kind, params, results }; + const getFormParts = (index: number): readonly string[] => + splitParts(forms[index]!, maximumBytes); + let typeSpaceUnknown = false; + const typeIndices: number[] = []; + const importIndices: number[] = []; + const definitionIndices: number[] = []; + const exportIndices: number[] = []; + for (let i = 0; i < forms.length; i++) { + const head = readFormHead(forms[i]!); + if (head === "rec") typeSpaceUnknown = true; + else if (head === "type") typeIndices.push(i); + else if (head === "import") importIndices.push(i); + else if (head === "export") exportIndices.push(i); + else if (head !== undefined && DEFINITION_KINDS.has(head)) + definitionIndices.push(i); + } + const ctx: DecoderContext = { + forms, + result, + budget: new WasmInterfaceBudget(maximumBytes), + splitGroup, + getFormParts, + types: [], + typeNames: new Map(), + definitionNames: new Map(), + definitions: new Map(), + ambiguousSpaces: new Set(), + typeSpaceUnknown, }; - - const types: (WasmInterfaceSignature | null)[] = []; - const typeNames = new Map(); - const definitionNames = new Map>(); - const indexLabel = ( - labels: Map, - label: string, - index: number, - space: string, - ) => { - const issue = `Ambiguous WABT identifiers in the ${space} index space; named references have unknown identity`; - if (labels.has(label) && !result.issues.includes(issue)) - result.issues.push(issue); - labels.set(label, labels.has(label) ? null : index); - }; - const definitions = new Map< - string, - { signature: WasmInterfaceSignature | null }[] - >(); - const typeSpaceUnknown = forms.some((f) => head(f) === "rec"); - for (const form of forms) { - const p = parts(form); - if (p[0] !== "type") continue; + for (const i of typeIndices) { + const p = getFormParts(i); if (p[1]?.startsWith("$") === true) - indexLabel(typeNames, p[1], types.length, "type"); + indexLabel(ctx, p[1], "type", ctx.types.length); const body = p.find((item) => item.startsWith("(")); - budget.reserve(256 + (body?.length ?? 0) * 6); - types.push( - body !== undefined && head(body) === "func" && !typeSpaceUnknown - ? functionType(body, "func") - : null, - ); - } - const signature = (form: string): WasmInterfaceSignature | null => { - const p = parts(form); - const kind = p[0]; - if (kind === "func" || kind === "tag") { - // Interpret group heads through the same comment/whitespace framing as - // their values; raw prefixes can mistake an explicit type for no type. - const use = p.find((t) => t.startsWith("(") && head(t) === "type"); - if (use === undefined) return functionType(form, kind); - const reference = parts(use)[1]; - const index = - reference === undefined - ? undefined - : reference.startsWith("$") - ? typeNames.get(reference) - : Number(reference); - const type = index == null || typeSpaceUnknown ? undefined : types[index]; - return type?.kind === "func" ? { ...type, kind } : null; - } - if (kind === "memory" || kind === "table") { - const groups = p.slice(1).filter((t) => t.startsWith("(")); - let pageSize = "65536"; - for (const group of groups) { - const declaration = parts(group); - if ( - kind !== "memory" || - declaration[0] !== "pagesize" || - declaration.length !== 2 - ) - return null; - const parsedPageSize = integer(declaration[1] ?? ""); - if (parsedPageSize === null) return null; - pageSize = parsedPageSize; - } - const tokens = p - .slice(1) - .filter((t) => !t.startsWith("$") && !t.startsWith("(")); - const address_type = tokens[0] === "i64" ? "i64" : "i32"; - if (tokens[0] === "i64" || tokens[0] === "i32") tokens.shift(); - const minimum = integer(tokens.shift() ?? ""); - const possibleMaximum = - tokens[0] === undefined ? null : integer(tokens[0]); - if (possibleMaximum !== null) tokens.shift(); - const shared = tokens[0] === "shared"; - if (shared) tokens.shift(); - if (minimum === null) return null; - if (kind === "memory") - return tokens.length === 0 - ? { - kind, - page_size: pageSize, - address_type, - minimum, - maximum: possibleMaximum, - shared, - } - : null; - const element = tokens.shift(); - return tokens.length === 0 && - element !== undefined && - (element === "funcref" || element === "externref") - ? { - kind, - address_type, - minimum, - maximum: possibleMaximum, - shared, - element, - } - : null; - } - if (kind === "global") { - const declaration = p[1]?.startsWith("$") === true ? p[2] : p[1]; - const group = - declaration?.startsWith("(") === true ? parts(declaration) : undefined; - const mutable = group?.[0] === "mut"; - const value_type = mutable ? group?.[1] : declaration; - return value_type !== undefined && isValueType(value_type) - ? { kind, value_type, mutable } - : null; - } - return null; - }; - const addDefinition = ( - form: string, - ): { - index: number; - kind: WasmInterfaceEntry["kind"]; - signature: WasmInterfaceSignature | null; - } => { - const p = parts(form); - const rawKind = p[0] ?? "unknown"; - const kind = ["func", "table", "memory", "global", "tag"].includes(rawKind) - ? (rawKind as WasmInterfaceEntry["kind"]) - : "unknown"; - const space = definitions.get(kind) ?? []; - const item = { signature: signature(form) }; - const label = p[1]?.startsWith("$") === true ? p[1] : undefined; - budget.reserve(256); - const index = space.length; - space.push(item); - definitions.set(kind, space); - if (label !== undefined) { - const labels = - definitionNames.get(kind) ?? new Map(); - indexLabel(labels, label, index, kind); - definitionNames.set(kind, labels); - } - return { index, kind, signature: item.signature }; - }; - for (const form of forms) { - const p = parts(form); - if (p[0] !== "import") continue; - const body = p[3]; - if (body === undefined) throw new WabtAdmissionError("incomplete_import"); - const observed = addDefinition(body); - const entry: WasmInterfaceEntry = { - direction: "import", - module: name(p[1]), - name: name(p[2]), - ...observed, - wat_form: form, - issue: - observed.signature === null - ? "Import type is outside admitted core signature semantics" + ctx.budget.reserve(256 + (body?.length ?? 0) * 6); + if (body === undefined || typeSpaceUnknown) { + if (body !== undefined) splitGroup(body); + ctx.types.push(null); + } else { + const bodyParts = splitGroup(body); + ctx.types.push( + bodyParts[0] === "func" + ? parseFunctionType(bodyParts, "func", splitGroup) : null, - }; - budget.reserve(wasmInterfaceEntryRepresentationBytes(entry)); - result.entries.push(entry); - } - for (const form of forms) { - const kind = head(form); - if ( - kind !== undefined && - ["func", "table", "memory", "global", "tag"].includes(kind) - ) - addDefinition(form); - } - for (const form of forms) { - const p = parts(form); - if (p[0] !== "export") continue; - const body = p[2]; - if (body === undefined) throw new WabtAdmissionError("incomplete_export"); - const descriptor = parts(body); - const rawKind = descriptor[0] ?? "unknown"; - const kind = ["func", "table", "memory", "global", "tag"].includes(rawKind) - ? (rawKind as WasmInterfaceEntry["kind"]) - : "unknown"; - const reference = descriptor[1]; - const space = definitions.get(kind) ?? []; - const index = - reference === undefined - ? -1 - : reference.startsWith("$") - ? (definitionNames.get(kind)?.get(reference) ?? -1) - : Number(reference); - const observed = - Number.isSafeInteger(index) && index >= 0 ? space[index] : undefined; - const entry: WasmInterfaceEntry = { - direction: "export", - module: null, - name: name(p[1]), - kind, - index: observed === undefined ? null : index, - signature: observed?.signature ?? null, - wat_form: form, - issue: - observed?.signature == null - ? "Export type/index is outside admitted core signature semantics" - : null, - }; - budget.reserve(wasmInterfaceEntryRepresentationBytes(entry)); - result.entries.push(entry); + ); + } } + for (const i of importIndices) appendImportEntry(ctx, i); + for (const i of definitionIndices) addDefinition(ctx, getFormParts(i)); + for (const i of exportIndices) appendExportEntry(ctx, i); // Unsupported signatures leave inventory completeness intact. A missing // signature is unknown per entry, not proof that a name is absent. return result; diff --git a/src/wasm/WabtOutput.test.ts b/src/wasm/WabtOutput.test.ts index 085d2ef239..3bc9ee331b 100644 --- a/src/wasm/WabtOutput.test.ts +++ b/src/wasm/WabtOutput.test.ts @@ -526,3 +526,94 @@ it.each([ ], }); }); + +it("parses many sections with large details and matches indexed glue references", () => { + let cursor = 8; + const rows: string[] = []; + const names: string[] = []; + for (let i = 0; i < 60; i++) { + const start = cursor + 2; + const end = start + 16; + rows.push( + ` Custom start=0x${start.toString(16).padStart(8, "0")} end=0x${end.toString(16).padStart(8, "0")} (size=0x00000010) "s${i}"`, + ); + names.push(`s${i}\0ignored`); + cursor = end; + } + const dump = [ + "", + "module.wasm:\tfile format wasm 0x1", + "", + "Sections:", + "", + ...rows, + "", + "Section Details:", + "", + "x".repeat(200_000), + ].join("\n"); + const parsed = parseWabtOutput(dump, cursor, names); + expect(parsed.sections).toHaveLength(60); + expect(parsed.sections[59]).toEqual({ + kind: "Custom", + start: cursor - 16, + end: cursor, + bytes: 16, + description: '"s59"', + }); + + const candidates = ["/app/a.wasm", "/other/a.wasm", "/other/b.wasm"]; + const glue = associateWasmGlue( + 'fetch("A.WASM#frag"); fetch("./a.wasm"); fetch("https://cdn.example/b.WASM?q=1");', + "/app/glue.js", + candidates, + ); + expect(glue.references).toMatchObject([ + { + value: "A.WASM#frag", + association: "unresolved", + candidate_paths: [], + }, + { + value: "./a.wasm", + association: "local-path-candidate", + candidate_paths: ["/app/a.wasm"], + }, + { + value: "https://cdn.example/b.WASM?q=1", + association: "unresolved", + candidate_paths: [], + }, + ]); + const upperGlue = associateWasmGlue( + 'fetch("./A.WASM"); fetch("https://cdn.example/a.wasm?q=1");', + "/app/glue.js", + ["/app/A.WASM", "/other/a.wasm"], + ); + expect(upperGlue.references).toMatchObject([ + { + value: "./A.WASM", + association: "local-path-candidate", + candidate_paths: ["/app/A.WASM"], + }, + { + value: "https://cdn.example/a.wasm?q=1", + association: "basename-candidates", + candidate_paths: ["/other/a.wasm"], + }, + ]); + + const decorated = associateWasmGlue( + 'class C { m(@dec("./a.wasm") x) {} }', + "/app/glue.js", + ["/app/a.wasm"], + ); + expect(decorated.parse_status).toBe("complete"); + expect(decorated.references).toMatchObject([ + { + value: "./a.wasm", + association: "local-path-candidate", + candidate_paths: ["/app/a.wasm"], + }, + ]); +}); diff --git a/src/wasm/WabtOutput.ts b/src/wasm/WabtOutput.ts index 4fdbe738ac..a8dc5ccc5c 100644 --- a/src/wasm/WabtOutput.ts +++ b/src/wasm/WabtOutput.ts @@ -2,9 +2,56 @@ import { WabtAdmissionError } from "./WabtAdmissionError.js"; import { readLeb128, ULEB32 } from "../domain/leb128.js"; import { isStrictUtf8 } from "../domain/strictUtf8.js"; +const SECTION_ROW_RE = + /[ \t]*(\w+) start=0x([\da-f]+) end=0x([\da-f]+) \(size=0x([\da-f]+)\) /uy; + /** WABT prints names with %.*s, so an embedded NUL ends their display. */ -const wabtDisplayedName = (name: string | undefined): string | undefined => - name?.split("\0", 1)[0]; +const wabtDisplayedName = (name: string | undefined): string | undefined => { + if (name === undefined) return undefined; + const nul = name.indexOf("\0"); + return nul < 0 ? name : name.slice(0, nul); +}; + +const parseCustomSectionField = ( + text: string, + offset: number, + customSectionNames: readonly string[], + customIndex: { value: number }, + bounds: { start: number; end: number; artifact: Uint8Array | undefined }, +): { + readonly description: string; + readonly nextOffset: number; + readonly invalidNameEnd?: number; +} => { + if (text.charCodeAt(offset) !== 0x22) { + // WABT leaves this field blank when the binary custom name is invalid + // UTF-8. Confirm the bytes rather than inventing a name from its output. + const invalidEnd = invalidCustomNameEnd( + bounds.artifact, + bounds.start, + bounds.end, + ); + if (invalidEnd === undefined) + throw new WabtAdmissionError("blank_custom_name"); + const nextOffset = + text.charCodeAt(offset) === 0x0a && + !text.startsWith("\nSection Details:\n", offset) + ? offset + 1 + : offset; + return { description: "", nextOffset, invalidNameEnd: invalidEnd }; + } + const name = wabtDisplayedName(customSectionNames[customIndex.value++]); + if ( + name === undefined || + text.charCodeAt(offset) !== 0x22 || + !text.startsWith(name, offset + 1) || + text.charCodeAt(offset + 1 + name.length) !== 0x22 || + text.charCodeAt(offset + 2 + name.length) !== 0x0a + ) + throw new WabtAdmissionError("custom_header_mismatch"); + const description = `"${name}"`; + return { description, nextOffset: offset + description.length + 1 }; +}; /** Frame WABT's raw custom names using the ordered names from its escaped WAT output. */ export const parseWabtOutput = ( @@ -14,75 +61,61 @@ export const parseWabtOutput = ( debugModuleNames: readonly string[] = [], artifact?: Uint8Array, ) => { - const preamble = - "\nmodule.wasm:\tfile format wasm 0x1\n" + - debugModuleNames - .map((name) => `module name: <${wabtDisplayedName(name)}>\n`) - .join(""); + let moduleLines = ""; + for (let i = 0; i < debugModuleNames.length; i++) + moduleLines += `module name: <${wabtDisplayedName(debugModuleNames[i])}>\n`; + const preamble = `\nmodule.wasm:\tfile format wasm 0x1\n${moduleLines}`; const prefix = `${preamble}\nSections:\n\n`; if (!text.startsWith(prefix)) throw new WabtAdmissionError("unsupported_section_header"); let offset = prefix.length; - let customIndex = 0; + const customIndex = { value: 0 }; + let previousEnd = 8; const sections = []; const invalidNameEnds = new Set(); while (!text.startsWith("\nSection Details:\n", offset)) { - const match = - /^[ \t]*(\w+) start=0x([\da-f]+) end=0x([\da-f]+) \(size=0x([\da-f]+)\) /u.exec( - text.slice(offset), - ); + SECTION_ROW_RE.lastIndex = offset; + const match = SECTION_ROW_RE.exec(text); if (match === null) throw new WabtAdmissionError("unrecognized_section_row"); offset += match[0].length; + const kind = match[1] ?? ""; + const start = Number.parseInt(match[2] ?? "", 16); + const end = Number.parseInt(match[3] ?? "", 16); + const bytes = Number.parseInt(match[4] ?? "", 16); let description: string; - if (match[1] === "Custom" && !text.startsWith('"', offset)) { - // WABT leaves this field blank when the binary custom name is invalid - // UTF-8. Confirm the bytes rather than inventing a name from its output. - const start = Number.parseInt(match[2] ?? "", 16); - const end = Number.parseInt(match[3] ?? "", 16); - const invalidEnd = invalidCustomNameEnd(artifact, start, end); - if (invalidEnd === undefined) - throw new WabtAdmissionError("blank_custom_name"); - invalidNameEnds.add(invalidEnd); - description = ""; - // WABT does not terminate a blank-name row when another section follows. - if ( - text.startsWith("\n", offset) && - !text.startsWith("\nSection Details:\n", offset) - ) - offset += 1; - } else if (match[1] === "Custom") { - const name = wabtDisplayedName(customSectionNames[customIndex++]); - if (name === undefined || !text.startsWith(`"${name}"\n`, offset)) - throw new WabtAdmissionError("custom_header_mismatch"); - description = `"${name}"`; - offset += description.length + 1; + if (kind === "Custom") { + const parsed = parseCustomSectionField( + text, + offset, + customSectionNames, + customIndex, + { start, end, artifact }, + ); + description = parsed.description; + offset = parsed.nextOffset; + if (parsed.invalidNameEnd !== undefined) + invalidNameEnds.add(parsed.invalidNameEnd); } else { - const end = text.indexOf("\n", offset); - if (end < 0) throw new WabtAdmissionError("incomplete_section_row"); - description = text.slice(offset, end).trim(); - offset = end + 1; + const rowEnd = text.indexOf("\n", offset); + if (rowEnd < 0) throw new WabtAdmissionError("incomplete_section_row"); + description = text.slice(offset, rowEnd).trim(); + offset = rowEnd + 1; } - const section = { - kind: match[1] ?? "", - start: Number.parseInt(match[2] ?? "", 16), - end: Number.parseInt(match[3] ?? "", 16), - bytes: Number.parseInt(match[4] ?? "", 16), - description, - }; - const sectionHeaderBytes = section.start - (sections.at(-1)?.end ?? 8); + const sectionHeaderBytes = start - previousEnd; if ( - section.end > artifactBytes || - section.end - section.start !== section.bytes || + end > artifactBytes || + end - start !== bytes || sectionHeaderBytes < 2 || sectionHeaderBytes > 6 ) throw new WabtAdmissionError("section_ranges"); - sections.push(section); + previousEnd = end; + sections.push({ kind, start, end, bytes, description }); } - if (customIndex !== customSectionNames.length) + if (customIndex.value !== customSectionNames.length) throw new WabtAdmissionError("custom_inventory_mismatch"); - if ((sections.at(-1)?.end ?? 8) !== artifactBytes) + if (previousEnd !== artifactBytes) throw new WabtAdmissionError("section_coverage"); const separator = offset + 1; return { diff --git a/src/wasm/WasmGlueAdapter.ts b/src/wasm/WasmGlueAdapter.ts index ca1ae78040..09d54fefb2 100644 --- a/src/wasm/WasmGlueAdapter.ts +++ b/src/wasm/WasmGlueAdapter.ts @@ -1,16 +1,79 @@ import { basename, dirname } from "node:path"; -import * as t from "@babel/types"; +import type * as t from "@babel/types"; import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js"; import { traverseJavaScriptAst } from "../domain/javascript/javascriptSemanticTraversal.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; +const SCHEME_OR_PROTOCOL_RE = /^[a-z][a-z\d+.-]*:|^\/\//iu; +const SKIPPABLE_GLUE_LEAVES = new Set([ + "NumericLiteral", + "BooleanLiteral", + "NullLiteral", + "BigIntLiteral", + "RegExpLiteral", + "ThisExpression", + "Super", +]); + /** * Only the path before the first query/fragment delimiter determines the suffix. - * Query/fragment content can contain any line terminator; one bounded scan suffices. + * Returns the delimiter offset (or `value.length`) when `.wasm` matches, else `-1`. */ -const endsWithWasmReference = (value: string): boolean => { - const delimiter = value.search(/[?#]/u); - return /\.wasm$/iu.test(delimiter < 0 ? value : value.slice(0, delimiter)); +const findWasmReferenceEnd = (value: string): number => { + if (value.length < 5) return -1; + const query = value.indexOf("?"); + const hash = value.indexOf("#"); + const end = + query < 0 + ? hash < 0 + ? value.length + : hash + : hash < 0 + ? query + : Math.min(query, hash); + if (end < 5) return -1; + return value.charCodeAt(end - 5) === 0x2e && + (value.charCodeAt(end - 4) | 0x20) === 0x77 && + (value.charCodeAt(end - 3) | 0x20) === 0x61 && + (value.charCodeAt(end - 2) | 0x20) === 0x73 && + (value.charCodeAt(end - 1) | 0x20) === 0x6d + ? end + : -1; +}; + +const literalNodeValue = (node: t.Node): string | null | undefined => { + switch (node.type) { + case "StringLiteral": + return node.value; + case "DirectiveLiteral": { + const cooked = node.extra?.expressionValue; + return typeof cooked === "string" ? cooked : undefined; + } + case "TemplateLiteral": + return node.expressions.length === 0 + ? node.quasis[0]?.value.cooked + : undefined; + default: + return undefined; + } +}; + +const indexCandidates = ( + candidates: readonly string[], + keyOf: (candidate: string) => string, +): Map => { + const index = new Map(); + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]!; + const key = keyOf(candidate); + let bucket = index.get(key); + if (bucket === undefined) { + bucket = []; + index.set(key, bucket); + } + bucket.push(candidate); + } + return index; }; /** Associate visible literals with selected candidates without asserting data flow or URL identity. */ @@ -36,58 +99,54 @@ export const associateWasmGlue = ( evidence_kind: "static-literal"; }[] = []; if (file === null) return { parse_status: "failed" as const, references }; + let glueDir: string | undefined; + let byAbsolutePath: Map | undefined; + let byBasename: Map | undefined; traverseJavaScriptAst(file, { + skip(node) { + if (node.type === "Identifier") + return ( + node.typeAnnotation == null && (node.decorators?.length ?? 0) === 0 + ); + return SKIPPABLE_GLUE_LEAVES.has(node.type); + }, enter(node) { // Babel retains the source spelling in DirectiveLiteral.value, while // extra.expressionValue is the same cooked value used by StringLiteral. - const directiveValue = t.isDirectiveLiteral(node) - ? node.extra?.expressionValue - : undefined; - const value = t.isStringLiteral(node) - ? node.value - : typeof directiveValue === "string" - ? directiveValue - : t.isTemplateLiteral(node) && node.expressions.length === 0 - ? node.quasis[0]?.value.cooked - : undefined; - if ( - value === undefined || - value === null || - !endsWithWasmReference(value) || - node.loc == null - ) - return; - const stripped = value.split(/[?#]/u)[0] ?? value; + const value = literalNodeValue(node); + if (value === undefined || value === null || node.loc == null) return; + const delimiterEnd = findWasmReferenceEnd(value); + if (delimiterEnd < 0) return; + const hasDelimiter = delimiterEnd < value.length; + const stripped = hasDelimiter ? value.slice(0, delimiterEnd) : value; const local = - !/^[a-z][a-z\d+.-]*:|^\/\//iu.test(value) && - !value.startsWith("/") && - !/[?#]/u.test(value); + !hasDelimiter && + value.charCodeAt(0) !== 0x2f && + !SCHEME_OR_PROTOCOL_RE.test(value); // Compare through the caller-path owner so `.` spellings match and a // symlink followed by `..` is never collapsed onto a sibling. - const target = local - ? absoluteCallerPath(value, { cwd: dirname(path) }) - : undefined; - const exact = - target === undefined - ? [] - : candidates.filter( - (candidate) => absoluteCallerPath(candidate) === target, - ); - const matches = - exact.length > 0 - ? exact - : candidates.filter( - (candidate) => basename(candidate) === basename(stripped), - ); + let exact: readonly string[] | undefined; + if (local && candidates.length > 0) { + glueDir ??= dirname(path); + byAbsolutePath ??= indexCandidates(candidates, (candidate) => + absoluteCallerPath(candidate), + ); + exact = byAbsolutePath.get(absoluteCallerPath(value, { cwd: glueDir })); + } + let matches: readonly string[] | undefined = exact; + if (matches === undefined && candidates.length > 0) { + byBasename ??= indexCandidates(candidates, basename); + matches = byBasename.get(basename(stripped)); + } references.push({ value, line: node.loc.start.line, column: node.loc.start.column, - candidate_paths: [...matches], + candidate_paths: matches === undefined ? [] : [...matches], association: - exact.length > 0 + exact !== undefined ? "local-path-candidate" - : matches.length > 0 + : matches !== undefined ? "basename-candidates" : "unresolved", evidence_kind: "static-literal",