mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
feat(web): deduplicate bundle findings across scripts by value and mechanism (#11354)
* feat(web): deduplicate bundle findings across scripts by value and mechanism Per-script findings were deduplicated only within one script, so the same endpoint or route observed in N scripts appeared N times in the merged bundle, inflating the finding list and overstating the inventory. Merge now deduplicates routes and endpoints across scripts by (value, mechanism). The first occurrence keeps its location and order; later occurrences fold into optional occurrences/script_keys on the retained entry, so no script is silently dropped and single-script findings keep their original shape. The key uses the existing compositeKey helper (JSON) instead of a NUL join. bundleLimitations gains a line describing the cross-script merge. * fix(web): address Greptile review on cross-script bundle dedup - Accept merged endpoint occurrences/script_keys in the web-bundle view row schema so unfiltered pages no longer throw. - Match endpoint script_keys filters against retained script_keys, falling back to location.script_key for older records. - Generate distinct finding keys in the wide-result capacity fixtures so routes/endpoints still exercise a 130,000-entry merged result. - Append later script keys in place instead of rebuilding the list. - Compare the dedup limitation against its owning constant instead of freezing the explanatory sentence in the test. - Update the route-inventory guide for merged endpoints. * test(web): expect the cross-script endpoint merge in the semantic budget case Main added a regression where two budget-limited scripts both report /health. With findings merged across scripts, it is one entry whose occurrences and script_keys name both scripts, which keeps the case's per-script attribution. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --------- Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com> Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
8 files changed
+293
-17
No files matched your search
@@ -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
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 = `
|
||||
|
||||
@@ -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<string, BundleFinding>();
|
||||
const endpointKeys = new Map<string, BundleFinding>();
|
||||
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<string, BundleFinding>,
|
||||
): 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.",
|
||||
];
|
||||
@@ -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,
|
||||
|
||||
@@ -20,9 +20,16 @@ const EXPECTED_BOUNDS: Record<WideCollection, readonly [string, string]> = {
|
||||
inferences: ["/api/first", "/api/last"],
|
||||
};
|
||||
|
||||
const fillWide = <T>(count: number, first: T, middle: T, last: T): T[] => {
|
||||
const items = new Array<T>(count).fill(middle);
|
||||
const fillWide = <T>(
|
||||
count: number,
|
||||
first: T,
|
||||
makeMiddle: (index: number) => T,
|
||||
last: T,
|
||||
): T[] => {
|
||||
const items = new Array<T>(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"),
|
||||
)
|
||||
: [],
|
||||
|
||||
Reference in new issue
Block a user