diff --git a/docs/javascript-route-inventory.md b/docs/javascript-route-inventory.md index db0102bf91..81b35705dd 100644 --- a/docs/javascript-route-inventory.md +++ b/docs/javascript-route-inventory.md @@ -51,8 +51,11 @@ Both row collections accept exact `indices`, `values`, `script_keys`, `fields`, `kinds`. Filters combine with AND, and an explicit empty selector matches no rows. Every row retains its `source_index` in the original collection, including when other fields are omitted. This identity is scoped to the parent Evidence -and collection. Original ordering and separate occurrences of duplicate values -are preserved; request endpoint `location` or inference `basis` for source details. +and collection. Original ordering is preserved. Endpoints are deduplicated +across scripts by value and mechanism: the retained row keeps the first +occurrence's `location`, and `occurrences` and `script_keys` record how many +scripts contained the same finding and which ones; request endpoint +`location` or inference `basis` for source details. Follow `coverage.next_offset` until `coverage.exhausted`; those fields describe the selected rows, independently of producer `completeness`. Each response also diff --git a/src/domain/analysisView/webBundleView.test.ts b/src/domain/analysisView/webBundleView.test.ts index f7a07e403d..d0cc66bd4a 100644 --- a/src/domain/analysisView/webBundleView.test.ts +++ b/src/domain/analysisView/webBundleView.test.ts @@ -223,6 +223,99 @@ it("filters endpoints by values, script_keys, mechanisms, and field projections" expect(item.location).toMatchObject({ script_key: "vendor.js" }); }); +it("returns merged endpoint occurrences and script_keys on an unfiltered page", () => { + const parent = makeParent({ + observations: { + ...sampleWebBundleAnalysis().observations, + endpoints: [ + { + value: "/api/shared", + mechanism: "call:fetch", + location: { script_key: "app.js", line: 10, column: 2 }, + occurrences: 2, + script_keys: ["app.js", "vendor.js"], + }, + { + value: "/api/orders", + mechanism: "call:sendBeacon", + location: { script_key: "app.js", line: 85, column: 4 }, + }, + ], + }, + }); + + const page = query(parent, { + kind: "web-bundle", + collection: "endpoints", + }); + if (page.kind !== "web-bundle") throw new Error("Expected web-bundle page"); + expect(page.items).toEqual([ + { + source_index: 0, + value: "/api/shared", + mechanism: "call:fetch", + location: { script_key: "app.js", line: 10, column: 2 }, + occurrences: 2, + script_keys: ["app.js", "vendor.js"], + }, + { + source_index: 1, + value: "/api/orders", + mechanism: "call:sendBeacon", + location: { script_key: "app.js", line: 85, column: 4 }, + }, + ]); +}); + +it("matches a merged endpoint by any retained script key", () => { + const parent = makeParent({ + observations: { + ...sampleWebBundleAnalysis().observations, + endpoints: [ + { + value: "/api/shared", + mechanism: "call:fetch", + location: { script_key: "app.js", line: 10, column: 2 }, + occurrences: 2, + script_keys: ["app.js", "vendor.js"], + }, + { + value: "/api/orders", + mechanism: "call:sendBeacon", + location: { script_key: "vendor.js", line: 85, column: 4 }, + }, + ], + }, + }); + + const bySecondScript = query(parent, { + kind: "web-bundle", + collection: "endpoints", + script_keys: ["vendor.js"], + fields: ["value"], + }); + if (bySecondScript.kind !== "web-bundle") + throw new Error("Expected web-bundle page"); + expect(bySecondScript.items).toEqual([ + { source_index: 0, value: "/api/shared" }, + { source_index: 1, value: "/api/orders" }, + ]); + + // The merged row also matches its first script; the unmerged row matches + // by its location script key. + const byFirstScript = query(parent, { + kind: "web-bundle", + collection: "endpoints", + script_keys: ["app.js"], + fields: ["value"], + }); + if (byFirstScript.kind !== "web-bundle") + throw new Error("Expected web-bundle page"); + expect(byFirstScript.items).toEqual([ + { source_index: 0, value: "/api/shared" }, + ]); +}); + it("pages inference records and filters by kind (endpoint_candidate)", () => { const parent = makeParent(); const candidatesOnly = query(parent, { diff --git a/src/domain/analysisView/webBundleView.ts b/src/domain/analysisView/webBundleView.ts index 31433beed3..05d20e33a3 100644 --- a/src/domain/analysisView/webBundleView.ts +++ b/src/domain/analysisView/webBundleView.ts @@ -89,6 +89,8 @@ export const webBundleEndpointRowSchema = z.strictObject({ value: endpointSchema.shape.value.optional(), mechanism: endpointSchema.shape.mechanism.optional(), location: sourceLocationSchema.optional(), + occurrences: endpointSchema.shape.occurrences.optional(), + script_keys: endpointSchema.shape.script_keys.optional(), }); export const webBundleInferenceRowSchema = z.strictObject({ @@ -391,7 +393,9 @@ export const projectWebBundleView = ( (indices === undefined || indices.has(index)) && (values === undefined || values.has(row.value)) && (scriptKeys === undefined || - scriptKeys.has(row.location.script_key)) && + (row.script_keys !== undefined + ? row.script_keys.some((key) => scriptKeys.has(key)) + : scriptKeys.has(row.location.script_key))) && (mechanisms === undefined || mechanisms.has(row.mechanism)), (row, source_index) => ({ source_index, diff --git a/src/domain/webBundleAnalysis.ts b/src/domain/webBundleAnalysis.ts index af57133c8b..c91db582de 100644 --- a/src/domain/webBundleAnalysis.ts +++ b/src/domain/webBundleAnalysis.ts @@ -309,6 +309,10 @@ const findingSchema = z.object({ value: z.string(), mechanism: z.string(), location: sourceLocationSchema, + /** Present only when the same finding was merged across scripts. */ + occurrences: z.int().min(1).exactOptional(), + /** Script keys that contained the finding, in first-occurrence order. */ + script_keys: z.array(z.string()).exactOptional(), }); const originalSourceSchema = z.object({ diff --git a/src/domain/webBundleAnalyzer.test.ts b/src/domain/webBundleAnalyzer.test.ts index d3cf97e822..f7fb592b2b 100644 --- a/src/domain/webBundleAnalyzer.test.ts +++ b/src/domain/webBundleAnalyzer.test.ts @@ -7,7 +7,10 @@ import { createWebPageInspection } from "../../tests/support/browser/webPageInsp import { analyzeJavaScriptStaticSource } from "../../tests/fixtures/javascriptStaticAnalysis.js"; import { analyzeCapturedWebScript } from "./webBundleAnalyzer.js"; import { analyzeWebBundleFixture } from "../../tests/support/browser/analyzeWebBundleFixture.js"; -import { buildCapturedWebBundleAnalysis } from "./webBundleAnalyzerResult.js"; +import { + buildCapturedWebBundleAnalysis, + CROSS_SCRIPT_DEDUP_LIMITATION, +} from "./webBundleAnalyzerResult.js"; import { webBundleAnalysisSchema } from "./webBundleAnalysis.js"; import { isIncludedScript } from "./webBundleAnalyzerState.js"; import { webBundleScriptAnalysisSchema } from "./webBundleScriptAnalysis.js"; @@ -1063,6 +1066,110 @@ describe("web bundle endpoint candidate classification", () => { }); }); +describe("web bundle cross-script finding deduplication", () => { + it("merges the same endpoint across scripts and keeps first occurrence order", () => { + const firstCapture = inspection("fetch('/shared'); fetch('/only-first');"); + const secondScript = inspection("fetch('/shared'); fetch('/only-second');") + .scripts.items[0]; + if (secondScript === undefined) + throw new Error("Missing second script fixture"); + const firstKey = firstCapture.scripts.items[0]?.script_key; + if (firstKey === undefined) throw new Error("Missing first script fixture"); + const secondKey = `scr_${"2".repeat(64)}`; + firstCapture.scripts.items.push({ + ...secondScript, + script_key: secondKey, + url: `${origin}/assets/second.js`, + }); + firstCapture.scripts.total += 1; + + const result = analyzeWebBundleFixture(firstCapture); + const endpoints = result.observations.endpoints; + expect(endpoints.map(({ value }) => value)).toEqual([ + "/shared", + "/only-first", + "/only-second", + ]); + const shared = endpoints[0]; + expect(shared).toMatchObject({ + value: "/shared", + mechanism: "call:fetch", + occurrences: 2, + script_keys: [firstKey, secondKey], + }); + expect(shared?.location.script_key).toBe(firstKey); + expect(endpoints[1]).not.toHaveProperty("occurrences"); + expect(endpoints[1]).not.toHaveProperty("script_keys"); + expect(endpoints[2]).not.toHaveProperty("occurrences"); + expect(webBundleAnalysisSchema.parse(result)).toEqual(result); + expect(result.limitations).toContain(CROSS_SCRIPT_DEDUP_LIMITATION); + }); + + it("merges the same route across scripts", () => { + const firstCapture = inspection( + 'const routes = [{ path: "/users" }, { path: "/only-first" }];', + ); + const secondScript = inspection( + 'const routes = [{ path: "/users" }, { path: "/only-second" }];', + ).scripts.items[0]; + if (secondScript === undefined) + throw new Error("Missing second script fixture"); + const firstKey = firstCapture.scripts.items[0]?.script_key; + if (firstKey === undefined) throw new Error("Missing first script fixture"); + const secondKey = `scr_${"2".repeat(64)}`; + firstCapture.scripts.items.push({ + ...secondScript, + script_key: secondKey, + url: `${origin}/assets/second.js`, + }); + firstCapture.scripts.total += 1; + + const result = analyzeWebBundleFixture(firstCapture); + const routes = result.observations.routes; + expect(routes.map(({ value }) => value)).toEqual([ + "/users", + "/only-first", + "/only-second", + ]); + expect(routes[0]).toMatchObject({ + value: "/users", + occurrences: 2, + script_keys: [firstKey, secondKey], + }); + expect(routes[0]?.location.script_key).toBe(firstKey); + expect(webBundleAnalysisSchema.parse(result)).toEqual(result); + }); + + it("keeps the same endpoint value under different mechanisms separate", () => { + const firstCapture = inspection("fetch('/shared');"); + const secondScript = inspection( + 'const xhr = new XMLHttpRequest(); xhr.open("GET", "/shared");', + ).scripts.items[0]; + if (secondScript === undefined) + throw new Error("Missing second script fixture"); + const secondKey = `scr_${"2".repeat(64)}`; + firstCapture.scripts.items.push({ + ...secondScript, + script_key: secondKey, + url: `${origin}/assets/second.js`, + }); + firstCapture.scripts.total += 1; + + const result = analyzeWebBundleFixture(firstCapture); + const endpoints = result.observations.endpoints; + expect(endpoints.map(({ value, mechanism }) => [value, mechanism])).toEqual( + [ + ["/shared", "call:fetch"], + ["/shared", "call:xhr.open"], + ], + ); + expect(endpoints.every((entry) => entry.occurrences === undefined)).toBe( + true, + ); + expect(webBundleAnalysisSchema.parse(result)).toEqual(result); + }); +}); + describe("web bundle method-first request candidates", () => { it("reads the exact target after an HTTP method token in both analyzers", () => { const source = ` diff --git a/src/domain/webBundleAnalyzerResult.ts b/src/domain/webBundleAnalyzerResult.ts index 373bf99722..ece10f3bb3 100644 --- a/src/domain/webBundleAnalyzerResult.ts +++ b/src/domain/webBundleAnalyzerResult.ts @@ -19,6 +19,7 @@ import { type WebBundleScriptAnalysis, } from "./webBundleScriptAnalysis.js"; import { appendAll } from "./appendAll.js"; +import { compositeKey } from "./unicodeCodePointOrder.js"; export const buildCapturedWebBundleAnalysis = ( inspection: WebPageInspection, @@ -212,6 +213,8 @@ const mergeScriptResults = ( results: readonly WebBundleScriptAnalysis[], ): AnalysisAccumulator => { const accumulator = createWebBundleAnalysisAccumulator(); + const routeKeys = new Map(); + const endpointKeys = new Map(); for (const result of results) { if (result.status === "unavailable") { // A refused script still parsed; its text inferences remain. @@ -233,8 +236,16 @@ const mergeScriptResults = ( if (result.widened_return_references) accumulator.widenedScripts.push(result.script_key); appendAll(accumulator.edges, result.observations.edges); - appendAll(accumulator.routes, result.observations.routes); - appendAll(accumulator.endpoints, result.observations.endpoints); + appendDeduplicatedFindings( + accumulator.routes, + result.observations.routes, + routeKeys, + ); + appendDeduplicatedFindings( + accumulator.endpoints, + result.observations.endpoints, + endpointKeys, + ); appendAll( accumulator.unresolvedEndpoints, result.observations.unresolved_endpoints, @@ -245,6 +256,39 @@ const mergeScriptResults = ( return accumulator; }; +type BundleFinding = AnalysisAccumulator["routes"][number]; + +/** + * Merge per-script findings across scripts by (value, mechanism). The first + * occurrence keeps its location; later occurrences are folded into + * occurrences/script_keys so no script is silently dropped. Findings that + * appear in only one script keep their original shape. + */ +const appendDeduplicatedFindings = ( + target: BundleFinding[], + findings: readonly BundleFinding[], + seen: Map, +): void => { + for (const finding of findings) { + const key = compositeKey([finding.value, finding.mechanism]); + const retained = seen.get(key); + if (retained === undefined) { + seen.set(key, finding); + target.push(finding); + continue; + } + retained.occurrences = (retained.occurrences ?? 1) + 1; + if (retained.script_keys === undefined) { + retained.script_keys = [ + retained.location.script_key, + finding.location.script_key, + ]; + } else { + retained.script_keys.push(finding.location.script_key); + } + } +}; + const buildCaptureObservation = ( inspection: WebPageInspection, sourceScripts: IncludedScript[], @@ -512,10 +556,19 @@ const buildCompleteness = ( visited_ast_nodes: input.visitedNodes, }); +/** + * Reported when findings are merged across scripts. Wording may change, but + * the limitation itself must stay so callers know the retained location is + * the first occurrence only. + */ +export const CROSS_SCRIPT_DEDUP_LIMITATION = + "Routes and endpoints are deduplicated across scripts by value and mechanism; the retained entry keeps the first occurrence's location, and occurrences and script_keys record the scripts that contained the same finding."; + const bundleLimitations = (): WebBundleAnalysis["limitations"] => [ "Static bundle findings are observations or bounded inferences; REA does not execute captured JavaScript.", "Bare string arguments of unbound HTTP-method-named calls are low-confidence endpoint candidates; form, translation, storage and other APIs can use the same syntax. URL-shaped findings still do not prove network execution.", 'Endpoint candidates are deduplicated by script, value and detector; basis retains only the first matching source coordinate. They are not a complete call-site inventory or a runtime occurrence count. completeness.status="complete" describes examination of captured source, not a call-site census.', + CROSS_SCRIPT_DEDUP_LIMITATION, "String-built routes and endpoints, encrypted configuration, and server-side behavior may remain unknown.", "Page-declared WebMCP metadata is untrusted and is never registered or invoked as an REA tool.", ]; diff --git a/src/domain/webBundleSemanticLimits.test.ts b/src/domain/webBundleSemanticLimits.test.ts index b424c60ea7..9631c960c0 100644 --- a/src/domain/webBundleSemanticLimits.test.ts +++ b/src/domain/webBundleSemanticLimits.test.ts @@ -107,11 +107,16 @@ it("attributes each reached budget to its own script and preserves unaffected sc [results[0]!.script_key], [results[1]!.script_key], ]); - expect(report.observations.endpoints.map((entry) => entry.value)).toEqual([ - "/health", - "/health", - "/unaffected", + // The same endpoint from both limited scripts merges and keeps both scripts. + expect(report.observations.endpoints).toMatchObject([ + { + value: "/health", + occurrences: 2, + script_keys: [results[0]!.script_key, results[1]!.script_key], + }, + { value: "/unaffected" }, ]); + expect(report.observations.endpoints).toHaveLength(2); expect(report.completeness).toMatchObject({ status: "partial", parsed_scripts: 3, diff --git a/tests/boundary/browser/webBundleResultCapacity.test.ts b/tests/boundary/browser/webBundleResultCapacity.test.ts index 6f505e7310..a8b8de21ca 100644 --- a/tests/boundary/browser/webBundleResultCapacity.test.ts +++ b/tests/boundary/browser/webBundleResultCapacity.test.ts @@ -20,9 +20,16 @@ const EXPECTED_BOUNDS: Record = { inferences: ["/api/first", "/api/last"], }; -const fillWide = (count: number, first: T, middle: T, last: T): T[] => { - const items = new Array(count).fill(middle); +const fillWide = ( + count: number, + first: T, + makeMiddle: (index: number) => T, + last: T, +): T[] => { + const items = new Array(count); items[0] = first; + for (let index = 1; index < count - 1; index += 1) + items[index] = makeMiddle(index); items[count - 1] = last; return items; }; @@ -80,7 +87,7 @@ const buildWideScriptResult = ( ? fillWide( count, makeEdge("./first.js"), - makeEdge("./mid.js"), + () => makeEdge("./mid.js"), makeEdge("./last.js"), ) : [], @@ -89,7 +96,7 @@ const buildWideScriptResult = ( ? fillWide( count, makeFinding("/first", "router"), - makeFinding("/mid", "router"), + (index) => makeFinding(`/mid-${index}`, "router"), makeFinding("/last", "router"), ) : [], @@ -98,7 +105,7 @@ const buildWideScriptResult = ( ? fillWide( count, makeFinding("/api/first", "fetch"), - makeFinding("/api/mid", "fetch"), + (index) => makeFinding(`/api/mid-${index}`, "fetch"), makeFinding("/api/last", "fetch"), ) : [], @@ -107,7 +114,7 @@ const buildWideScriptResult = ( ? fillWide( count, makeWebMcp("firstTool"), - makeWebMcp("midTool"), + () => makeWebMcp("midTool"), makeWebMcp("lastTool"), ) : [], @@ -118,7 +125,7 @@ const buildWideScriptResult = ( ? fillWide( count, makeInference("/api/first"), - makeInference("/api/mid"), + () => makeInference("/api/mid"), makeInference("/api/last"), ) : [],