Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
Kaoru0822
2026-10-14 00:31:27 +00:00
559 changed files with 102122 additions and 35266 deletions
+25 -1
View File
@@ -65,7 +65,7 @@ export abstract class AnalysisError extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>> | undefined;
readonly capturedOutput: AnalysisCapturedOutput | undefined;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupIncomplete: boolean;
cleanupIncomplete: boolean;
readonly cleanupResources: readonly string[];
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
@@ -89,6 +89,30 @@ export abstract class AnalysisError extends Error {
partialObservation: AnalysisPartialObservation | undefined;
readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined;
/** Retain a later lifecycle failure without replacing the original typed error. */
retainSecondaryFailure(
failure: AnalysisError,
diagnostics: Readonly<Record<string, JsonValue>>,
): this {
// Secondary resources remain owned by their cleanup lifecycle; preserve
// the primary error's live cleanup status and original output.
Object.assign(this, {
diagnostics: structuredClone({ ...this.diagnostics, ...diagnostics }),
cause: new AggregateError(
this.cause === undefined ? [failure] : [this.cause, failure],
"Analysis failed and a later lifecycle operation also failed.",
{ cause: this.cause },
),
});
return this;
}
/** Clear live cleanup status only after its owning resource confirms retry success. */
resolveCleanup(): this {
this.cleanupIncomplete = false;
return this;
}
/** Retain a completed observation when a later step fails. */
retainPartialObservation(observation: AnalysisPartialObservation): this {
this.partialObservation ??= observation;
+3 -1
View File
@@ -86,13 +86,15 @@ export interface AnalysisInputIssue {
/** Provider output failed provider-neutral application parsing. */
export class AnalysisOutputError extends AnalysisError {
readonly _tag = "AnalysisOutputError";
readonly cleanupOnly: boolean;
constructor(
readonly operation: string,
readonly reason: string,
options?: AnalysisErrorOptions,
options?: AnalysisErrorOptions & { readonly cleanupOnly?: boolean },
) {
super(`Invalid analysis output for ${operation}: ${reason}`, options);
this.cleanupOnly = options?.cleanupOnly ?? false;
}
}
@@ -796,3 +796,32 @@ describe("analysis error projection: evidence files", () => {
},
);
});
it("retains the primary failure and both cleanup reports after a secondary failure", () => {
const primary = new AnalysisCancelledError("execute_rizin_command", {
capturedOutput: {
stdout: "partial",
stderr: "diagnostic",
truncated: false,
},
cleanup: { reason: "writer remains", resources: ["writer"] },
});
const secondary = new AnalysisOutputError("open_binary", "cannot rebind", {
cleanup: { reason: "provider remains", resources: ["provider", "writer"] },
});
const enriched = primary.retainSecondaryFailure(secondary, {
rebind_error: projectAnalysisError(secondary),
});
expect(enriched).toBe(primary);
expect(enriched._tag).toBe("AnalysisCancelledError");
expect(projectAnalysisError(enriched)).toMatchObject({
code: "cleanup_incomplete",
details: {
execution_failure: "cancelled",
resources: ["writer"],
cleanup_reason: "writer remains",
captured_output: { stdout: "partial", stderr: "diagnostic" },
diagnostics: { rebind_error: { code: "cleanup_incomplete" } },
},
});
});
+3 -3
View File
@@ -447,8 +447,8 @@ const lifecycleErrorDetails = (
if (error instanceof AnalysisCancelledError)
return {
operation: error.operation,
cleanup: error.cleanup === undefined ? "complete" : "incomplete",
...(error.cleanup === undefined
cleanup: error.cleanupIncomplete ? "incomplete" : "complete",
...(error.cleanup === undefined || !error.cleanupIncomplete
? {}
: {
cleanup_reason: error.cleanup.reason,
@@ -462,7 +462,7 @@ const lifecycleErrorDetails = (
return {
operation: error.operation,
timeout_ms: error.timeoutMs,
...(error.cleanup === undefined
...(error.cleanup === undefined || !error.cleanupIncomplete
? {}
: {
cleanup: "incomplete",
@@ -26,6 +26,36 @@ const add = (
if (!result.ok) throw result.error;
};
it("bounds query parser expansion before publishing or merging observed names", () => {
const accumulator = new WebNetworkApiSurfaceAccumulator(64 * 1024, true);
add(accumulator, record(0, "/products?kept=1"));
const before = accumulator.page(0, 1);
expect(
accumulator.add(record(1, `/products?${"x=1&".repeat(200)}`)),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisResourceConstraintError" },
});
expect(accumulator.page(0, 1)).toEqual(before);
add(accumulator, record(2, "/products?after=2"));
expect(accumulator.page(0, 1).groups[0]?.query_parameter_names).toEqual([
{ name: "after", record_ordinals: [2] },
{ name: "kept", record_ordinals: [0] },
]);
});
it("charges each retained name once and each name's ordinal once per request", () => {
const accumulator = new WebNetworkApiSurfaceAccumulator(1024 * 1024, true);
for (let ordinal = 0; ordinal < 1000; ordinal += 1)
add(accumulator, record(ordinal, "/products?category=one&category=two"));
expect(accumulator.page(0, 1).groups[0]?.query_parameter_names).toEqual([
{
name: "category",
record_ordinals: Array.from({ length: 1000 }, (_, index) => index),
},
]);
});
it("admits the capture schema clone and grouping against the same budget", () => {
const sample = record(0, `/${"a".repeat(1200)}`);
const isolated = new WebNetworkApiSurfaceAccumulator(64 * 1024);
@@ -5,7 +5,10 @@ import {
} from "../analysisErrorCore.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js";
import { parseRecordedTransportUrl } from "../recordedTransportUrl.js";
import {
parseRecordedTransportUrl,
parseUrlQueryParameterNames,
} from "../recordedTransportUrl.js";
import { err, ok, type Result } from "../result.js";
import { MAX_JSON_DEPTH } from "../jsonValue.js";
import {
@@ -41,6 +44,7 @@ interface GroupState {
readonly ordinals: number[];
readonly statuses: Set<number>;
readonly contentTypes: Set<string>;
readonly queryNames?: Map<string, number[]>;
}
type Buckets = Map<string, Map<string, Map<string, Map<string, GroupState>>>>;
@@ -120,7 +124,10 @@ export class WebNetworkApiSurfaceAccumulator {
#retainedBytes = 0;
#temporaryBytes = 0;
constructor(readonly maximumBytes = WEB_NETWORK_CAPTURE_LIMITS.outputBytes) {}
constructor(
readonly maximumBytes = WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
readonly includeQueryParameterNames = false,
) {}
#retain(bytes: number): boolean {
if (this.#retainedBytes + this.#temporaryBytes + bytes > this.maximumBytes)
@@ -305,7 +312,9 @@ export class WebNetworkApiSurfaceAccumulator {
if (!this.#temporary(RECORD_SCRATCH_BYTES + textBytes(url.length)))
return this.#overBudget();
try {
const parsed = parseRecordedTransportUrl(url);
const parsed = parseRecordedTransportUrl(url, {
includeQuery: this.includeQueryParameterNames,
});
if (parsed.origin === null)
return this.#exclude(record.ordinal, "url-unparseable");
if (typeof method !== "string" || method.length === 0)
@@ -325,6 +334,8 @@ export class WebNetworkApiSurfaceAccumulator {
return this.#overBudget();
const route = this.#route(parsed.path);
if (!route.ok) return route;
const queryNames = this.#queryNames(parsed.query);
if (!queryNames.ok) return queryNames;
return this.#append(
record.ordinal,
method,
@@ -332,6 +343,7 @@ export class WebNetworkApiSurfaceAccumulator {
route.value,
typeof status === "number" && status !== 0 ? status : null,
mediaTypeEssence(rawMime),
queryNames.value,
);
} finally {
// Per-record strings and descriptors never become cumulative scratch.
@@ -339,6 +351,26 @@ export class WebNetworkApiSurfaceAccumulator {
}
}
#queryNames(
query: string | undefined,
): Result<ReadonlySet<string> | undefined, AnalysisError> {
if (query === undefined) return ok(undefined);
// Reserve form-parser tuples, decoded strings, the iterator and the name
// set before URLSearchParams materializes them. Delimiter count is an upper
// bound: empty query pairs are ignored by the WHATWG parser.
let pairs = query.length > 1 ? 1 : 0;
for (const character of query) if (character === "&") pairs += 1;
if (
!this.#temporary(
RECORD_SCRATCH_BYTES +
textBytes(query.length) +
pairs * ENTRY_BYTES * 4,
)
)
return this.#overBudget();
return ok(new Set(parseUrlQueryParameterNames(query)));
}
#append(
ordinal: number,
method: string,
@@ -346,6 +378,7 @@ export class WebNetworkApiSurfaceAccumulator {
route: Route,
status: number | null,
mime: string | null,
queryNames: ReadonlySet<string> | undefined,
): Result<void, AnalysisError> {
let group = this.#buckets
.get(method)
@@ -371,6 +404,14 @@ export class WebNetworkApiSurfaceAccumulator {
if (status !== null && !group?.statuses.has(status)) bytes += ENTRY_BYTES;
if (mime !== null && !group?.contentTypes.has(mime))
bytes += ENTRY_BYTES + textBytes(mime.length);
if (queryNames !== undefined) {
if (group === undefined) bytes += CAPTURE_CONTAINER_BYTES;
for (const name of queryNames) {
bytes += ENTRY_BYTES; // This name's source ordinal, once per record.
if (!group?.queryNames?.has(name))
bytes += ENTRY_BYTES + textBytes(name.length);
}
}
// Reserve the whole mutation while route scratch is still live. No sets,
// map entries, arrays or new observed values are retained before admission.
if (!this.#retain(bytes)) return this.#overBudget();
@@ -387,6 +428,7 @@ export class WebNetworkApiSurfaceAccumulator {
ordinals: [],
statuses: new Set(),
contentTypes: new Set(),
...(queryNames === undefined ? {} : { queryNames: new Map() }),
};
const byOrigin = this.#buckets.get(method) ?? new Map();
this.#buckets.set(method, byOrigin);
@@ -404,6 +446,13 @@ export class WebNetworkApiSurfaceAccumulator {
if (status === null || mime === null) this.#unavailableResponse = true;
if (status !== null) group.statuses.add(status);
if (mime !== null) group.contentTypes.add(mime);
if (queryNames !== undefined && group.queryNames !== undefined) {
for (const name of queryNames) {
const ordinals = group.queryNames.get(name);
if (ordinals === undefined) group.queryNames.set(name, [ordinal]);
else ordinals.push(ordinal);
}
}
return ok(undefined);
}
@@ -440,6 +489,16 @@ export class WebNetworkApiSurfaceAccumulator {
record_ordinals: [...group.ordinals],
statuses: [...group.statuses].sort((a, b) => a - b),
content_types: [...group.contentTypes].sort(compare),
...(group.queryNames === undefined
? {}
: {
query_parameter_names: [...group.queryNames]
.sort(([a], [b]) => compare(a, b))
.map(([name, record_ordinals]) => ({
name,
record_ordinals: [...record_ordinals],
})),
}),
flags: [
...(group.ordinals.length === 1 ? ["single-sample" as const] : []),
...(group.statuses.size > 1 ? ["mixed-statuses" as const] : []),
@@ -1,3 +1,4 @@
import { boundedViewMessages } from "./analysisViewCoverage.js";
import { expect, it } from "vitest";
import { functionDossierSchema } from "../hopperValues.js";
@@ -717,6 +718,159 @@ it("retains semantic coverage and limitations in a summary", () => {
});
});
it.each([63, 64, 65, 10_000])(
"bounds and deduplicates %i messages in JavaScript and layout views",
(count) => {
const messages = Array.from(
{ length: count },
(_, index) => `Module ${String(index).padStart(5, "0")} was not parsed.`,
);
const analysis = analysisViewJavaScriptAnalysis();
const { graph_id: _graphId, ...semantic } = analysis.semantic_graph;
const parent = javascriptParent({
...analysis,
limitations: messages,
semantic_graph: createJavaScriptSemanticGraph({
...semantic,
limitations: messages.slice(0, 1),
}),
});
const duplicatedParent = { ...parent, limitations: messages };
const notice = (
omitted: number,
field: "limitations" | "unknowns",
evidenceId: string,
) =>
`${String(omitted)} additional ${field} omitted from this view; consult source parent Evidence ${evidenceId} for the complete list (the caller-supplied record, or its retaining session).`;
for (const view of [
{ kind: "summary" },
{ kind: "page", collection: "modules", offset: 0, limit: 1 },
] as const) {
const result = projectAnalysisView(duplicatedParent, view);
if (!result.ok) throw result.error;
if (count <= 65) {
expect(result.value.limitations).toEqual(messages);
expect(result.value.unknowns).toEqual(
[...messages, "semantic_graph.coverage.status is unknown"].sort(),
);
} else {
const limitations = result.value.limitations;
const unknowns = result.value.unknowns;
expect(limitations.length).toBeGreaterThan(65);
expect(limitations.at(-1)).toBe(
notice(
count - limitations.length + 1,
"limitations",
parent.evidenceId,
),
);
expect(unknowns.length).toBeGreaterThan(65);
expect(unknowns.at(-1)).toBe(
notice(
count + 1 - unknowns.length + 1,
"unknowns",
parent.evidenceId,
),
);
}
}
const layout = layoutParent();
const layoutWithMessages = {
...layout,
limitations: messages,
normalizedResult: {
...analysisViewLayoutFixture(),
limitations: messages,
},
};
for (const view of [
{ kind: "summary" },
{ kind: "page", collection: "sections", offset: 0, limit: 1 },
] as const) {
const result = projectAnalysisView(layoutWithMessages, view);
if (!result.ok) throw result.error;
if (count <= 65) expect(result.value.limitations).toEqual(messages);
else {
expect(result.value.limitations.length).toBeGreaterThan(65);
expect(result.value.limitations.at(-1)).toBe(
notice(
count - result.value.limitations.length + 1,
"limitations",
layout.evidenceId,
),
);
}
}
},
);
it.each(["partial", "unknown"] as const)(
"preserves %s parent graph completeness when a module page is exhausted",
(status) => {
const analysis = analysisViewJavaScriptAnalysis();
const first = analysis.graph.nodes[0];
if (first === undefined) throw new Error("missing module");
const unknown = createJavaScriptApplicationNode({
kind: "unknown",
identity: {
strategy: "observation-fingerprint",
stability: "observation-only",
observation_sha256: "8".repeat(64),
scope: "unclassified module",
},
observations: first.observations.map((observation) => ({
label: "unclassified module",
properties: {},
evidence: observation.evidence,
})),
});
const messages = [
...Array.from(
{ length: 65 },
(_, index) =>
`Module ${String(index).padStart(5, "0")} was not parsed.`,
),
"z".repeat(300_000),
];
const { graph_id: _applicationId, ...application } = analysis.graph;
const graph = createJavaScriptApplicationGraph({
...application,
nodes: [...application.nodes, unknown],
limitations: messages.slice(0, 1),
coverage: { ...application.coverage, status, omitted_count: null },
});
const bound = analysisViewBindJavaScriptGraphs(analysis, graph);
const { graph_id: _semanticId, ...semantic } = bound.semantic_graph;
const parent = javascriptParent({
...bound,
limitations: messages,
semantic_graph: createJavaScriptSemanticGraph({
...semantic,
limitations: messages.slice(0, 1),
}),
});
for (const view of [
{ kind: "page", collection: "modules", offset: 0, limit: 10 },
{
kind: "item",
collection: "modules",
selector: { path: "renderer.js" },
},
] as const) {
const result = projectAnalysisView(parent, view);
if (!result.ok) throw result.error;
expect(result.value.coverage.exhausted).toBe(true);
expect(result.value.unknowns).toEqual([
"1 application graph unknowns remain in the parent Evidence.",
...messages.slice(0, 65),
`graph.coverage.status is ${status}`,
"semantic_graph.coverage.status is unknown",
`1 additional unknowns omitted from this view; consult source parent Evidence ${parent.evidenceId} for the complete list (the caller-supplied record, or its retaining session).`,
]);
}
},
);
it("does not match unavailable layout names using a display placeholder", () => {
const layout = analysisViewLayoutFixture();
const section = layout.sections[2];
@@ -793,6 +947,35 @@ it("rejects unsupported parent operations and incompatible collections", () => {
});
});
it("keeps the complete unique set when it fits the byte budget", () => {
const messages = ["a".repeat(2_400), "b".repeat(2_400)];
expect(
boundedViewMessages(messages, `ev_${"a".repeat(64)}`, "limitations"),
).toEqual(messages);
});
it("does not impose a message-count cutoff below the byte budget", () => {
const messages = Array.from(
{ length: 100 },
(_, index) => `message ${String(index).padStart(2, "0")}`,
);
expect(
boundedViewMessages(messages, `ev_${"a".repeat(64)}`, "limitations"),
).toEqual(messages.toSorted());
});
it("bounds repeated view messages even when fewer than 64 source strings are huge", () => {
const oversized = ["\u0000".repeat(300_000), "\\".repeat(300_000)];
const projected = boundedViewMessages(
oversized,
`ev_${"a".repeat(64)}`,
"limitations",
);
expect(projected).toHaveLength(1);
expect(projected[0]).toContain("2 additional limitations omitted");
expect(Buffer.byteLength(JSON.stringify(projected))).toBeLessThan(256 * 1024);
});
it("preserves selected native facet unavailability instead of an exhausted empty page", () => {
const parent = nativeParent({
...functionDossierSchema.parse(ghidraFunctionDossier()),
@@ -1,4 +1,6 @@
import { uniqueSorted } from "../canonicalOrdering.js";
import type { AnalysisViewCoverage } from "./analysisView.js";
/** Coverage for a summary, facet, or single selected object. */
export const completeWithinViewCoverage = (
examined: number,
@@ -26,3 +28,45 @@ export const pageViewCoverage = (
exhausted,
};
};
/** Per-field repeated MCP message budget, independent of the selected page. */
export const ANALYSIS_VIEW_MESSAGE_BYTE_LIMIT = 256 * 1024;
// A UTF-16 unit needs at most six JSON bytes, or twelve when that JSON is
// escaped into MCP text. Reserve both forms across three Evidence projections.
// This upper bound rejects giant messages without allocating their JSON copies.
const messageWireBytes = (value: string): number => (value.length * 18 + 6) * 3;
/** Deduplicate and bound messages by count and repeated serialized bytes. */
export const boundedViewMessages = (
values: readonly string[],
parentEvidenceId: string,
field: "limitations" | "unknowns",
required: readonly string[] = [],
): string[] => {
const priority = uniqueSorted(required);
const unique = uniqueSorted([...priority, ...values]);
const notice = (omitted: number): string =>
`${String(omitted)} additional ${field} omitted from this view; consult source parent Evidence ${parentEvidenceId} for the complete list (the caller-supplied record, or its retaining session).`;
const totalBytes = unique.reduce(
(total, value) => total + messageWireBytes(value),
0,
);
if (totalBytes <= ANALYSIS_VIEW_MESSAGE_BYTE_LIMIT) return unique;
// Reserve notice space only after proving the complete source set does not fit.
let remaining =
ANALYSIS_VIEW_MESSAGE_BYTE_LIMIT - messageWireBytes(notice(unique.length));
const retained = new Set<string>();
for (const value of [...priority, ...unique]) {
if (retained.has(value)) continue;
const bytes = messageWireBytes(value);
if (bytes > remaining) continue;
retained.add(value);
remaining -= bytes;
}
const omitted = unique.length - retained.size;
return omitted === 0
? unique
: [...uniqueSorted([...retained]), notice(omitted)];
};
+11 -3
View File
@@ -3,7 +3,6 @@ import {
type AnalysisInputIssue,
} from "../analysisErrorCore.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import type { BinaryLayout } from "../native/binaryLayout.js";
import { err, ok, type Result } from "../result.js";
import type {
@@ -12,6 +11,7 @@ import type {
UnsignedAnalysisView,
} from "./analysisView.js";
import {
boundedViewMessages,
completeWithinViewCoverage as completeCoverage,
pageViewCoverage as pageCoverage,
} from "./analysisViewCoverage.js";
@@ -126,8 +126,16 @@ const parentFields = (parent: AnalysisViewParent, layout: BinaryLayout) => ({
path: layout.artifact.path,
sha256: layout.artifact.sha256,
},
limitations: uniqueSorted([...parent.limitations, ...layout.limitations]),
unknowns: uniqueSorted([...layoutUnknowns(layout)]),
limitations: boundedViewMessages(
[...parent.limitations, ...layout.limitations],
parent.evidenceId,
"limitations",
),
unknowns: boundedViewMessages(
layoutUnknowns(layout),
parent.evidenceId,
"unknowns",
),
});
const layoutSummary = (layout: BinaryLayout) => ({
@@ -3,12 +3,12 @@ import {
type AnalysisInputIssue,
} from "../analysisErrorCore.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { jsonObjectSchema, type JsonValue } from "../jsonValue.js";
import type { JavaScriptApplicationAnalysisResult } from "../javascript/javascriptApplicationAnalysis.js";
import type { ApplicationNode } from "../javascript/javascriptApplicationGraphSchemas.js";
import { err, ok, type Result } from "../result.js";
import {
boundedViewMessages,
completeWithinViewCoverage as completeCoverage,
pageViewCoverage as pageCoverage,
} from "./analysisViewCoverage.js";
@@ -136,23 +136,20 @@ const applicationUnknownCount = (
0,
);
const javascriptUnknowns = (
const javascriptCoverageUnknowns = (
analysis: JavaScriptApplicationAnalysisResult,
): readonly string[] => {
const unknowns = [
...analysis.limitations,
...analysis.graph.limitations,
...analysis.semantic_graph.limitations,
];
const unknowns: string[] = [];
if (analysis.graph.coverage.status !== "complete")
unknowns.push(`graph.coverage.status is ${analysis.graph.coverage.status}`);
if (analysis.semantic_graph.coverage.status !== "complete")
unknowns.push(
`semantic_graph.coverage.status is ${analysis.semantic_graph.coverage.status}`,
);
if (applicationUnknownCount(analysis) > 0)
const applicationUnknowns = applicationUnknownCount(analysis);
if (applicationUnknowns > 0)
unknowns.push(
`${String(applicationUnknownCount(analysis))} application graph unknowns remain in the parent Evidence.`,
`${String(applicationUnknowns)} application graph unknowns remain in the parent Evidence.`,
);
if (analysis.semantic_graph.unknowns.length > 0)
unknowns.push(
@@ -164,22 +161,33 @@ const javascriptUnknowns = (
const parentFields = (
parent: AnalysisViewParent,
analysis: JavaScriptApplicationAnalysisResult,
) => ({
parent_evidence_id: parent.evidenceId,
parent_operation: "analyze_javascript_application" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: {
path: analysis.input_path,
sha256: analysis.root_artifact_sha256,
},
limitations: uniqueSorted([
...parent.limitations,
) => {
const limitations = [
...analysis.limitations,
...analysis.graph.limitations,
...analysis.semantic_graph.limitations,
]),
unknowns: uniqueSorted([...javascriptUnknowns(analysis)]),
});
];
return {
parent_evidence_id: parent.evidenceId,
parent_operation: "analyze_javascript_application" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: {
path: analysis.input_path,
sha256: analysis.root_artifact_sha256,
},
limitations: boundedViewMessages(
[...parent.limitations, ...limitations],
parent.evidenceId,
"limitations",
),
unknowns: boundedViewMessages(
limitations,
parent.evidenceId,
"unknowns",
javascriptCoverageUnknowns(analysis),
),
};
};
const selectModule = (
modules: ReturnType<typeof moduleEntries>,
@@ -10,6 +10,7 @@ const project = (
offset = 0,
limit = 50,
parameters: unknown = { sensitive_value_count: 0 },
includeQueryParameterNames?: boolean,
) => {
const parent = analysisViewCaptureEvidence(capture);
return projectAnalysisView(
@@ -20,9 +21,111 @@ const project = (
limitations: [],
parameters,
},
{ kind: "api-surface", offset, limit },
{
kind: "api-surface",
offset,
limit,
...(includeQueryParameterNames === undefined
? {}
: {
include_query_parameter_names: includeQueryParameterNames,
}),
},
);
};
it("selects query names without values, retains source ordinals and leaves default groups unchanged", () => {
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 3);
capture.total_records = 3;
const urls = [
"https://api.test/products?category=books&page=1&category=repeat#fragment-only",
"https://api.test/products?category=games&sort=price",
"https://api.test/health",
];
for (const [index, record] of capture.records.entries())
record.reported = {
request: { method: "GET", url: urls[index]! },
response: { status: 200, content: { mimeType: "application/json" } },
};
const selected = project(capture, 0, 50, { sensitive_value_count: 0 }, true);
const omitted = project(capture);
const disabled = project(capture, 0, 50, { sensitive_value_count: 0 }, false);
if (
!selected.ok ||
selected.value.kind !== "api-surface" ||
!omitted.ok ||
omitted.value.kind !== "api-surface" ||
!disabled.ok ||
disabled.value.kind !== "api-surface"
)
throw new Error("Expected surfaces");
expect(disabled.value.groups).toEqual(omitted.value.groups);
expect(selected.value.groups).toEqual([
{ ...omitted.value.groups[0], query_parameter_names: [] },
{
...omitted.value.groups[1],
query_parameter_names: [
{ name: "category", record_ordinals: [0, 1] },
{ name: "page", record_ordinals: [0] },
{ name: "sort", record_ordinals: [1] },
],
},
]);
for (const literal of ["books", "games", "repeat", "price", "fragment-only"])
expect(JSON.stringify(selected.value)).not.toContain(literal);
expect(selected.value.parent_evidence_id).toBe(
omitted.value.parent_evidence_id,
);
});
it("preserves decoded empty and Unicode query names, plus distinctions and caller ordinal order", () => {
const capture = analysisViewCaptureFixture();
capture.records = [capture.records[3]!, capture.records[1]!];
const urls = [
"https://api.test/a/%2e%2e/products?b=1&a+b=2&a%2Bb=3&=4&%E9%9B%AA=5&b=6&&%FF=7&__proto__=8#ignored=9",
"https://api.test/a/%2e%2e/products?b=10",
];
capture.records.forEach((record, index) => {
record.reported = { request: { method: "GET", url: urls[index]! } };
});
const result = project(capture, 0, 1, { sensitive_value_count: 0 }, true);
if (!result.ok || result.value.kind !== "api-surface")
throw new Error("Expected surface");
expect(result.value.groups[0]).toMatchObject({
path_template: "/a/%2e%2e/products",
record_ordinals: [3, 1],
query_parameter_names: [
{ name: "", record_ordinals: [3] },
{ name: "__proto__", record_ordinals: [3] },
{ name: "a b", record_ordinals: [3] },
{ name: "a+b", record_ordinals: [3] },
{ name: "b", record_ordinals: [3, 1] },
{ name: "雪", record_ordinals: [3] },
{ name: "�", record_ordinals: [3] },
],
});
expect(result.value.records.total).toBe(15);
expect(result.value.limitations.join(" ")).toContain("ordinal subset");
});
it("preserves sensitive-parent refusal when query names are selected", () => {
expect(
project(
analysisViewCaptureFixture(),
0,
50,
{ sensitive_value_count: 1 },
true,
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
reason: "sensitive_values_unretained",
},
});
});
it("groups only exact formats, preserves literal routes, excludes URLs and produces deterministic digests", () => {
const result = project();
if (!result.ok || result.value.kind !== "api-surface")
@@ -15,6 +15,12 @@ export const apiSurfaceViewSchema = z.strictObject({
kind: z.literal("api-surface"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(50),
include_query_parameter_names: z
.boolean()
.optional()
.describe(
"Include distinct observed query parameter names and their original record ordinals; names do not establish required parameters or a complete API schema.",
),
});
const ruleSchema = z.enum(["numeric", "uuid", "hex", "iso-date"]);
const groupSchema = z.strictObject({
@@ -32,6 +38,14 @@ const groupSchema = z.strictObject({
record_ordinals: z.array(z.number().int().nonnegative()),
statuses: z.array(z.number()),
content_types: z.array(z.string()),
query_parameter_names: z
.array(
z.strictObject({
name: z.string(),
record_ordinals: z.array(z.number().int().nonnegative()),
}),
)
.optional(),
flags: z.array(
z.enum(["single-sample", "mixed-statuses", "mixed-content-types"]),
),
@@ -66,7 +80,10 @@ export const apiSurfaceFields = {
export const projectWebNetworkApiSurfaceView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
accumulator = new WebNetworkApiSurfaceAccumulator(),
accumulator = new WebNetworkApiSurfaceAccumulator(
undefined,
view.kind === "api-surface" && view.include_query_parameter_names === true,
),
): Result<UnsignedAnalysisView, AnalysisError> => {
const unsupported = (reason: string) =>
err(
@@ -111,6 +128,11 @@ export const projectWebNetworkApiSurfaceView = (
...parent.limitations,
...capture.limitations,
"Grouping does not establish handler identity, URL-space schemas or causality.",
...(view.include_query_parameter_names === true
? [
"Observed query parameter names do not establish required parameters, value types or a complete API schema.",
]
: []),
...(capture.records.length < capture.total_records
? [
"Parent contains an ordinal subset; the surface covers only retained records.",
+1 -1
View File
@@ -98,7 +98,7 @@ const textCoverage = z.strictObject({
text: z.string(),
reported_total_bytes: z.number().int().nonnegative().nullable(),
});
/** A DEX prototype: parameter descriptors followed by the return descriptor. */
/** A DEX prototype; hex parentheses also keep the advertised class valid in v mode. */
export const dexDescriptorSchema = z
.string()
.regex(
+3 -2
View File
@@ -68,7 +68,7 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
limitations: z.array(z.string()),
});
export type AndroidApplicationProjectionInput = z.infer<
@@ -99,7 +99,8 @@ export const projectAndroidApplication = (
);
const components = classified;
const limitations = [
...(!hasCompleteInventoryCoverage(inventory)
...inventory.limitations,
...(!hasCompleteInventoryCoverage(inventory, "container-entries")
? ["Source inventory coverage is partial; absence is unknown."]
: []),
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
+18 -12
View File
@@ -94,7 +94,7 @@ export const appleApplicationProjectionResultSchema = z.strictObject({
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
limitations: z.array(z.string()),
});
export type AppleApplicationProjectionInput = z.infer<
@@ -169,18 +169,24 @@ export const projectAppleApplication = (
);
const uninventoriedImage =
rootFormat === "dmg" && inventory.occurrences.length === 1;
const inventoryComplete = hasCompleteInventoryCoverage(inventory);
const inventoryComplete = hasCompleteInventoryCoverage(
inventory,
"container-entries",
);
const complete = inventoryComplete && !uninventoriedImage;
const limitations = projectionLimitations({
complete: inventoryComplete,
uninventoriedImage,
roots,
bundles,
sidecars: entries.some(({ path }) => isSidecar(path)),
symlinks: entries.some(({ kind }) => kind === "symlink"),
unattributed,
bridgeCandidateCoverage: bridgeProjection.coverage,
});
const limitations = [
...inventory.limitations,
...projectionLimitations({
complete: inventoryComplete,
uninventoriedImage,
roots,
bundles,
sidecars: entries.some(({ path }) => isSidecar(path)),
symlinks: entries.some(({ kind }) => kind === "symlink"),
unattributed,
bridgeCandidateCoverage: bridgeProjection.coverage,
}),
];
const withoutId = {
root_sha256: inventory.manifest.root_sha256,
root_format: rootFormat,
+53 -12
View File
@@ -104,13 +104,51 @@ export const compareArtifacts = (
const right = parseArtifactInventoryEvidence(rightEvidence);
const leftComplete = left.inventory.complete;
const rightComplete = right.inventory.complete;
const leftCovered = hasCompleteInventoryCoverage(left.inventory);
const rightCovered = hasCompleteInventoryCoverage(right.inventory);
const sameScope =
left.inventory.coverage.scope === right.inventory.coverage.scope;
const rootCoverageComplete =
sameScope &&
left.inventory.complete &&
right.inventory.complete &&
left.inventory.coverage.status === "complete" &&
right.inventory.coverage.status === "complete";
const entryCoverageComplete =
rootCoverageComplete &&
left.inventory.coverage.scope === "container-entries";
const leftCovered =
sameScope &&
hasCompleteInventoryCoverage(left.inventory, left.inventory.coverage.scope);
const rightCovered =
sameScope &&
hasCompleteInventoryCoverage(
right.inventory,
right.inventory.coverage.scope,
);
const fullyCovered =
leftCovered &&
rightCovered &&
(entryCoverageComplete ||
(rootCoverageComplete &&
left.inventory.manifest.occurrence_count === 1 &&
right.inventory.manifest.occurrence_count === 1));
const limitations = [
...left.inventory.limitations.map((item) => `Left: ${item}`),
...right.inventory.limitations.map((item) => `Right: ${item}`),
...(leftComplete ? [] : ["Left artifact inventory is incomplete."]),
...(rightComplete ? [] : ["Right artifact inventory is incomplete."]),
...(sameScope ? [] : ["Artifact inventory scopes differ."]),
...(sameScope &&
left.inventory.coverage.scope === "root" &&
(left.inventory.manifest.occurrence_count > 1 ||
right.inventory.manifest.occurrence_count > 1)
? ["Container entry coverage is unavailable for child paths."]
: []),
...(left.inventory.coverage.status === "complete"
? []
: ["Left artifact inventory traversal coverage is unknown."]),
...(right.inventory.coverage.status === "complete"
? []
: ["Right artifact inventory traversal coverage is unknown."]),
];
const changes = compareOccurrences(
left.inventory,
@@ -119,7 +157,7 @@ export const compareArtifacts = (
...left.evidence.map(({ evidence_id: id }) => id),
...right.evidence.map(({ evidence_id: id }) => id),
],
leftCovered && rightCovered,
{ root: rootCoverageComplete, entries: entryCoverageComplete },
);
applyRootHashChange(left.inventory, right.inventory, changes, [
...left.evidence.map(({ evidence_id: id }) => id),
@@ -129,7 +167,7 @@ export const compareArtifacts = (
left.inventory,
right.inventory,
changes,
leftCovered && rightCovered,
fullyCovered,
);
return artifactComparisonResultSchema.parse({
status:
@@ -139,7 +177,7 @@ export const compareArtifacts = (
({ classification }) => classification === "contradiction",
)
? "contradiction"
: !leftCovered || !rightCovered
: !fullyCovered
? "unknown"
: changes.some(({ classification }) => classification === "unknown")
? "unknown"
@@ -158,7 +196,7 @@ const compareOccurrences = (
left: InventorySet,
right: InventorySet,
evidenceLinks: readonly string[],
complete: boolean,
coverage: { readonly root: boolean; readonly entries: boolean },
): ArtifactChange[] => {
const leftByPath = new Map(
left.occurrences.map((item) => [item.logical_path, item]),
@@ -187,7 +225,8 @@ const compareOccurrences = (
rightNode: nodeFor(rightOccurrence, rightNodes),
leftRelations: leftRelations.get(path) ?? [],
rightRelations: rightRelations.get(path) ?? [],
complete,
rootCovered: coverage.root,
entriesCovered: coverage.entries,
evidenceLinks,
});
if (change !== null) output.push(change);
@@ -203,7 +242,8 @@ interface ClassifyPathInput {
readonly rightNode: ArtifactNode | undefined;
readonly leftRelations: readonly RelationProjection[];
readonly rightRelations: readonly RelationProjection[];
readonly complete: boolean;
readonly rootCovered: boolean;
readonly entriesCovered: boolean;
readonly evidenceLinks: readonly string[];
}
@@ -217,17 +257,18 @@ const buildArtifactChangeBase = (input: ClassifyPathInput) => ({
});
const classifyPresence = (input: ClassifyPathInput): ArtifactChange | null => {
const covered = input.path === "." ? input.rootCovered : input.entriesCovered;
if (input.leftOccurrence === undefined)
return {
...buildArtifactChangeBase(input),
classification: input.complete ? "added" : "unknown",
dimensions: [input.complete ? "content" : "availability"],
classification: covered ? "added" : "unknown",
dimensions: [covered ? "content" : "availability"],
};
if (input.rightOccurrence === undefined)
return {
...buildArtifactChangeBase(input),
classification: input.complete ? "removed" : "unknown",
dimensions: [input.complete ? "content" : "availability"],
classification: covered ? "removed" : "unknown",
dimensions: [covered ? "content" : "availability"],
};
return null;
};
+13 -6
View File
@@ -188,8 +188,11 @@ export const artifactGraphManifestSchema = z.object({
edge_count: z.number().int().min(0),
});
/** Whether the inventory producer covered its modeled child-entry scope. */
export const artifactInventoryCoverageSchema = z.enum(["complete", "partial"]);
/** Producer-owned traversal coverage; content certainty remains on each occurrence. */
export const artifactInventoryCoverageSchema = z.strictObject({
scope: z.enum(["root", "container-entries"]),
status: z.enum(["complete", "unknown"]),
});
export type ArtifactInventoryCoverage = z.infer<
typeof artifactInventoryCoverageSchema
>;
@@ -202,15 +205,19 @@ export const artifactInventoryResultSchema = z.object({
edges: z.array(artifactEdgeSchema),
provenance: z.array(artifactCommandSchema),
integrity_contradictions: z.array(integrityContradictionSchema).default([]),
// Omitted by older retained Evidence; the inventory parser owns its compatibility policy.
coverage: artifactInventoryCoverageSchema.optional(),
limitations: z.array(z.string()),
/** Optional only for persisted inventory Evidence written before this field. */
coverage_status: artifactInventoryCoverageSchema.optional(),
coverage_status: z.enum(["complete", "partial"]).optional(),
});
/** Current inventory producers always classify the coverage they examined. */
/** Current producers always declare coverage; historical Evidence inputs may omit it. */
export const artifactInventoryOutputSchema =
artifactInventoryResultSchema.extend({
coverage_status: artifactInventoryCoverageSchema,
artifactInventoryResultSchema.safeExtend({
coverage: artifactInventoryCoverageSchema,
coverage_status:
artifactInventoryResultSchema.shape.coverage_status.unwrap(),
});
export type ArtifactInventoryOutput = z.infer<
typeof artifactInventoryOutputSchema
+89 -31
View File
@@ -18,7 +18,10 @@ import {
} from "./artifactIdentity.js";
import { parseEvidence, type Evidence } from "./evidence.js";
import { artifactInspectionResultSchema } from "./artifactInspection.js";
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "./zipPackageFormat.js";
import {
isZipPackageFormat,
isZipInventoryScopeLimitation,
} from "./zipPackageFormat.js";
/** Complete or partially assembled inventory used by comparison workflows. */
export interface InventorySet {
@@ -30,13 +33,17 @@ export interface InventorySet {
readonly limitations: readonly string[];
/** True when merged node, occurrence, and edge counts match the manifest. */
readonly complete: boolean;
readonly coverage_status: ArtifactInventoryCoverage;
readonly coverage: ArtifactInventoryCoverage;
}
/** Whether all graph members are present and the producer reports full coverage. */
export const hasCompleteInventoryCoverage = (
inventory: InventorySet,
): boolean => inventory.complete && inventory.coverage_status === "complete";
requiredScope: ArtifactInventoryCoverage["scope"],
): boolean =>
inventory.complete &&
inventory.coverage.scope === requiredScope &&
inventory.coverage.status === "complete";
export interface ParsedInventorySet {
readonly evidence: readonly Evidence[];
@@ -132,11 +139,14 @@ const assembleInventoryResults = (
const first = pages[0];
if (first === undefined)
throw new TypeError("Artifact inventory requires Evidence pages");
const coverageStatuses = new Set(pages.map(resolveInventoryCoverageStatus));
if (coverageStatuses.size !== 1)
throw new TypeError("Artifact inventory pages disagree on coverage status");
const coverageStatus = [...coverageStatuses][0]!;
const manifestJson = canonicalJson(first.manifest, "Artifact inventory");
const coverageJson = canonicalJson(
{
coverage: first.coverage ?? null,
coverage_status: first.coverage_status ?? null,
},
"Artifact inventory coverage",
);
const nodes = new Map<string, ArtifactNode>();
const occurrences = new Map<string, ArtifactOccurrence>();
const paths = new Map<string, ArtifactOccurrence>();
@@ -144,6 +154,18 @@ const assembleInventoryResults = (
for (const page of pages) {
if (canonicalJson(page.manifest, "Artifact inventory") !== manifestJson)
throw new TypeError("Artifact inventory pages do not share one manifest");
if (
canonicalJson(
{
coverage: page.coverage ?? null,
coverage_status: page.coverage_status ?? null,
},
"Artifact inventory coverage",
) !== coverageJson
)
throw new TypeError(
"Artifact inventory pages do not share one coverage declaration",
);
if (
canonicalJson(page.integrity_contradictions, "Artifact inventory") !==
canonicalJson(first.integrity_contradictions, "Artifact inventory")
@@ -165,12 +187,11 @@ const assembleInventoryResults = (
for (const edge of page.edges)
mergeExact(edges, edge.edge_id, edge, "edge");
}
const inventory = orderedInventory(
first,
pages,
{ nodes, occurrences, edges },
coverageStatus,
);
const inventory = orderedInventory(first, pages, {
nodes,
occurrences,
edges,
});
if (inventory.complete) validateCompleteInventory(inventory);
return inventory;
};
@@ -186,7 +207,6 @@ const orderedInventory = (
ArtifactInventoryResult["edges"][number]
>;
},
coverageStatus: ArtifactInventoryCoverage,
): InventorySet => {
const nodes = [...values.nodes.values()].sort((left, right) =>
compareUnicodeCodePoints(left.artifact_id, right.artifact_id),
@@ -197,40 +217,78 @@ const orderedInventory = (
const edges = [...values.edges.values()].sort((left, right) =>
compareUnicodeCodePoints(left.edge_id, right.edge_id),
);
const limitations = [
...new Set(pages.flatMap((inventory) => inventory.limitations)),
].sort(compareUnicodeCodePoints);
return {
manifest: first.manifest,
nodes,
occurrences,
edges,
integrityContradictions: first.integrity_contradictions,
limitations: [
...new Set(pages.flatMap((inventory) => inventory.limitations)),
].sort(compareUnicodeCodePoints),
limitations,
coverage: resolveInventoryCoverage({ ...first, limitations }),
complete:
nodes.length === first.manifest.node_count &&
occurrences.length === first.manifest.occurrence_count &&
edges.length === first.manifest.edge_count,
coverage_status: coverageStatus,
};
};
const resolveInventoryCoverageStatus = (
// Normalize both retained coverage formats at this owning boundary.
const resolveInventoryCoverage = (
inventory: ArtifactInventoryResult,
): ArtifactInventoryCoverage => {
if (inventory.coverage_status !== undefined) return inventory.coverage_status;
// Older retained Evidence has no typed status. Keep only its known
// informational notices complete; unknown limitation text fails closed.
return inventory.limitations.every(isKnownNonCoverageNotice)
? "complete"
: "partial";
const legacy = legacyInventoryCoverage(
inventory.manifest.root_format,
inventory.limitations,
inventory.integrity_contradictions.length,
);
if (inventory.coverage !== undefined) {
if (
inventory.coverage_status !== undefined &&
(inventory.coverage.status === "complete") !==
(inventory.coverage_status === "complete")
)
throw new TypeError(
"Artifact inventory has conflicting coverage declarations",
);
return inventory.coverage;
}
return inventory.coverage_status === undefined
? legacy
: {
...legacy,
status:
inventory.coverage_status === "complete" ? "complete" : "unknown",
};
};
const isKnownNonCoverageNotice = (limitation: string): boolean =>
limitation === "Artifact has no child container entries." ||
limitation === ZIP_NON_ENTRY_TAIL_LIMITATION ||
/^\d+ integrity contradiction\(s\) were recorded; mismatched content is observed-untrusted\.$/u.test(
limitation,
);
// Retained pre-coverage records cannot classify arbitrary prose. Recognize only
// the historical producer vocabulary here; unfamiliar diagnostics remain unknown.
const legacyInventoryCoverage = (
format: ArtifactInventoryResult["manifest"]["root_format"],
limitations: readonly string[],
contradictionCount: number,
): ArtifactInventoryCoverage => ({
scope:
isZipPackageFormat(format) ||
["directory", "asar", "dmg", "pkg", "mach-o-universal"].includes(format)
? "container-entries"
: "root",
status: limitations.some(
(limitation) =>
limitation !== "Artifact has no child container entries." &&
!isZipInventoryScopeLimitation(limitation) &&
!(
contradictionCount > 0 &&
limitation ===
`${String(contradictionCount)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`
),
)
? "unknown"
: "complete",
});
const validateCompleteInventory = (inventory: InventorySet): void => {
const nodeIds = new Set(inventory.nodes.map(({ artifact_id: id }) => id));
+4 -1
View File
@@ -7,7 +7,9 @@ import type {
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly coverage_status: ArtifactInventoryCoverage;
readonly coverage_status: NonNullable<
ArtifactInventoryResult["coverage_status"]
>;
readonly manifest: ArtifactInventoryResult["manifest"];
readonly nodes: readonly ArtifactNode[];
readonly occurrences: ArtifactInventoryResult["occurrences"];
@@ -16,5 +18,6 @@ export interface ArtifactInventorySnapshot {
ArtifactInventoryResult["provenance"][number]
>;
readonly integrity_contradictions: readonly IntegrityContradiction[];
readonly coverage?: ArtifactInventoryCoverage;
readonly limitations: readonly string[];
}
+72 -2
View File
@@ -58,20 +58,67 @@ export const fat = (
return bytes;
};
/** Build a bounded PE image with optional managed metadata. */
export interface PeCodeViewFixture {
readonly type?: "RSDS" | "NB10";
readonly guid?: string;
readonly age?: number;
readonly pdbPath?: string;
}
/** Build a bounded PE image with optional managed metadata or CodeView debug data. */
export const pe = (
machine: number,
offset = 64,
characteristics = 0x0002,
managed = false,
codeView?: PeCodeViewFixture,
): Buffer => {
const optionalHeaderSize =
machine === 0x014c || machine === 0x01c0 ? 224 : 240;
const bytes = Buffer.alloc(Math.max(512, offset + 24 + optionalHeaderSize));
const sectionTableOffset = offset + 24 + optionalHeaderSize;
const sectionCount = codeView !== undefined ? 1 : 0;
const rawDataOffset = 512;
let codeViewData: Buffer | undefined;
if (codeView !== undefined) {
const type = codeView.type ?? "RSDS";
const pdbPath = codeView.pdbPath ?? "app.pdb";
const age = codeView.age ?? 1;
const pathBuf = Buffer.from(`${pdbPath}\0`, "utf8");
if (type === "RSDS") {
codeViewData = Buffer.alloc(24 + pathBuf.length);
codeViewData.write("RSDS", 0, "ascii");
const guid = codeView.guid ?? "01234567-89ab-cdef-0123-456789abcdef";
const parts = guid.split("-");
if (parts.length === 5) {
codeViewData.writeUInt32LE(parseInt(parts[0]!, 16), 4);
codeViewData.writeUInt16LE(parseInt(parts[1]!, 16), 8);
codeViewData.writeUInt16LE(parseInt(parts[2]!, 16), 10);
Buffer.from(parts[3]!, "hex").copy(codeViewData, 12);
Buffer.from(parts[4]!, "hex").copy(codeViewData, 14);
}
codeViewData.writeUInt32LE(age, 20);
pathBuf.copy(codeViewData, 24);
} else {
codeViewData = Buffer.alloc(16 + pathBuf.length);
codeViewData.write("NB10", 0, "ascii");
codeViewData.writeUInt32LE(0, 4);
codeViewData.writeUInt32LE(0, 8);
codeViewData.writeUInt32LE(age, 12);
pathBuf.copy(codeViewData, 16);
}
}
const minSize =
codeViewData !== undefined
? rawDataOffset + 28 + codeViewData.length + 32
: Math.max(512, offset + 24 + optionalHeaderSize);
const bytes = Buffer.alloc(minSize);
bytes.write("MZ", 0, "ascii");
bytes.writeUInt32LE(offset, 0x3c);
bytes.write("PE\0\0", offset, "binary");
bytes.writeUInt16LE(machine, offset + 4);
bytes.writeUInt16LE(sectionCount, offset + 6);
bytes.writeUInt16LE(optionalHeaderSize, offset + 20);
bytes.writeUInt16LE(characteristics, offset + 22);
const optionalHeader = offset + 24;
@@ -83,6 +130,29 @@ export const pe = (
bytes.writeUInt32LE(0x2000, optionalHeader + directoryOffset + 14 * 8);
bytes.writeUInt32LE(72, optionalHeader + directoryOffset + 14 * 8 + 4);
}
if (codeViewData !== undefined) {
const debugDirRva = 0x1000;
const debugDirSize = 28;
bytes.writeUInt32LE(debugDirRva, optionalHeader + directoryOffset + 6 * 8);
bytes.writeUInt32LE(
debugDirSize,
optionalHeader + directoryOffset + 6 * 8 + 4,
);
bytes.write(".rdata\0\0", sectionTableOffset, "ascii");
bytes.writeUInt32LE(0x1000, sectionTableOffset + 8);
bytes.writeUInt32LE(0x1000, sectionTableOffset + 12);
bytes.writeUInt32LE(512, sectionTableOffset + 16);
bytes.writeUInt32LE(rawDataOffset, sectionTableOffset + 20);
bytes.writeUInt32LE(0x40000040, sectionTableOffset + 36);
bytes.writeUInt32LE(2, rawDataOffset + 12);
bytes.writeUInt32LE(codeViewData.length, rawDataOffset + 16);
bytes.writeUInt32LE(debugDirRva + 28, rawDataOffset + 20);
bytes.writeUInt32LE(rawDataOffset + 28, rawDataOffset + 24);
codeViewData.copy(bytes, rawDataOffset + 28);
}
return bytes;
};
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import { parseExecutableHeader } from "./binaryTarget.js";
const header = (little: boolean, bits: 32 | 64 = 32, machine = 20): Buffer => {
const bytes = Buffer.alloc(bits === 32 ? 52 : 64);
bytes.set([0x7f, 0x45, 0x4c, 0x46, bits === 32 ? 1 : 2, little ? 1 : 2, 1]);
if (little) {
bytes.writeUInt16LE(2, 16);
bytes.writeUInt16LE(machine, 18);
bytes.writeUInt32LE(1, 20);
bytes.writeUInt16LE(bytes.length, bits === 32 ? 40 : 52);
} else {
bytes.writeUInt16BE(2, 16);
bytes.writeUInt16BE(machine, 18);
bytes.writeUInt32BE(1, 20);
bytes.writeUInt16BE(bytes.length, bits === 32 ? 40 : 52);
}
return bytes;
};
describe("PowerPC ELF header boundaries", () => {
it.each([false, true])(
"retains source endian and flags (little=%s)",
(little) => {
const parsed = parseExecutableHeader(header(little), "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toEqual({
format: "elf",
architecture: "powerpc",
availableArchitectures: ["powerpc"],
powerpc: {
elfClass: 32,
byteOrder: little ? "little" : "big",
type: 2,
flags: 0,
},
});
},
);
it("reads ELF64 flags at their own offset without claiming support", () => {
const bytes = header(false, 64);
bytes.writeUInt32BE(0x80000000, 48);
const parsed = parseExecutableHeader(bytes, "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toMatchObject({
architecture: "powerpc",
powerpc: { elfClass: 64, byteOrder: "big", flags: 0x80000000 },
});
});
it("does not recognize EM_PPC64 as the 32-bit family", () => {
expect(parseExecutableHeader(header(false, 64, 21), "x64")).toEqual({
ok: false,
error: "unsupported ELF architecture",
});
});
});
+193 -2
View File
@@ -3,7 +3,9 @@ import type {
ElfFamilyMetadata,
HeaderArchitecture,
MipsElfMetadata,
PeCodeViewRecord,
RiscvElfMetadata,
PowerPcElfMetadata,
UniversalMachOSlice,
} from "./binaryTargetTypes.js";
import { err, ok, type Result } from "./result.js";
@@ -29,6 +31,12 @@ export type ExecutableMetadata =
readonly availableArchitectures: readonly "riscv"[];
readonly riscv: RiscvElfMetadata;
}
| {
readonly format: "elf";
readonly architecture: "powerpc";
readonly availableArchitectures: readonly "powerpc"[];
readonly powerpc: PowerPcElfMetadata;
}
| {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly architecture: HeaderArchitecture;
@@ -50,6 +58,7 @@ export type ExecutableMetadata =
| "shared-library"
| "non-executable";
readonly managed: boolean;
readonly codeView?: PeCodeViewRecord;
};
/**
@@ -199,7 +208,11 @@ const parseElf = (
const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18);
const architecture = elfArchitecture(machine);
if (architecture === undefined) return err("unsupported ELF architecture");
if (architecture === "mips" || architecture === "riscv") {
if (
architecture === "mips" ||
architecture === "riscv" ||
architecture === "powerpc"
) {
const flagsOffset = elfClass === 32 ? 36 : 48;
const metadata: ElfFamilyMetadata = {
elfClass,
@@ -209,6 +222,13 @@ const parseElf = (
? bytes.readUInt32LE(flagsOffset)
: bytes.readUInt32BE(flagsOffset),
};
if (architecture === "powerpc")
return ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
powerpc: metadata,
});
return architecture === "mips"
? ok({
format: "elf",
@@ -257,7 +277,8 @@ const parseMz = (
);
if (windowsHeader.signature !== "PE")
return err("invalid or truncated Windows executable header in MZ image");
return parsePeRecord(bytes.subarray(offset));
const codeView = parsePeCodeViewFromBuffer(bytes, offset);
return parsePeRecord(bytes.subarray(offset), codeView);
}
const parsed = parseDosMzHeader(bytes, fileSize, signatureAtOffset);
return parsed.ok
@@ -272,6 +293,7 @@ const parseMz = (
/** Parse a bounded PE signature, COFF record, and optional header without I/O. */
export const parsePeRecord = (
record: Buffer,
codeView: PeCodeViewRecord | undefined,
): Result<ExecutableMetadata, string> => {
if (
record.length < 24 ||
@@ -305,9 +327,176 @@ export const parsePeRecord = (
? "application"
: "shared-library",
managed: managed.value,
...(codeView !== undefined ? { codeView } : {}),
});
};
/** Parse CodeView record data (RSDS or NB10) from raw data bytes. */
export const parseCodeViewData = (
buffer: Buffer,
sizeOfData: number,
): PeCodeViewRecord | undefined => {
if (sizeOfData < 16 || buffer.length < 16) return undefined;
const magic = buffer.subarray(0, 4).toString("binary");
const pathOffset = magic === "RSDS" ? 24 : magic === "NB10" ? 16 : undefined;
if (
pathOffset === undefined ||
sizeOfData <= pathOffset ||
buffer.length <= pathOffset
)
return undefined;
const end = buffer.indexOf(0, pathOffset);
if (end <= pathOffset || end >= sizeOfData) return undefined;
const pdbPath = buffer.toString("utf8", pathOffset, end);
const pdbFileName = pdbPath.split(/[/\\]/u).pop() ?? pdbPath;
if (magic === "RSDS" && sizeOfData >= 24 && buffer.length >= 24) {
const part1 = buffer.readUInt32LE(4).toString(16).padStart(8, "0");
const part2 = buffer.readUInt16LE(8).toString(16).padStart(4, "0");
const part3 = buffer.readUInt16LE(10).toString(16).padStart(4, "0");
const part4 = buffer.subarray(12, 14).toString("hex");
const part5 = buffer.subarray(14, 20).toString("hex");
const guid = `${part1}-${part2}-${part3}-${part4}-${part5}`;
const age = buffer.readUInt32LE(20);
return { pdbPath, pdbFileName, guid, age };
}
if (magic === "NB10") {
const age = buffer.readUInt32LE(12);
return { pdbPath, pdbFileName, guid: null, age };
}
return undefined;
};
/** Locate the debug directory RVA and size from a PE optional header. */
export const peDebugDirectoryEntry = (
optionalHeader: Buffer,
):
| {
readonly debugRva: number;
readonly debugSize: number;
readonly sizeOfHeaders: number;
}
| undefined => {
if (optionalHeader.length < 2) return undefined;
const magic = optionalHeader.readUInt16LE(0);
if (magic !== 0x10b && magic !== 0x20b) return undefined;
const directoryOffset = magic === 0x20b ? 112 : 96;
const directoryCountOffset = directoryOffset - 4;
if (optionalHeader.length < directoryCountOffset + 4) return undefined;
const directoryCount = optionalHeader.readUInt32LE(directoryCountOffset);
if (directoryCount <= 6) return undefined;
const debugEntryOffset = directoryOffset + 6 * 8;
if (optionalHeader.length < debugEntryOffset + 8) return undefined;
const debugRva = optionalHeader.readUInt32LE(debugEntryOffset);
const debugSize = optionalHeader.readUInt32LE(debugEntryOffset + 4);
if (debugRva === 0 || debugSize < 28) return undefined;
return {
debugRva,
debugSize,
sizeOfHeaders: optionalHeader.readUInt32LE(60),
};
};
/** Translate an RVA to an absolute file offset using the PE section table. */
export const peRvaToFileOffset = (
rva: number,
sectionTable: Buffer,
numberOfSections: number,
sizeOfHeaders: number,
size = 1,
): number | undefined => {
if (rva < sizeOfHeaders && size <= sizeOfHeaders - rva) return rva;
for (let i = 0; i < numberOfSections; i++) {
const offset = i * 40;
if (sectionTable.length < offset + 40) break;
const virtualAddress = sectionTable.readUInt32LE(offset + 12);
const sizeOfRawData = sectionTable.readUInt32LE(offset + 16);
const pointerToRawData = sectionTable.readUInt32LE(offset + 20);
if (
pointerToRawData > 0 &&
rva >= virtualAddress &&
rva - virtualAddress < sizeOfRawData &&
size <= sizeOfRawData - (rva - virtualAddress)
) {
return pointerToRawData + (rva - virtualAddress);
}
}
return undefined;
};
/** Parse CodeView metadata from a bounded in-memory PE image buffer. */
export const parsePeCodeViewFromBuffer = (
fileBytes: Buffer,
peOffset: number,
): PeCodeViewRecord | undefined => {
if (fileBytes.length < peOffset + 24) return undefined;
const numberOfSections = fileBytes.readUInt16LE(peOffset + 6);
const optionalHeaderSize = fileBytes.readUInt16LE(peOffset + 20);
if (
optionalHeaderSize > 4096 ||
fileBytes.length < peOffset + 24 + optionalHeaderSize
)
return undefined;
const optionalHeader = fileBytes.subarray(
peOffset + 24,
peOffset + 24 + optionalHeaderSize,
);
const debugDir = peDebugDirectoryEntry(optionalHeader);
if (debugDir === undefined) return undefined;
const sectionTableOffset = peOffset + 24 + optionalHeaderSize;
const sectionTableSize = numberOfSections * 40;
if (fileBytes.length < sectionTableOffset + sectionTableSize)
return undefined;
const sectionTable = fileBytes.subarray(
sectionTableOffset,
sectionTableOffset + sectionTableSize,
);
const debugFileOffset = peRvaToFileOffset(
debugDir.debugRva,
sectionTable,
numberOfSections,
debugDir.sizeOfHeaders,
Math.min(debugDir.debugSize, 4096),
);
if (debugFileOffset === undefined || fileBytes.length < debugFileOffset + 28)
return undefined;
const maxDebugBytes = Math.min(
debugDir.debugSize,
fileBytes.length - debugFileOffset,
);
const numEntries = Math.floor(maxDebugBytes / 28);
for (let j = 0; j < numEntries; j++) {
const entryOffset = debugFileOffset + j * 28;
const type = fileBytes.readUInt32LE(entryOffset + 12);
if (type !== 2) continue; // IMAGE_DEBUG_TYPE_CODEVIEW
const sizeOfData = fileBytes.readUInt32LE(entryOffset + 16);
let pointerToRawData = fileBytes.readUInt32LE(entryOffset + 24);
if (pointerToRawData === 0) {
const addressOfRawData = fileBytes.readUInt32LE(entryOffset + 20);
const mapped = peRvaToFileOffset(
addressOfRawData,
sectionTable,
numberOfSections,
debugDir.sizeOfHeaders,
Math.min(sizeOfData, 4096),
);
if (mapped === undefined) continue;
pointerToRawData = mapped;
}
if (
sizeOfData < 16 ||
fileBytes.length < pointerToRawData + Math.min(sizeOfData, 24)
)
continue;
const codeViewData = fileBytes.subarray(
pointerToRawData,
Math.min(fileBytes.length, pointerToRawData + sizeOfData),
);
const parsed = parseCodeViewData(codeViewData, sizeOfData);
if (parsed !== undefined) return parsed;
}
return undefined;
};
const peManagedStatus = (
optionalHeader: Buffer,
architecture: BinaryArchitecture,
@@ -361,6 +550,8 @@ const elfArchitecture = (
return "x86_64";
case 8: // EM_MIPS: ISA, ABI and byte order remain separate ELF facts.
return "mips";
case 20: // EM_PPC; byte order and processor variant remain ELF declarations.
return "powerpc";
case 40:
return "arm";
case 183:
+24
View File
@@ -9,6 +9,7 @@ export const BINARY_ARCHITECTURES = [
"mips",
"6502",
"riscv",
"powerpc",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
@@ -24,10 +25,19 @@ export interface ElfFamilyMetadata {
readonly flags: number;
}
/** Referenced CodeView debug symbols from a PE debug directory. */
export interface PeCodeViewRecord {
readonly pdbPath: string;
readonly pdbFileName: string;
readonly guid: string | null;
readonly age: number;
}
/** Families whose parsed target variant carries `ElfFamilyMetadata`. */
export const ELF_METADATA_ARCHITECTURES = [
"mips",
"riscv",
"powerpc",
] as const satisfies readonly BinaryArchitecture[];
export type ElfMetadataArchitecture =
(typeof ELF_METADATA_ARCHITECTURES)[number];
@@ -82,6 +92,9 @@ export interface MipsAbiFlags {
*/
export type RiscvElfMetadata = ElfFamilyMetadata;
/** Raw PowerPC declarations; family identity does not select a processor variant. */
export type PowerPcElfMetadata = ElfFamilyMetadata;
/** Byte range of the selected slice inside its universal Mach-O container. */
export interface UniversalMachOSlice {
readonly offset: number;
@@ -132,6 +145,15 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "elf";
readonly architecture: "powerpc";
readonly availableArchitectures: readonly "powerpc"[];
readonly powerpc: PowerPcElfMetadata;
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly universalSlice?: never;
@@ -170,6 +192,8 @@ export type BinaryTarget =
| "non-executable";
/** Whether the PE declares a non-empty CLI header data-directory entry. */
readonly managed: boolean;
/** Referenced CodeView debug symbols from the PE debug directory, if present. */
readonly codeView?: PeCodeViewRecord;
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
+2 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { urlDeclaresQueryOrFragment } from "./urlComponents.js";
import { parseUrlQueryParameterNames } from "./recordedTransportUrl.js";
const parseExactOrigin = (value: string): string | undefined => {
let url: URL;
@@ -254,7 +255,7 @@ export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
};
}
const hadCredentials = parsed.username !== "" || parsed.password !== "";
const names = [...parsed.searchParams.keys()];
const names = [...parseUrlQueryParameterNames(parsed.search)];
const sanitizedUrl = hadCredentials
? removeUrlUserInfo(value, parsed)
: value;
+1 -1
View File
@@ -11,7 +11,7 @@ import { AnalysisCancelledError } from "./analysisErrorCore.js";
/** A bounded passive browser observation failed at its CDP boundary. */
export class BrowserObservationError extends AnalysisError {
readonly _tag = "BrowserObservationError";
override readonly cleanupIncomplete: boolean;
override cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
override readonly userCategory: "cancelled" | undefined;
override readonly userMessage: string | undefined;
+36
View File
@@ -337,6 +337,42 @@ describe("call path topology and capacity", () => {
});
});
describe("directional call relationship coverage", () => {
it.each([
{
directions: ["callers"] as ["callers"],
status: "not_found",
exhaustive: true,
},
{
directions: ["callees"] as ["callees"],
status: "unknown",
exhaustive: false,
},
{
directions: ["callers", "callees"] as ["callers", "callees"],
status: "unknown",
exhaustive: false,
},
])(
"uses $directions coverage for the forward search",
({ directions, status, exhaustive }) => {
const limitation = "The inventory omitted a reference.";
const relationshipCoverage: RelationshipCoverage = {
status: "partial",
limitations: [limitation],
limited_directions: directions,
};
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", { relationshipCoverage }),
observe("0x2000", [], "rea-workflow", { relationshipCoverage }),
]);
expect(result).toMatchObject({ status, search_scope: { exhaustive } });
expect(result.limitations).toContain(limitation);
},
);
});
describe("explicit call relationship coverage", () => {
it("accumulates 150,000 partial reasons without argument-stack exhaustion", () => {
const result = run([
+8 -10
View File
@@ -1,3 +1,4 @@
import { relationshipCoverageLimitations } from "./relationshipCoverage.js";
import {
callPathInputSchema,
callPathResultSchema,
@@ -10,7 +11,7 @@ import {
parseFunctionEvidence,
type FunctionSnapshot,
} from "./functionDossierEvidence.js";
import { isCallerOnlyUnknownCoverage } from "./functionCallCoverage.js";
import { isCallerOnlyIncompleteCoverage } from "./functionCallCoverage.js";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
/** Minimal directed caller-to-callee adjacency for call-path search. */
@@ -240,15 +241,12 @@ const inspectSearch = ({
const coverage = snapshot.evidence.relationship_coverage;
for (const limitation of snapshot.limitations)
limitations.push(limitation);
if (coverage?.status === "partial")
for (const limitation of coverage.limitations)
if (coverage !== null) {
for (const limitation of relationshipCoverageLimitations(coverage))
limitations.push(limitation);
else if (coverage?.status === "unknown")
limitations.push(coverage.reason);
for (const diagnostic of coverage !== null && "diagnostics" in coverage
? coverage.diagnostics
: [])
limitations.push(diagnostic);
for (const diagnostic of coverage.diagnostics ?? [])
limitations.push(diagnostic);
}
// The requested goal is a terminal for this search. Its outgoing edges
// cannot add a path to the goal, so its dossier limits are contextual
// but do not make the searched start-to-goal closure incomplete.
@@ -268,7 +266,7 @@ const inspectSearch = ({
coverage === null
? snapshot.limitations.length > 0
: coverage.status !== "complete" &&
!isCallerOnlyUnknownCoverage(coverage)
!isCallerOnlyIncompleteCoverage(coverage)
)
incompleteExpandedCoverage = true;
} else if (node === goal) {
+7 -6
View File
@@ -72,13 +72,14 @@ const windowsHeaderSignature = (
bytes: Buffer | undefined,
): "PE" | "NE" | "LE" | "LX" | "other" | "unobserved" => {
if (bytes === undefined || bytes.length < 2) return "unobserved";
const prefix = bytes.toString("latin1", 0, 2);
if (prefix === "NE" || prefix === "LE" || prefix === "LX") return prefix;
if (prefix !== "PE") return "other";
const first = bytes[0];
const second = bytes[1];
if (first === 0x4e && second === 0x45) return "NE";
if (first === 0x4c && second === 0x45) return "LE";
if (first === 0x4c && second === 0x58) return "LX";
if (first !== 0x50 || second !== 0x45) return "other";
if (bytes.length < 4) return "unobserved";
return bytes.subarray(0, 4).equals(Buffer.from("PE\0\0", "binary"))
? "PE"
: "other";
return bytes[2] === 0 && bytes[3] === 0 ? "PE" : "other";
};
/**
+33 -7
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import {
combineFunctionRelationshipCoverage,
isCallerOnlyUnknownCoverage,
isCallerOnlyIncompleteCoverage,
} from "./functionCallCoverage.js";
import type { RelationshipCoverage } from "./relationshipCoverage.js";
@@ -22,14 +22,14 @@ const cappedCallees: RelationshipCoverage = {
};
const complete: RelationshipCoverage = { status: "complete" };
describe("isCallerOnlyUnknownCoverage", () => {
describe("isCallerOnlyIncompleteCoverage", () => {
it("detects unknown callers beside complete callees", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
complete,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(true);
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(true);
});
it("rejects unknown callees beside complete callers", () => {
@@ -37,7 +37,7 @@ describe("isCallerOnlyUnknownCoverage", () => {
complete,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false);
});
it("rejects unknown coverage on both sides", () => {
@@ -45,7 +45,7 @@ describe("isCallerOnlyUnknownCoverage", () => {
unknownCallers,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false);
});
it("rejects unknown callers beside IDA-capped callees", () => {
@@ -54,11 +54,37 @@ describe("isCallerOnlyUnknownCoverage", () => {
cappedCallees,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false);
});
it("rejects complete coverage", () => {
const combined = combineFunctionRelationshipCoverage(complete, complete);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false);
});
it("retains caller-only partial coverage without relying on limitation wording", () => {
const combined = combineFunctionRelationshipCoverage(
{ status: "partial", limitations: ["Missing incoming references."] },
complete,
);
expect(combined).toMatchObject({ limited_directions: ["callers"] });
expect(isCallerOnlyIncompleteCoverage(combined)).toBe(true);
});
it("uses explicit directions even when explanation text contains direction labels", () => {
expect(
isCallerOnlyIncompleteCoverage({
status: "unknown",
reason: "Callers: unavailable. Callees: diagnostic text.",
limited_directions: ["callers"],
}),
).toBe(true);
expect(
isCallerOnlyIncompleteCoverage({
status: "unknown",
reason: "Callers: unavailable.",
limited_directions: ["callees"],
}),
).toBe(false);
});
});
+39 -42
View File
@@ -1,4 +1,7 @@
import type { RelationshipCoverage } from "./relationshipCoverage.js";
import {
relationshipCoverageLimitations,
type RelationshipCoverage,
} from "./relationshipCoverage.js";
import type { FunctionDossier } from "./hopperValues.js";
import { uniqueSorted } from "./canonicalOrdering.js";
@@ -15,25 +18,25 @@ export const combineFunctionRelationshipCoverage = (
{ direction: "callees" as const, coverage: callees },
];
const diagnostics = uniqueSorted(
reads.flatMap(({ coverage }) =>
coverage !== undefined && "diagnostics" in coverage
? coverage.diagnostics
: [],
),
reads.flatMap(({ coverage }) => coverage?.diagnostics ?? []),
);
const details = diagnostics.length > 0 ? { diagnostics } : {};
const callersLimited = callers?.status !== "complete";
const calleesLimited = callees?.status !== "complete";
const limited_directions: Extract<
RelationshipCoverage,
{ status: "partial" }
>["limited_directions"] = callersLimited
? calleesLimited
? ["callers", "callees"]
: ["callers"]
: ["callees"];
const reasons = reads.flatMap(({ direction, coverage }) => {
const label =
direction === "callers" ? callerCoveragePrefix : calleeCoveragePrefix;
const limitations =
coverage === undefined
? ["Provider did not report relationship coverage."]
: coverage.status === "unknown"
? [coverage.reason]
: coverage.status === "partial"
? coverage.limitations
: [];
return limitations.map((reason) => `${label}${reason}`);
return relationshipCoverageLimitations(coverage).map(
(reason) => `${label}${reason}`,
);
});
if (
reads.some(
@@ -43,54 +46,48 @@ export const combineFunctionRelationshipCoverage = (
return {
status: "unknown",
reason: uniqueSorted(reasons).join(" "),
limited_directions,
...details,
};
if (reasons.length > 0)
return {
status: "partial",
limitations: uniqueSorted(reasons),
limited_directions,
...details,
};
return { status: "complete", ...details };
};
/**
* Whether combined relationship coverage is unknown only on the caller side.
* The combine helper above prefixes each direction's reasons, so a reason
* that carries the caller prefix and no callee prefix records observed
* callees with unobservable callers. Forward (callee-edge) searches stay
* exhaustive under that caveat; the caller reason remains a limitation.
* Forward searches depend on callee coverage. Preserve the historical
* unknown-reason encoding when reading observations without explicit directions.
*/
export const isCallerOnlyUnknownCoverage = (
export const isCallerOnlyIncompleteCoverage = (
coverage: RelationshipCoverage,
): boolean =>
coverage.status === "unknown" &&
coverage.reason.startsWith(callerCoveragePrefix) &&
!coverage.reason.includes(calleeCoveragePrefix);
): boolean => {
if (coverage.status === "complete") return false;
if (coverage.limited_directions !== undefined)
return !coverage.limited_directions.some(
(direction) => direction === "callees",
);
return (
coverage.status === "unknown" &&
coverage.reason.startsWith(callerCoveragePrefix) &&
!coverage.reason.includes(calleeCoveragePrefix)
);
};
/** Explain why two resolved call sets cannot establish call-set equality. */
export const functionCallCoverageLimitations = (
coverage: RelationshipCoverage | null,
dossier: Pick<FunctionDossier, "unresolved_calls">,
): string[] => {
const limitations =
coverage === null
? ["Provider did not report relationship coverage."]
: coverage.status === "unknown"
? [
coverage.reason,
...("diagnostics" in coverage ? coverage.diagnostics : []),
]
: coverage.status === "partial"
? [
...coverage.limitations,
...("diagnostics" in coverage ? coverage.diagnostics : []),
]
: [];
limitations.push(
return uniqueSorted([
...relationshipCoverageLimitations(coverage),
...(coverage?.status === "complete" ? [] : (coverage?.diagnostics ?? [])),
...(dossier.unresolved_calls ?? []).map(
({ address, reason }) => `Unresolved call at ${address}: ${reason}`,
),
);
return uniqueSorted(limitations);
]);
};
+12 -4
View File
@@ -147,7 +147,7 @@ export const ghidraNativeApiBoundary = () => ({
],
});
export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
export const ghidraFunctionDossier = (): JsonValue => {
const pseudocode = "int fixture_main(void) { return 42; }";
return {
procedure: {
@@ -156,10 +156,18 @@ export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
locals: [],
},
pseudocode,
assembly: includeAssembly
? ["0x401000: CALL 0x401020", "0x401005: RET"]
: [],
assembly: ["0x401000: CALL 0x401020", "0x401005: RET"],
comments: [],
facet_availability: {
pseudocode: { available: true },
assembly: { available: true },
comments: { available: true },
callers: { available: true },
callees: { available: true },
references: { available: true },
strings_names: { available: true },
cfg: { available: true },
},
callers: [],
callees: [],
incoming_references: [],
+3 -2
View File
@@ -72,7 +72,7 @@ export const harmonyApplicationProjectionResultSchema = z.strictObject({
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
limitations: z.array(z.string()),
});
export type HarmonyApplicationProjectionInput = z.infer<
@@ -112,7 +112,8 @@ export const projectHarmonyApplication = (
classified.native_libraries,
);
const limitations = [
...(!hasCompleteInventoryCoverage(inventory)
...inventory.limitations,
...(!hasCompleteInventoryCoverage(inventory, "container-entries")
? ["Source inventory coverage is partial; absence is unknown."]
: []),
...(unavailable.length > 0
+12
View File
@@ -0,0 +1,12 @@
/**
* Apple publisher identity pinned for the official Hopper macOS bundle. The
* team identifier was captured from `Hopper-6.6.0-demo.dmg` at
* `https://www.hopperapp.com:443/downloader/public/Hopper-6.6.0-demo.dmg`
* (34846271 bytes, SHA-1 0be530f038249742590992199c7b042ea20ca955) with
* `codesign -dvvv`, which reported
* `Authority=Developer ID Application: Cryptic Apps (2AMA2753NF)`.
*/
export const HOPPER_PUBLISHER = Object.freeze({
bundleIdentifier: "com.cryptic-apps.hopper-web-4",
teamIdentifier: "2AMA2753NF",
});
+13 -1
View File
@@ -78,9 +78,21 @@ describe("Hopper boundary values", () => {
(_label, parse) => {
const result = parse();
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
},
);
it("uses provider-neutral wording for malformed shared values", () => {
const result = parseSegments([{ name: 1 }]);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisOutputError");
expect(result.error.operation).toBe("list_segments");
expect(result.error.reason).toBe(
"Provider returned an invalid segment list",
);
}
});
});
describe("provider-neutral inclusive function body evidence", () => {
+33 -21
View File
@@ -7,7 +7,6 @@ import { err, ok, type Result } from "./result.js";
import { nativeApiBoundarySchema } from "./native/nativeApiBoundary.js";
import { nativeValueFlowSchema } from "./native/nativeValueFlow.js";
import { AnalysisOutputError } from "./analysisErrorCore.js";
import { HopperProtocolError } from "./hopperErrors.js";
export interface AddressedName {
readonly address: string;
@@ -460,10 +459,11 @@ export const parseFunctionDossier = (
);
};
/** Parse Hopper's direct or wrapped procedure map into stable entries. */
/** Parse a provider's direct or wrapped procedure map into stable entries. */
export const parseProcedures = (
value: JsonValue,
): Result<readonly AddressedName[], HopperProtocolError> => {
operation = "list_procedures",
): Result<readonly AddressedName[], AnalysisOutputError> => {
const parsed = procedureMapSchema.safeParse(
unwrapProperty(value, "procedures"),
);
@@ -474,43 +474,48 @@ export const parseProcedures = (
name,
})),
)
: invalid("procedure map", parsed.error);
: invalid(operation, "procedure map", parsed.error);
};
/** Parse Hopper's direct or wrapped list of address/name records. */
/** Parse a provider's direct or wrapped list of address/name records. */
export const parseNames = (
value: JsonValue,
): Result<readonly AddressedName[], HopperProtocolError> => {
operation = "list_names",
): Result<readonly AddressedName[], AnalysisOutputError> => {
const unwrapped = unwrapProperty(value, "names");
const records = addressedNamesSchema.safeParse(unwrapped);
if (records.success) return ok(records.data);
const map = addressedNameMapSchema.safeParse(unwrapped);
return map.success
? ok(Object.entries(map.data).map(([address, name]) => ({ address, name })))
: invalid("name list", map.error);
: invalid(operation, "name list", map.error);
};
/** Parse callee/caller strings from direct or wrapped Hopper results. */
/** Parse callee/caller strings from direct or wrapped provider results. */
export const parseRelatedAddresses = (
value: JsonValue,
relation: "callees" | "callers",
): Result<readonly string[], HopperProtocolError> => {
operation = relation === "callees"
? "procedure_callees"
: "procedure_callers",
): Result<readonly string[], AnalysisOutputError> => {
const parsed = z.array(z.string()).safeParse(unwrapProperty(value, relation));
return parsed.success
? ok(parsed.data)
: invalid(`${relation} list`, parsed.error);
: invalid(operation, `${relation} list`, parsed.error);
};
/** Preserve reported address context in direct or wrapped provider segments. */
export const parseSegments = (
value: JsonValue,
): Result<readonly SegmentSummary[], HopperProtocolError> => {
operation = "list_segments",
): Result<readonly SegmentSummary[], AnalysisOutputError> => {
const parsed = z
.array(segmentSchema)
.safeParse(unwrapProperty(value, "segments"));
return parsed.success
? ok(parsed.data)
: invalid("segment list", parsed.error);
: invalid(operation, "segment list", parsed.error);
};
/** Return a reported overview base only when every parsed segment agrees. */
@@ -524,30 +529,32 @@ export const parseSegmentImageBase = (
: undefined;
};
/** Parse direct or wrapped Hopper document names. */
/** Parse direct or wrapped provider document names. */
export const parseDocuments = (
value: JsonValue,
): Result<readonly string[], HopperProtocolError> => {
operation = "list_documents",
): Result<readonly string[], AnalysisOutputError> => {
const parsed = z
.array(z.string())
.safeParse(unwrapProperty(value, "documents"));
return parsed.success
? ok(parsed.data)
: invalid("document list", parsed.error);
: invalid(operation, "document list", parsed.error);
};
/** Parse a direct or wrapped list when only its cardinality is required. */
export const parseListCount = (
value: JsonValue,
property: string,
): Result<number, HopperProtocolError> => {
operation = property === "procedures" ? "list_procedures" : "list_strings",
): Result<number, AnalysisOutputError> => {
const unwrapped = unwrapProperty(value, property);
const list = z.array(z.unknown()).safeParse(unwrapped);
if (list.success) return ok(list.data.length);
const map = z.record(z.string(), z.unknown()).safeParse(unwrapped);
return map.success
? ok(Object.keys(map.data).length)
: invalid(`${property} list`, map.error);
: invalid(operation, `${property} list`, map.error);
};
const unwrapProperty = (value: JsonValue, property: string): JsonValue => {
@@ -563,11 +570,16 @@ const unwrapProperty = (value: JsonValue, property: string): JsonValue => {
};
const invalid = <T>(
operation: string,
expected: string,
cause: z.ZodError,
): Result<T, HopperProtocolError> =>
): Result<T, AnalysisOutputError> =>
err(
new HopperProtocolError(`Hopper returned an invalid ${expected}`, {
cause,
}),
new AnalysisOutputError(
operation,
`Provider returned an invalid ${expected}`,
{
cause,
},
),
);
@@ -2,6 +2,67 @@ import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
describe("native addon type-only TypeScript imports", () => {
it("ignores declaration-wide import type and export type from .node modules", () => {
const analysis = analyzeJavaScriptStaticSource(`
import type { NativeThing } from "./addon.node";
export type { Extra } from "./addon.node";
`);
expect(analysis.parse_status).toBe("complete");
expect(analysis.electron.native_addon_bindings).toEqual([]);
});
it("keeps only value members from mixed type/value native imports", () => {
const analysis = analyzeJavaScriptStaticSource(`
import { type OtherThing, load } from "./addon.node";
load();
`);
expect(analysis.electron.native_addon_bindings).toEqual([
expect.objectContaining({
specifier: "./addon.node",
binding_kind: "import",
members: ["load"],
}),
]);
});
it("retains ordinary value imports of native addons", () => {
const analysis = analyzeJavaScriptStaticSource(`
import { load } from "./addon.node";
load();
`);
expect(analysis.electron.native_addon_bindings).toEqual([
expect.objectContaining({
specifier: "./addon.node",
binding_kind: "import",
members: ["load"],
}),
]);
});
});
describe("native addon type-only re-exports", () => {
it.each([
['export { type Extra, load } from "./addon.node";', ["load"]],
['export { type Extra } from "./addon.node";', []],
['export type * from "./addon.node";', []],
] as const)("retains only runtime members from %s", (source, members) => {
const analysis = analyzeJavaScriptStaticSource(source);
expect(analysis.parse_status).toBe("complete");
expect(analysis.electron.native_addon_bindings).toEqual(
members.length === 0
? []
: [
expect.objectContaining({
specifier: "./addon.node",
binding_kind: "re-export",
members: [...members],
}),
],
);
});
});
describe("native addon loader provenance", () => {
it("distinguishes CommonJS and ESM re-exports", () => {
const analysis = analyzeJavaScriptStaticSource(`
@@ -6,6 +6,12 @@ import {
} from "../unicodeCodePointOrder.js";
import { stripQueryAndFragment } from "../artifactPathSyntax.js";
import type { ElectronNativeAddonBindingFinding } from "./electronStaticAnalysisTypes.js";
import {
isTypeOnlyExportDeclaration,
isTypeOnlyExportSpecifier,
isTypeOnlyImportDeclaration,
isTypeOnlyImportSpecifier,
} from "./javascriptModuleDeclaration.js";
import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js";
import {
argumentNode,
@@ -47,7 +53,15 @@ const inspectImport = (
context: JavaScriptFindingContext,
): void => {
if (!isNativeSpecifier(node.source.value, "import")) return;
const members = node.specifiers.flatMap((specifier) => {
// TypeScript erases `import type` and per-binding `type` imports; they never
// request a runtime native-addon member.
if (isTypeOnlyImportDeclaration(node)) return;
const valueSpecifiers = node.specifiers.filter(
(specifier) =>
!(t.isImportSpecifier(specifier) && isTypeOnlyImportSpecifier(specifier)),
);
if (node.specifiers.length > 0 && valueSpecifiers.length === 0) return;
const members = valueSpecifiers.flatMap((specifier) => {
if (t.isImportDefaultSpecifier(specifier)) return ["default"];
if (t.isImportNamespaceSpecifier(specifier)) return [];
return [propertyName(specifier.imported)];
@@ -59,7 +73,7 @@ const inspectImport = (
kind: "import",
moduleKind: "import",
members,
namespaceAccess: node.specifiers.some((value) =>
namespaceAccess: valueSpecifiers.some((value) =>
t.isImportNamespaceSpecifier(value),
),
dynamicMemberAccess: false,
@@ -76,7 +90,13 @@ const inspectNamedExport = (
!isNativeSpecifier(node.source.value, "import")
)
return;
const members = node.specifiers.flatMap((specifier) => {
if (isTypeOnlyExportDeclaration(node)) return;
const valueSpecifiers = node.specifiers.filter(
(specifier) =>
!(t.isExportSpecifier(specifier) && isTypeOnlyExportSpecifier(specifier)),
);
if (node.specifiers.length > 0 && valueSpecifiers.length === 0) return;
const members = valueSpecifiers.flatMap((specifier) => {
if (t.isExportSpecifier(specifier)) return [propertyName(specifier.local)];
if (t.isExportDefaultSpecifier(specifier)) return ["default"];
return [];
@@ -88,7 +108,7 @@ const inspectNamedExport = (
kind: "re-export",
moduleKind: "import",
members,
namespaceAccess: node.specifiers.some((value) =>
namespaceAccess: valueSpecifiers.some((value) =>
t.isExportNamespaceSpecifier(value),
),
dynamicMemberAccess: false,
@@ -101,7 +121,8 @@ const inspectExportAll = (
): void => {
if (
node.source === undefined ||
!isNativeSpecifier(node.source.value, "import")
!isNativeSpecifier(node.source.value, "import") ||
isTypeOnlyExportDeclaration(node)
)
return;
addBinding({
@@ -1,4 +1,5 @@
import * as t from "@babel/types";
import { runtimeFunctionParameters } from "./javascriptAstValues.js";
import { JavaScriptSymbolicBindings } from "./javascriptSymbolicBindings.js";
import {
symbolicVariants,
@@ -447,7 +448,9 @@ export const collectElectronWrappedCallPaths = (
const entry = `${key.value}.${name}`;
functionBody(
fn,
fn.node.params.map(() => symbolicUnknown("public API argument")),
runtimeFunctionParameters(fn.node).map(() =>
symbolicUnknown("public API argument"),
),
{
...memberContext,
entryNode: node,
@@ -77,15 +77,23 @@ export const matchJavaScriptApplicationVersions = (
): ApplicationVersionMatchingProjection => {
const left = new Map(leftNodes.map((node) => [node.node_id, node]));
const right = new Map(rightNodes.map((node) => [node.node_id, node]));
const leftCandidates = new Map<string, Set<string>>();
const rightCandidates = new Map<string, Set<string>>();
const pairs: ApplicationVersionNodePair[] = [];
const ambiguousGroups: AmbiguousGroup[] = [];
for (const tier of matchTiers())
applyTier({ left, right, pairs, leftCandidates, rightCandidates, tier });
applyTier({ left, right, pairs, ambiguousGroups, tier });
const remainingLeft = sortedNodes(left.values());
const remainingRight = sortedNodes(right.values());
const leftIds = new Set(remainingLeft.map(({ node_id: id }) => id));
const rightIds = new Set(remainingRight.map(({ node_id: id }) => id));
const leftCandidates = new Map<string, Set<string>>();
const rightCandidates = new Map<string, Set<string>>();
// Later tiers can pair members of an ambiguous group. Expand only survivors,
// without pairing groups that became unique after those later matches.
for (const group of ambiguousGroups) {
const leftGroup = group.left.filter((node) => left.has(node.node_id));
if (leftGroup.length === 0) continue;
const rightGroup = group.right.filter((node) => right.has(node.node_id));
if (rightGroup.length === 0) continue;
recordCandidates(leftGroup, rightGroup, leftCandidates, rightCandidates);
}
return {
pairs: pairs.sort((a, b) =>
compareUnicodeCodePoints(
@@ -95,17 +103,21 @@ export const matchJavaScriptApplicationVersions = (
),
unmatchedLeft: remainingLeft,
unmatchedRight: remainingRight,
candidatesForLeft: filteredCandidates(leftCandidates, rightIds),
candidatesForRight: filteredCandidates(rightCandidates, leftIds),
candidatesForLeft: sortedCandidates(leftCandidates),
candidatesForRight: sortedCandidates(rightCandidates),
};
};
interface AmbiguousGroup {
readonly left: readonly ApplicationNode[];
readonly right: readonly ApplicationNode[];
}
interface TierContext {
readonly left: Map<string, ApplicationNode>;
readonly right: Map<string, ApplicationNode>;
readonly pairs: ApplicationVersionNodePair[];
readonly leftCandidates: Map<string, Set<string>>;
readonly rightCandidates: Map<string, Set<string>>;
readonly ambiguousGroups: AmbiguousGroup[];
readonly tier: MatchTier;
}
@@ -114,15 +126,12 @@ const applyTier = (context: TierContext): void => {
const rightByKey = nodesByKey(context.right.values(), context.tier.key);
for (const key of [...leftByKey.keys()].sort(compareUnicodeCodePoints)) {
const leftGroup = leftByKey.get(key) ?? [];
const rightGroup = rightByKey.get(key) ?? [];
if (rightGroup.length === 0) continue;
recordCandidates(
leftGroup,
rightGroup,
context.leftCandidates,
context.rightCandidates,
);
if (leftGroup.length !== 1 || rightGroup.length !== 1) continue;
const rightGroup = rightByKey.get(key);
if (rightGroup === undefined) continue;
if (leftGroup.length !== 1 || rightGroup.length !== 1) {
context.ambiguousGroups.push({ left: leftGroup, right: rightGroup });
continue;
}
const leftNode = leftGroup[0];
const rightNode = rightGroup[0];
if (leftNode === undefined || rightNode === undefined) continue;
@@ -144,7 +153,9 @@ const nodesByKey = (
for (const node of nodes) {
const key = keyFor(node);
if (key === null) continue;
output.set(key, [...(output.get(key) ?? []), node]);
const group = output.get(key);
if (group === undefined) output.set(key, [node]);
else group.push(node);
}
return output;
};
@@ -169,17 +180,14 @@ const recordCandidates = (
}
};
const filteredCandidates = (
const sortedCandidates = (
candidates: ReadonlyMap<string, ReadonlySet<string>>,
retained: ReadonlySet<string>,
): ReadonlyMap<string, readonly string[]> =>
new Map(
[...candidates.entries()].flatMap(([nodeId, values]) => {
const filtered = [...values]
.filter((value) => retained.has(value))
.sort(compareUnicodeCodePoints);
return filtered.length === 0 ? [] : [[nodeId, filtered] as const];
}),
[...candidates.entries()].map(([nodeId, values]) => [
nodeId,
[...values].sort(compareUnicodeCodePoints),
]),
);
const nodeIdentityKey = (node: ApplicationNode): string =>
@@ -0,0 +1,181 @@
import { describe, expect, it } from "vitest";
import {
artifactEvidence,
completeCoverage,
fixtureNode,
} from "./javascriptApplicationGraph.fixture.js";
import {
createJavaScriptApplicationGraph,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js";
const ARTIFACT_SHA = "a".repeat(64);
const moduleNode = (name: string, source: string, structure?: string) =>
fixtureNode(
"javascript-module",
{
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: ARTIFACT_SHA,
path: `${name}.js`,
},
name,
{
source_sha256: source.repeat(64),
...(structure === undefined
? {}
: {
structural_fingerprint_sha256: structure.repeat(64),
structural_fingerprint_algorithm: "fixture",
}),
},
artifactEvidence(ARTIFACT_SHA, `${name}.js`),
);
const graph = (nodes: ApplicationNode[]): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: nodes.map(({ node_id }) => node_id),
nodes,
edges: [],
coverage: completeCoverage,
limitations: [],
});
const compare = (
left: JavaScriptApplicationGraph,
right: JavaScriptApplicationGraph,
) =>
compareJavaScriptApplicationVersions({
left: {
evidenceId: `ev_${"1".repeat(64)}`,
rootArtifactSha256: ARTIFACT_SHA,
graph: left,
},
right: {
evidenceId: `ev_${"2".repeat(64)}`,
rootArtifactSha256: ARTIFACT_SHA,
graph: right,
},
leftNativeEvidence: [],
rightNativeEvidence: [],
});
describe("application version matching", () => {
it("does not revisit a source group that becomes unique after identity matching", () => {
const shared = moduleNode("shared", "1");
const leftOnly = moduleNode("left", "1");
const rightOnly = moduleNode("right", "1");
const result = compare(
graph([shared, leftOnly]),
graph([shared, rightOnly]),
);
expect(result.matching).toMatchObject({
exact_node_identity: 1,
exact_module_source_digest: 0,
ambiguous: 2,
unmatched: 0,
});
expect(
result.items.find(({ left_node_id }) => left_node_id === shared.node_id),
).toMatchObject({
right_node_id: shared.node_id,
match: { status: "matched", basis: "exact-node-identity" },
});
expect(
result.items.find(
({ left_node_id }) => left_node_id === leftOnly.node_id,
),
).toMatchObject({
status: "unknown",
right_node_id: null,
match: {
status: "ambiguous",
candidate_right_node_ids: [rightOnly.node_id],
},
});
expect(
result.items.find(
({ right_node_id }) => right_node_id === rightOnly.node_id,
),
).toMatchObject({
status: "unknown",
left_node_id: null,
match: {
status: "ambiguous",
candidate_left_node_ids: [leftOnly.node_id],
},
});
});
it("unions all unresolved source and structural candidates without forcing pairs", () => {
const a = moduleNode("a", "1", "a");
const b = moduleNode("b", "1", "a");
const c = moduleNode("c", "2", "a");
const x = moduleNode("x", "1", "a");
const y = moduleNode("y", "1", "b");
const z = moduleNode("z", "3", "a");
const left = graph([a, b, c]);
const right = graph([x, y, z]);
const result = compare(left, right);
expect(result.summary).toEqual({
unchanged: 0,
added: 0,
removed: 0,
changed: 0,
unknown: 6,
});
expect(result.matching).toMatchObject({ ambiguous: 6, unmatched: 0 });
for (const [node, candidates] of [
[a, [x, y, z]],
[b, [x, y, z]],
[c, [x, z]],
] as const) {
expect(
result.items.find(({ left_node_id }) => left_node_id === node.node_id)
?.match,
).toEqual({
status: "ambiguous",
basis: "none",
confidence: "unknown",
candidate_left_node_ids: [],
candidate_right_node_ids: candidates
.map(({ node_id }) => node_id)
.sort(),
});
}
for (const [node, candidates] of [
[x, [a, b, c]],
[y, [a, b]],
[z, [a, b, c]],
] as const) {
expect(
result.items.find(({ right_node_id }) => right_node_id === node.node_id)
?.match,
).toEqual({
status: "ambiguous",
basis: "none",
confidence: "unknown",
candidate_left_node_ids: candidates
.map(({ node_id }) => node_id)
.sort(),
candidate_right_node_ids: [],
});
}
// Permute the already validated graph so matching sees the changed order.
// Compare the full result, including item, comparison and change-graph IDs.
expect(
compare(
{ ...left, nodes: [...left.nodes].reverse() },
{ ...right, nodes: [...right.nodes].reverse() },
),
).toEqual(result);
});
});
@@ -7,6 +7,7 @@ import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import {
propertyName,
runtimeFunctionParameters,
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
@@ -38,15 +39,13 @@ export const collectJavaScriptExports = (
bindings?: JavaScriptSemanticAnalysisState,
): StaticExports => {
const exports = new Set<string>();
const parameter = t.isFunction(node)
? runtimeFunctionParameters(node)[1]
: undefined;
const factoryExports =
bindings !== undefined &&
t.isFunction(node) &&
t.isIdentifier(node.params[1])
? resolveSemanticBindingState(
bindings,
node.params[1],
node.params[1].name,
)?.bindingId
bindings !== undefined && t.isFunction(node) && t.isIdentifier(parameter)
? resolveSemanticBindingState(bindings, parameter, parameter.name)
?.bindingId
: undefined;
const isExportsAlias = (reference: t.Node | null): boolean => {
if (!t.isIdentifier(reference)) return false;
@@ -1,6 +1,14 @@
import * as t from "@babel/types";
import type { JavaScriptSemanticPrimitive } from "./javascriptSemanticValueTypes.js";
/** TypeScript receiver annotations occupy no positional runtime parameter slot. */
export const runtimeFunctionParameters = (
node: t.Function,
): t.Function["params"] =>
t.isIdentifier(node.params[0], { name: "this" })
? node.params.slice(1)
: node.params;
/**
* Remove wrappers that affect TypeScript or Flow checking but not runtime
* expression identity. The returned depth lets bounded evaluators account for
+7 -4
View File
@@ -1,6 +1,9 @@
import * as t from "@babel/types";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import {
semanticStaticPropertyKey,
runtimeFunctionParameters,
} from "./javascriptAstValues.js";
import { moduleFactory } from "./javascriptStaticAnalysisHelpers.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
@@ -27,7 +30,7 @@ export const javascriptBootstrapAt = (
(!t.isFunctionExpression(call.callee) &&
!t.isArrowFunctionExpression(call.callee)) ||
!t.isBlockStatement(call.callee.body) ||
call.callee.params.length !== 0 ||
runtimeFunctionParameters(call.callee).length !== 0 ||
call.arguments.length !== 0
)
return undefined;
@@ -63,10 +66,10 @@ export const javascriptBootstrapAt = (
!t.isFunctionDeclaration(loader) ||
loader.id === null ||
loader.id === undefined ||
loader.params.length !== 1
runtimeFunctionParameters(loader).length !== 1
)
continue;
const parameter = loader.params[0];
const parameter = runtimeFunctionParameters(loader)[0];
if (!t.isIdentifier(parameter)) continue;
const loaderName = loader.id.name;
const loaderBindingId = bindingId(state, loader.id);
@@ -26,6 +26,7 @@ import {
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
import {
readExactJavaScriptLiteral,
runtimeFunctionParameters,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
@@ -662,10 +663,10 @@ const identityFunction = (
!t.isFunction(node) ||
node.async ||
node.generator ||
node.params.length !== 1
runtimeFunctionParameters(node).length !== 1
)
return false;
const parameter = node.params[0];
const parameter = runtimeFunctionParameters(node)[0];
const result = t.isBlockStatement(node.body)
? node.body.body.length === 1 && t.isReturnStatement(node.body.body[0])
? node.body.body[0].argument
@@ -130,3 +130,74 @@ describe("JavaScript semantic analysis: runtime boundaries 1", () => {
expect(ir.objectOperations.length).toBeGreaterThan(0);
});
});
describe("JavaScript semantic analysis: event dispatch data", () => {
it("keeps emitted data out of dispatch listener fields", () => {
const ir = analyzeJavaScriptSemantics(`
import { EventEmitter } from "node:events";
const bus = new EventEmitter();
const data = 1;
const handler = () => {};
bus.on("ready", handler);
bus.emit("ready", data);
bus.emit("ready");
bus.off("ready", handler);
bus.removeAllListeners("ready", data);
`);
const handler = ir.bindings.find(({ name }) => name === "handler");
expect(handler).toBeDefined();
expect(
ir.eventOperations.map(
({ kind, method, listenerBindingId, listenerLocation }) => ({
kind,
method,
listenerBindingId,
hasListenerLocation: listenerLocation !== null,
}),
),
).toEqual([
{
kind: "register",
method: "on",
listenerBindingId: handler?.bindingId,
hasListenerLocation: true,
},
{
kind: "dispatch",
method: "emit",
listenerBindingId: null,
hasListenerLocation: false,
},
{
kind: "dispatch",
method: "emit",
listenerBindingId: null,
hasListenerLocation: false,
},
{
kind: "remove",
method: "off",
listenerBindingId: handler?.bindingId,
hasListenerLocation: true,
},
{
kind: "remove",
method: "removeAllListeners",
listenerBindingId: null,
hasListenerLocation: false,
},
]);
expect(
ir.eventOperations.map(({ eventName, resolution }) => [
eventName,
resolution,
]),
).toEqual([
["ready", "complete"],
["ready", "complete"],
["ready", "complete"],
["ready", "complete"],
["ready", "complete"],
]);
});
});
@@ -10,6 +10,45 @@ import {
origin,
} from "./javascriptSemanticAnalysis.fixture.js";
describe("JavaScript semantic analysis: ESM import origins", () => {
it.each(["", "a", "0"])(
"preserves exact ESM import name %j in binding origins",
(name) => {
const ir = analyzeJavaScriptSemantics(
"import { " +
JSON.stringify(name) +
' as selected } from "./module.mjs"; const alias = selected; export { alias };',
);
for (const binding of ["selected", "alias"])
expect(origin(topLevelBinding(ir, binding))).toEqual({
specifier: "./module.mjs",
importedPath: [name],
});
expect(ir.moduleLinks).toContainEqual(
expect.objectContaining({
kind: "import",
importedName: name,
localName: "selected",
}),
);
},
);
it("keeps default and namespace import origins distinct from an empty named import", () => {
const ir = analyzeJavaScriptSemantics(
'import value from "./module.mjs"; import * as namespace from "./module.mjs";',
);
expect(origin(topLevelBinding(ir, "value"))).toEqual({
specifier: "./module.mjs",
importedPath: ["default"],
});
expect(origin(topLevelBinding(ir, "namespace"))).toEqual({
specifier: "./module.mjs",
importedPath: [],
});
});
});
describe("JavaScript semantic analysis: structure 1", () => {
it("resolves imports, require destructuring, aliases, assignments, and shadowing", () => {
const ir = analyzeJavaScriptSemantics(`
@@ -18,6 +18,7 @@ import {
} from "./javascriptSemanticProjection.js";
import {
semanticObjectPatternKeys,
runtimeFunctionParameters,
semanticStaticPropertyKey,
semanticWriteTargets,
} from "./javascriptAstValues.js";
@@ -57,7 +58,6 @@ import {
ELECTRON_MODULE,
} from "./javascriptElectronMemberWrites.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import { propertyName } from "./javascriptAstValues.js";
import { semanticCoverage } from "./javascriptSemanticCoverage.js";
import { semanticResourceLimitsIn } from "./javascriptSemanticResourceLimits.js";
import {
@@ -718,7 +718,7 @@ function* collectDefinitionsSteps(
functionBodies.push({
body: node,
scope: nested,
parameters: parent.params,
parameters: runtimeFunctionParameters(parent),
});
}
const scope = currentSemanticScope(stack);
@@ -1077,7 +1077,7 @@ const scopeKind = (
};
const functionParametersHaveExpressions = (node: t.Function): boolean => {
const pending: t.Node[] = [...node.params];
const pending: t.Node[] = [...runtimeFunctionParameters(node)];
while (pending.length > 0) {
const parameter = pending.pop();
if (t.isAssignmentPattern(parameter)) return true;
@@ -1109,7 +1109,7 @@ const bindImports = (
? ["default"]
: t.isImportNamespaceSpecifier(specifier)
? []
: [propertyName(specifier.imported) || "[dynamic]"];
: [semanticStaticPropertyKey(specifier.imported, false) ?? "[dynamic]"];
addBinding({
state,
scope,
@@ -1134,7 +1134,7 @@ const bindFunctionLocals = (
scope: JavaScriptSemanticScopeState,
state: JavaScriptSemanticAnalysisState,
): void => {
for (const parameter of node.params)
for (const parameter of runtimeFunctionParameters(node))
bindPattern({
pattern: t.isTSParameterProperty(parameter)
? parameter.parameter
@@ -37,6 +37,13 @@ const EVENT_REMOVE_METHODS = [
"removeListener",
"removeAllListeners",
] as const;
/**
* Methods whose argument position 1 names a listener. `removeAllListeners`
* takes only an optional event name, and `emit` passes its remaining
* arguments as data to listeners that already exist.
*/
const EVENT_LISTENER_METHODS: readonly JavaScriptSemanticEventOperation["method"][] =
[...EVENT_REGISTER_METHODS, "off", "removeListener"];
const EVENT_METHODS = [
...EVENT_REGISTER_METHODS,
...EVENT_REMOVE_METHODS,
@@ -137,7 +144,9 @@ const collectEvent = (
if (method === undefined) return;
const kind = eventKind(method);
const eventArgument = node.arguments[0];
const listenerArgument = node.arguments[1];
const listenerArgument = EVENT_LISTENER_METHODS.includes(method)
? node.arguments[1]
: undefined;
const emitter = emitterIdentity(member.object, state);
const eventName = dataEffectLiteralString(eventArgument);
output.push({
@@ -6,7 +6,10 @@ import type {
} from "./javascriptSemanticIr.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
import { unwrapJavaScriptExpression } from "./javascriptAstValues.js";
import {
unwrapJavaScriptExpression,
runtimeFunctionParameters,
} from "./javascriptAstValues.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
@@ -194,14 +197,15 @@ const parameterAcceptsArgument = (
): boolean => {
const node = state.callableNodesById.get(callable.callableId);
if (!t.isFunction(node)) return false;
const parameterIndex = node.params.findIndex((parameter) =>
const parameters = runtimeFunctionParameters(node);
const parameterIndex = parameters.findIndex((parameter) =>
rangeContains(range(parameter), location),
);
if (parameterIndex === argumentIndex) return true;
return (
parameterIndex >= 0 &&
parameterIndex < argumentIndex &&
t.isRestElement(node.params[parameterIndex])
t.isRestElement(parameters[parameterIndex])
);
};
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import * as t from "@babel/types";
import { runtimeFunctionParameters } from "./javascriptAstValues.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { JavaScriptSemanticCallAnalysis } from "./javascriptSemanticCalls.js";
@@ -279,7 +280,7 @@ const relationShape = (
];
const callableParameterArity = (node: t.Node): number =>
t.isFunction(node) ? node.params.length : 0;
t.isFunction(node) ? runtimeFunctionParameters(node).length : 0;
const isAsyncCallable = (node: t.Node): boolean =>
t.isFunction(node) && node.async;
@@ -2,6 +2,7 @@ import * as t from "@babel/types";
import {
semanticObjectPatternKeys,
runtimeFunctionParameters,
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import {
@@ -212,7 +213,8 @@ export const semanticIterationSources = (
else if (t.isYieldExpression(node) && node.delegate && node.argument != null)
add(sources, { node: node.argument, projection: [] }, node, {});
else if (t.isFunction(node))
for (const parameter of node.params) visit(context, parameter, undefined);
for (const parameter of runtimeFunctionParameters(node))
visit(context, parameter, undefined);
return sources;
};
@@ -54,6 +54,57 @@ export function* collectSemanticMemberMutationsSteps(
const selections = new Map<string, readonly string[]>();
const coveringPaths = new Map<string, SemanticPropertyPathCoverage>();
let arrayIterationUnknown = false;
// Definition collection finishes before this phase, so a scope's bindings no
// longer change and one node resolves to one binding. Repeated visits of the
// same node otherwise repeat the same scope walk.
const resolvedBindings = new WeakMap<
t.Node,
JavaScriptSemanticBindingState | null
>();
const resolveBinding = (
node: t.Node,
name: string,
): JavaScriptSemanticBindingState | undefined => {
const cached = resolvedBindings.get(node);
if (cached !== undefined) return cached ?? undefined;
const resolved = resolveSemanticBindingState(state, node, name);
resolvedBindings.set(node, resolved ?? null);
return resolved;
};
// One capture tuple recurs across every alias it reaches. Re-encoding it
// would rebuild the same long key and force a fresh string hash per lookup.
const captureKeys = new WeakMap<
JavaScriptSemanticBindingState,
Map<string, string>
>();
const captureKeyOf = (
binding: JavaScriptSemanticBindingState,
originAt: t.Node | undefined,
ownerInitializer: t.Node | undefined,
): string => {
let byPosition = captureKeys.get(binding);
if (byPosition === undefined) {
byPosition = new Map();
captureKeys.set(binding, byPosition);
}
const positionKey = `${originAt?.start ?? "u"}:${originAt?.end ?? "u"}:${
ownerInitializer?.start ?? "u"
}:${ownerInitializer?.end ?? "u"}`;
const cached = byPosition.get(positionKey);
if (cached !== undefined) return cached;
const created = JSON.stringify([
binding.bindingId,
originAt?.start,
originAt?.end,
ownerInitializer?.start,
ownerInitializer?.end,
]);
byPosition.set(positionKey, created);
return created;
};
// A capture key already ends the array; a path stays one nested element.
const lifetimeKey = (captureKey: string, path: PropertyPath): string =>
`${captureKey.slice(0, -1)},${JSON.stringify(path)}]`;
const pendingReferences: {
readonly initializer: JavaScriptSemanticBindingState["referenceInitializers"][number];
readonly path: PropertyPath;
@@ -121,11 +172,7 @@ export function* collectSemanticMemberMutationsSteps(
if (current === undefined) break;
const expression = unwrapJavaScriptExpression(current.node).node;
if (t.isIdentifier(expression)) {
const binding = resolveSemanticBindingState(
state,
expression,
expression.name,
);
const binding = resolveBinding(expression, expression.name);
if (binding === undefined) {
if (
(expression.name === "Array" &&
@@ -142,21 +189,18 @@ export function* collectSemanticMemberMutationsSteps(
// An alias restored from a saved reference can revisit the same binding
// at an earlier capture or a shorter getter-receiver path. Only a
// repeated capture and path closes a cycle.
const capture = [
binding.bindingId,
current.originAt?.start,
current.originAt?.end,
current.ownerInitializer?.start,
current.ownerInitializer?.end,
];
const lifetime = JSON.stringify([...capture, current.path]);
const captureKey = captureKeyOf(
binding,
current.originAt,
current.ownerInitializer,
);
const lifetime = lifetimeKey(captureKey, current.path);
if (current.bindings.has(lifetime)) continue;
// A self alias such as `node = node[key]` revisits its capture with the
// same prefix added on every cycle, so exact paths never repeat. When
// that prefix can never be pruned, escaping it once covers every longer
// effect, including writes below shared children.
// Only a capture already on this alias chain can repeat a prefix.
const captureKey = JSON.stringify(capture);
const revisited = current.bindings.has(captureKey);
let repeatedPrefix: PropertyPath | undefined;
for (
@@ -165,8 +209,7 @@ export function* collectSemanticMemberMutationsSteps(
start++
) {
const suffix = current.path.slice(start);
if (!current.bindings.has(JSON.stringify([...capture, suffix])))
continue;
if (!current.bindings.has(lifetimeKey(captureKey, suffix))) continue;
repeatedPrefix = current.path.slice(0, start);
break;
}
@@ -408,7 +451,7 @@ export function* collectSemanticMemberMutationsSteps(
if (!t.isNode(node)) continue;
const pathKey = JSON.stringify(value.path);
if (t.isIdentifier(node) && value.iterableFallbackPath === undefined) {
const binding = resolveSemanticBindingState(state, node, node.name);
const binding = resolveBinding(node, node.name);
const identity = JSON.stringify([
binding === undefined ? null : binding.bindingId,
binding === undefined ? node.name : null,
@@ -12,6 +12,37 @@ interface StatementPosition {
readonly declaratorIndex: number;
}
/**
* Initializer positions depend only on a node and its parent map, which one
* analysis builds once and never changes. Different mutations and initializers
* re-derive the same positions along shared ancestry, so retain the first
* result for as long as its parent map is reachable.
*/
interface InitializerPositionCache {
readonly direct: WeakMap<t.Node, StatementPosition | null>;
readonly mutation: WeakMap<t.Node, StatementPosition | null>;
readonly reference: WeakMap<t.Node, StatementPosition | null>;
}
const initializerPositionCaches = new WeakMap<
WeakMap<t.Node, t.Node>,
InitializerPositionCache
>();
const initializerPositionCache = (
parents: WeakMap<t.Node, t.Node>,
): InitializerPositionCache => {
const cached = initializerPositionCaches.get(parents);
if (cached !== undefined) return cached;
const created: InitializerPositionCache = {
direct: new WeakMap(),
mutation: new WeakMap(),
reference: new WeakMap(),
};
initializerPositionCaches.set(parents, created);
return created;
};
const statementPosition = (
statement: t.Statement,
parents: WeakMap<t.Node, t.Node>,
@@ -42,7 +73,7 @@ const positionPrecedes = (
left.declaratorIndex >= 0 &&
left.declaratorIndex < right.declaratorIndex));
const directInitializerPosition = (
const computeDirectInitializerPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
@@ -67,7 +98,19 @@ const directInitializerPosition = (
return null;
};
const directMutationPosition = (
const directInitializerPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
const cache = initializerPositionCache(parents);
const cached = cache.direct.get(node);
if (cached !== undefined) return cached;
const computed = computeDirectInitializerPosition(node, parents);
cache.direct.set(node, computed);
return computed;
};
const computeDirectMutationPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
@@ -115,7 +158,19 @@ const directMutationPosition = (
}
};
const referenceInitializerPosition = (
const directMutationPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
const cache = initializerPositionCache(parents);
const cached = cache.mutation.get(node);
if (cached !== undefined) return cached;
const computed = computeDirectMutationPosition(node, parents);
cache.mutation.set(node, computed);
return computed;
};
const computeReferenceInitializerPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
@@ -137,6 +192,18 @@ const referenceInitializerPosition = (
}
};
const referenceInitializerPosition = (
node: t.Node,
parents: WeakMap<t.Node, t.Node>,
): StatementPosition | null => {
const cache = initializerPositionCache(parents);
const cached = cache.reference.get(node);
if (cached !== undefined) return cached;
const computed = computeReferenceInitializerPosition(node, parents);
cache.reference.set(node, computed);
return computed;
};
/** Resolve origins at their use or capture, never at a later transitive effect. */
export const semanticMutationInitializers = (
binding: JavaScriptSemanticBindingState,
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const endpoints = (source: string) =>
analyzeJavaScriptStaticSource(source).endpoints.map(
({ kind, value, mechanism }) => ({ kind, value, mechanism }),
);
describe("server-sent event endpoints", () => {
it("reports EventSource URLs like WebSocket URLs", () => {
expect(
endpoints(`
new WebSocket("wss://chat.example/ws");
new EventSource("/api/chat/stream");
new window.EventSource("https://chat.example/events", { withCredentials: true });
`),
).toEqual([
{
kind: "network",
value: "wss://chat.example/ws",
mechanism: "call:WebSocket",
},
{
kind: "network",
value: "/api/chat/stream",
mechanism: "call:EventSource",
},
{
kind: "network",
value: "https://chat.example/events",
mechanism: "call:window.EventSource",
},
]);
});
it("keeps a dynamic EventSource URL unreported", () => {
expect(endpoints("new EventSource(url);")).toEqual([]);
});
});
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const endpoints = (source: string) =>
analyzeJavaScriptStaticSource(source).endpoints.map(
({ kind, value, mechanism }) => ({ kind, value, mechanism }),
);
describe("beacon endpoints", () => {
it("reports navigator.sendBeacon URLs", () => {
expect(
endpoints(`
navigator.sendBeacon("/api/telemetry", payload);
window.navigator.sendBeacon("https://metrics.example/collect");
`),
).toEqual([
{
kind: "network",
value: "/api/telemetry",
mechanism: "call:navigator.sendBeacon",
},
{
kind: "network",
value: "https://metrics.example/collect",
mechanism: "call:window.navigator.sendBeacon",
},
]);
});
it("keeps a dynamic beacon URL unreported", () => {
expect(endpoints("navigator.sendBeacon(url, payload);")).toEqual([]);
});
});
@@ -1,4 +1,5 @@
import * as t from "@babel/types";
import { runtimeFunctionParameters } from "./javascriptAstValues.js";
import { javascriptBootstrapAt } from "./javascriptBootstrap.js";
import {
resolveSemanticBindingState,
@@ -304,7 +305,7 @@ const runtimeMetadata = (node: t.Node | null | undefined): RuntimeMetadata => {
asyncChunkKeys: [],
unknownAsyncChunkKeys: 0,
};
const parameter = node.params[0];
const parameter = runtimeFunctionParameters(node)[0];
const requireName = t.isIdentifier(parameter) ? parameter.name : null;
if (requireName === null)
return {
@@ -13,6 +13,7 @@ import type {
} from "./javascriptStaticAnalysisTypes.js";
import {
readExactJavaScriptLiteral,
runtimeFunctionParameters,
semanticStaticPropertyKey,
semanticStaticPropertyName,
unwrapJavaScriptExpression,
@@ -147,7 +148,7 @@ export const modulePropertyName = (
export const factoryRequireName = (
factory: t.FunctionExpression | t.ArrowFunctionExpression | t.ObjectMethod,
): string | null => {
const parameter = factory.params[2];
const parameter = runtimeFunctionParameters(factory)[2];
return t.isIdentifier(parameter) ? parameter.name : null;
};
@@ -553,7 +554,13 @@ export const endpointArgument = (
receiverFact?: JavaScriptOpenReceiverFact,
): string | undefined => {
if (receiverFact === "window") return undefined;
if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket")
if (
name === "fetch" ||
name.endsWith(".fetch") ||
name === "WebSocket" ||
name === "EventSource" ||
name.endsWith(".EventSource")
)
return stringValue(args[0]);
if (name.endsWith(".open"))
return xhrOpenUrl(name, args[0], args[1], receiverFact);
@@ -573,6 +580,9 @@ export const endpointArgument = (
? undefined
: value;
}
// navigator.sendBeacon(url, data) queues a POST to its first argument.
if (name === "sendBeacon" || name.endsWith(".sendBeacon"))
return stringValue(args[0]);
if (name.endsWith("loadURL")) return stringValue(args[0]);
return undefined;
};
@@ -1,6 +1,7 @@
import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
runtimeFunctionParameters,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import { javascriptBootstrapAt } from "./javascriptBootstrap.js";
@@ -387,7 +388,7 @@ export class JavaScriptSymbolicBindings {
invocationNode?: t.Node,
): SymbolicEnvironment {
const values = new Map<string, SymbolicValue>();
fn.node.params.forEach((param, index) => {
runtimeFunctionParameters(fn.node).forEach((param, index) => {
const target = t.isRestElement(param) ? param.argument : param;
if (!t.isIdentifier(target)) return;
const binding = resolveSemanticBindingState(
@@ -866,9 +867,7 @@ export class JavaScriptSymbolicBindings {
? {}
: { scopeId: this.state.scopeByNode.get(factory)!.scopeId }),
};
const first = factory.params[0];
const second = factory.params[1];
const third = factory.params[2];
const [first, second, third] = runtimeFunctionParameters(factory);
const binding = (n: t.Node | undefined) =>
t.isIdentifier(n)
? resolveSemanticBindingState(this.state, n, n.name)?.bindingId
+21
View File
@@ -219,6 +219,16 @@ const managedMemberReferenceSchema = z.object({
signature: managedSignatureSchema,
});
const managedUserStringSchema = z.object({
token: tokenSchema,
offset: offsetSchema.describe("File offset of the #US item"),
value: z
.string()
.describe(
"Decoded UTF-16 code units, excluding the terminal flag byte; unpaired surrogates are kept",
),
});
const managedModuleReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
@@ -457,6 +467,17 @@ export const managedMemberInspectionSchema = z.object({
member_refs: z.array(managedMemberReferenceSchema),
call_edges: z.array(managedCallEdgeSchema),
field_accesses: z.array(managedFieldAccessSchema),
// Distinct #US literals loaded by ldstr in the inspected method bodies, in
// token order, with their own coverage: #US issues never enter the member
// coverage. null means they were not examined, not that there were none.
user_strings: z
.object({
state: z.enum(["complete", "partial"]),
literals: z.array(managedUserStringSchema),
issues: z.array(managedParseIssueSchema),
})
.nullable()
.default(null),
/** Caller-selected declaring types; null when every type was inspected. */
selection: z
.object({
@@ -107,8 +107,8 @@ export const comparisonLimitations = (
): string[] => {
const limitations: string[] = [
"Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.",
"Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.",
"Fields pair by exact signature, then declared type, name, and signature; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.",
"Methods pair within one declared type and name by exact CIL/signature, then signature, then structural shape; only then may exact CIL/signature or structural shape alone remap across declared types or names, never taking a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Names alone are never a matching basis.",
"Fields pair by declared type, name, and signature, then remap by exact decoded signature alone under the same rule; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.",
];
if (left.coverage.state !== "complete" || right.coverage.state !== "complete")
limitations.push("At least one managed member observation is partial.");
@@ -131,5 +131,8 @@ export const comparisonLimitations = (
limitations.push(
"ExportedType rows, including type forwarders, are observed but not compared; an unchanged comparison does not establish an unchanged exported or forwarded type set.",
);
limitations.push(
"ldstr literals are not compared; normalized CIL keeps #US tokens rather than decoded text, so an unchanged method does not establish unchanged string literals.",
);
return limitations;
};
@@ -5,6 +5,7 @@ import type { ManagedMemberComparisonResult } from "./managedMemberComparison.js
import {
type ManagedFieldMatches,
type ManagedMethodMatches,
identityOf,
sha256,
} from "./managedMemberComparisonMatch.js";
@@ -73,7 +74,11 @@ const methodDimensions = (
if (bothAbsent) return { dimensions, bodyUnknown: false };
if (!leftBodyComplete || !rightBodyComplete)
return { dimensions, bodyUnknown: true };
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
// The decoded fingerprint omits switch targets and is not exact CIL identity.
if (
left.body.il_sha256 !== right.body.il_sha256 ||
left.body.normalized_il_sha256 !== right.body.normalized_il_sha256
)
dimensions.push("cil");
if (
canonicalize(left.body.opcode_counts) !==
@@ -207,33 +212,36 @@ const absenceLimitations = (
`signature-not-decoded: The member's ${member.signature.parse_status} signature was compared only by exact declared type, name, and raw bytes, so a changed or renamed counterpart could not be sought.`,
]),
...(member.signature.parse_status === "decoded" &&
opposite.oppositeUndecodedNames.has(declaredName(member))
opposite.oppositeUndecodedNames.size > 0 &&
opposite.oppositeUndecodedNames.has(identityOf(member))
? [
`counterpart-signature-not-decoded: The ${opposite.opposite} ${opposite.inventory} inventory has an unpaired member with the same declared type and name whose signature was not decoded, so it may be this member with a changed signature.`,
]
: []),
];
const declaredName = (member: Method | Field): string =>
JSON.stringify([member.declaring_type, member.name]);
/**
* Declared names of unpaired members whose signature was not decoded: one-sided
* members and candidates of ambiguous groups, which also remain unpaired.
*/
interface Unpaired {
readonly item: Method | Field;
readonly identity: string;
}
const undecodedOneSidedNames = (members: {
readonly leftOnly: readonly { readonly item: Method | Field }[];
readonly rightOnly: readonly { readonly item: Method | Field }[];
readonly leftOnly: readonly Unpaired[];
readonly rightOnly: readonly Unpaired[];
readonly ambiguous: readonly {
readonly left: readonly { readonly item: Method | Field }[];
readonly right: readonly { readonly item: Method | Field }[];
readonly left: readonly Unpaired[];
readonly right: readonly Unpaired[];
}[];
}): UndecodedOneSidedNames => {
const names = (side: readonly { readonly item: Method | Field }[]) =>
const names = (side: readonly Unpaired[]) =>
new Set(
side
.filter(({ item }) => item.signature.parse_status !== "decoded")
.map(({ item }) => declaredName(item)),
.map(({ identity }) => identity),
);
return {
left: names([
@@ -296,18 +304,20 @@ const fieldOnlyItem = (
};
/**
* Name the identity key an ambiguous group shares. The exact-signature key
* already includes the declared type and name, so names cannot separate it.
* Name only evidence shared by the whole group. Exact-signature ambiguities
* include both declared-identity collisions and unresolved raw-signature choices.
*/
const ambiguityLimitation = (
members: "methods" | "fields",
basis: MethodItem["match"]["basis"],
): string =>
basis === "exact-signature"
? `Multiple managed ${members} share the same declared type, name, and raw signature; REA did not guess a token remap.`
: members === "methods"
? "Multiple managed methods share the same non-name identity key; REA did not guess a token remap."
: "Multiple managed fields share the same signature; REA did not guess a token remap from names.";
? `Multiple managed ${members} share the same raw signature; REA did not guess declared ownership or a token remap.`
: basis === "exact-il-signature"
? "Multiple managed methods share the same CIL and signature; REA did not guess a token remap."
: members === "methods"
? "Multiple managed methods share the same structural shape; REA did not guess a token remap."
: "Multiple managed fields share the same signature; REA did not guess a token remap.";
export const buildMethodItems = (
matches: ManagedMethodMatches,
@@ -28,8 +28,11 @@ type ConcreteMatchBasis = Exclude<MatchBasis, "none">;
interface Keyed<Item> {
readonly item: Item;
/** Declared type and name; an unresolved type is null, the name remains. */
readonly identity: string;
readonly exactKey: string | null;
readonly signatureKey: string | null;
readonly rawSignatureKey: string;
readonly structuralKey: string | null;
}
@@ -48,11 +51,16 @@ interface Ambiguous<Item> {
const keyMethod = (item: Method): Keyed<Method> => ({
item,
identity: identityOf(item),
rawSignatureKey: item.signature.raw_sha256,
exactKey:
item.body.status === "present" && item.body.normalized_il_sha256 !== null
item.body.status === "present" &&
item.body.il_sha256 !== null &&
item.body.normalized_il_sha256 !== null
? sha256([
"method-exact",
item.signature.raw_sha256,
item.body.il_sha256,
item.body.normalized_il_sha256,
])
: null,
@@ -96,6 +104,8 @@ const keyMethod = (item: Method): Keyed<Method> => ({
const keyField = (item: Field): Keyed<Field> => ({
item,
identity: identityOf(item),
rawSignatureKey: item.signature.raw_sha256,
exactKey:
item.signature.parse_status === "decoded"
? sha256(["field-exact", item.signature.raw_sha256])
@@ -123,15 +133,34 @@ const matchMethods = (
matchByKeys({
left,
right,
exactBasis: "exact-il-signature",
fallbackBases: [
rounds: [
{
basis: "exact-il-signature",
key: declaredAs(({ exactKey }) => exactKey),
},
{
basis: "exact-signature",
key: ({ signatureKey }) => signatureKey,
competitionKey: ({ rawSignatureKey }) => rawSignatureKey,
},
{
basis: "structural-method-shape",
// An unresolved owner has no declared shape match to prove.
key: declaredAs((keyed) =>
keyed.item.declaring_type === null ? null : keyed.structuralKey,
),
competitionKey: ({ structuralKey }) => structuralKey,
},
{
basis: "exact-il-signature",
key: ({ exactKey }) => exactKey,
remap: true,
},
{
basis: "structural-method-shape",
key: ({ structuralKey }) => structuralKey,
competitionKey: ({ structuralKey }) => structuralKey,
remap: true,
},
],
});
@@ -143,11 +172,20 @@ const matchFields = (
matchByKeys({
left,
right,
exactBasis: "field-signature",
fallbackBases: [
rounds: [
{
basis: "field-signature",
key: declaredAs(({ exactKey }) => exactKey),
},
{
basis: "exact-signature",
key: ({ signatureKey }) => signatureKey,
competitionKey: ({ rawSignatureKey }) => rawSignatureKey,
},
{
basis: "field-signature",
key: ({ exactKey }) => exactKey,
remap: true,
},
],
});
@@ -155,21 +193,47 @@ const matchFields = (
export type ManagedMethodMatches = ReturnType<typeof matchMethods>;
export type ManagedFieldMatches = ReturnType<typeof matchFields>;
interface MatchRound<Item> {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
/** Name-free evidence paired with the retained member name for contesting. */
readonly competitionKey?: (item: Keyed<Item>) => string | null;
/**
* The key omits the declared type, so a pair may join different declared
* identities; same-identity pairs were taken by earlier rounds. Contention
* still retains the member name, which unresolved owners keep as evidence.
* A member whose own identity is still unpaired on the other side does not
* take part, and a group with a member of an unresolved type stays ambiguous.
*/
readonly remap?: true;
}
interface MatchByKeysInput<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly exactBasis: ConcreteMatchBasis;
readonly fallbackBases: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[];
readonly rounds: readonly MatchRound<Item>[];
}
const matchByKeys = <Item>({
export const identityOf = ({
declaring_type,
name,
}: {
readonly declaring_type: string | null;
readonly name: string;
}): string => sha256([declaring_type, name]);
/** Narrow a key to members of one declared type and name. */
const declaredAs =
<Item>(key: (item: Keyed<Item>) => string | null) =>
(item: Keyed<Item>): string | null => {
const value = key(item);
return value === null ? null : sha256([item.identity, value]);
};
const matchByKeys = <Item extends Declared>({
left,
right,
exactBasis,
fallbackBases,
rounds,
}: MatchByKeysInput<Item>): {
readonly pairs: readonly MatchedPair<Item>[];
readonly ambiguous: readonly Ambiguous<Item>[];
@@ -178,33 +242,58 @@ const matchByKeys = <Item>({
} => {
const usedLeft = new Set<Keyed<Item>>();
const usedRight = new Set<Keyed<Item>>();
const pairedLeft = new Set<Keyed<Item>>();
const pairedRight = new Set<Keyed<Item>>();
const pairs: MatchedPair<Item>[] = [];
const ambiguous: Ambiguous<Item>[] = [];
const rounds: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[] = [
{ basis: exactBasis, key: ({ exactKey }) => exactKey },
...fallbackBases,
];
for (const round of rounds) {
const competitionKey = round.competitionKey ?? ((item) => item.exactKey);
const unpairedLeft = unpairedOf(left, pairedLeft);
const unpairedRight = unpairedOf(right, pairedRight);
const declarable = ownerlessDeclarable(
unpairedLeft,
unpairedRight,
competitionKey,
);
const openLeft = left.filter((item) => !usedLeft.has(item));
const openRight = right.filter((item) => !usedRight.has(item));
// Only open candidates can justify overriding a held declared identity:
// consumed ambiguous rows remain identity barriers, but cannot join a
// later remap group to establish its ambiguity.
const remapContested =
round.remap === true
? ownerlessContested([openLeft, openRight], competitionKey)
: new Set<string>();
const leftGroups = groupBy(
left.filter((item) => !usedLeft.has(item)),
round.remap === true
? remappable(openLeft, unpairedRight, competitionKey, remapContested)
: openLeft.filter(declarable),
round.key,
);
const rightGroups = groupBy(
right.filter((item) => !usedRight.has(item)),
round.remap === true
? remappable(openRight, unpairedLeft, competitionKey, remapContested)
: openRight.filter(declarable),
round.key,
);
for (const [key, leftItems] of leftGroups) {
const rightItems = rightGroups.get(key);
if (rightItems === undefined) continue;
if (leftItems.length === 1 && rightItems.length === 1) {
// An unresolved owner may be either member's own counterpart, so a
// remap group it joins stays ambiguous.
const refused =
round.remap === true &&
[...leftItems, ...rightItems].some(
({ item }) => item.declaring_type === null,
);
if (!refused && leftItems.length === 1 && rightItems.length === 1) {
const [leftItem] = leftItems;
const [rightItem] = rightItems;
if (leftItem === undefined || rightItem === undefined) continue;
usedLeft.add(leftItem);
usedRight.add(rightItem);
pairedLeft.add(leftItem);
pairedRight.add(rightItem);
pairs.push({
left: leftItem,
right: rightItem,
@@ -227,6 +316,22 @@ const matchByKeys = <Item>({
}
}
}
// Contention can prevent a declared signature pair even when CIL/shape
// evidence cannot form a later remap. Held ambiguities still contest
// ownership; only proven pairs leave that evidence pool. Group only open
// candidates so held members retain their original ambiguity and provenance.
for (const group of unresolvedSignatureAmbiguities(
left.filter((item) => !usedLeft.has(item)),
right.filter((item) => !usedRight.has(item)),
ownerlessContested(
[unpairedOf(left, pairedLeft), unpairedOf(right, pairedRight)],
(member) => member.rawSignatureKey,
),
)) {
for (const item of group.left) usedLeft.add(item);
for (const item of group.right) usedRight.add(item);
ambiguous.push(group);
}
return {
pairs,
ambiguous,
@@ -235,6 +340,132 @@ const matchByKeys = <Item>({
};
};
/** Open signature choices contested by unresolved owners, including held rows. */
const unresolvedSignatureAmbiguities = <Item extends Declared>(
left: readonly Keyed<Item>[],
right: readonly Keyed<Item>[],
contested: ReadonlySet<string>,
): Ambiguous<Item>[] => {
const key = (member: Keyed<Item>): string =>
competitionIdentityKey(member, member.rawSignatureKey) ?? "";
const leftGroups = groupBy(left, key);
const rightGroups = groupBy(right, key);
const groups: Ambiguous<Item>[] = [];
for (const [signature, leftItems] of leftGroups) {
const rightItems = rightGroups.get(signature);
if (!contested.has(signature) || rightItems === undefined) continue;
groups.push({
left: leftItems,
right: rightItems,
basis: "exact-signature",
});
}
return groups;
};
interface Declared {
readonly declaring_type: string | null;
readonly name: string;
}
const unpairedOf = <Item>(
items: readonly Keyed<Item>[],
paired: ReadonlySet<Keyed<Item>>,
): Keyed<Item>[] => items.filter((item) => !paired.has(item));
/**
* Round-specific evidence keys an unresolved owner competes for, paired with
* its retained member name. Another same-name member on the same side can be
* the unresolved row's owner; a different name cannot. Contested candidates
* stay in remap rounds rather than pairing by declared identity.
*/
const competitionIdentityKey = <Item extends Declared>(
member: Keyed<Item>,
evidenceKey: string | null,
): string | null =>
evidenceKey === null ? null : JSON.stringify([member.item.name, evidenceKey]);
const ownerlessContested = <Item extends Declared>(
sides: readonly (readonly Keyed<Item>[])[],
keyOf: (item: Keyed<Item>) => string | null,
): ReadonlySet<string> => {
const contested = new Set<string>();
for (const side of sides) {
const seen = new Map<string, number>();
const ownerless = new Set<string>();
for (const member of side) {
const key = competitionIdentityKey(member, keyOf(member));
if (key === null) continue;
seen.set(key, (seen.get(key) ?? 0) + 1);
if (member.item.declaring_type === null) ownerless.add(key);
}
for (const key of ownerless)
if ((seen.get(key) ?? 0) > 1) contested.add(key);
}
return contested;
};
/**
* Members a remap round may group: an unresolved owner, which keeps its group
* ambiguous; a member whose selected key an unresolved owner competes for, so the
* group that preserved the base matcher's ambiguity can form; or no member of
* the same declared identity left unpaired on the other side, whether
* one-sided or in an ambiguous group. The sets are taken before grouping, so
* no group order decides a remap.
*/
const remappable = <Item extends Declared>(
items: readonly Keyed<Item>[],
others: readonly Keyed<Item>[],
keyOf: (item: Keyed<Item>) => string | null,
contested: ReadonlySet<string>,
): Keyed<Item>[] => {
const kept = new Set(others.map(({ identity }) => identity));
return items.filter((member) => {
const key = keyOf(member);
return (
(key !== null &&
contested.has(competitionIdentityKey(member, key) ?? "")) ||
member.item.declaring_type === null ||
!kept.has(member.identity)
);
});
};
/**
* Whether a member may pair in a declared-identity round. A member with an
* unresolved owner may, only when no other member on either side shares its
* selected evidence key: its owner might be any of them, so a shared key
* leaves it to the remap rounds, which keep such a group ambiguous. The
* resolved members that share such a key stay out too, so they cannot pair and
* consume the candidate the ownerless member might own.
*/
const ownerlessDeclarable = <Item extends Declared>(
left: readonly Keyed<Item>[],
right: readonly Keyed<Item>[],
keyOf: (item: Keyed<Item>) => string | null,
): ((member: Keyed<Item>) => boolean) => {
const count = (side: readonly Keyed<Item>[]) => {
const seen = new Map<string, number>();
for (const member of side) {
const key = keyOf(member);
if (key !== null) seen.set(key, (seen.get(key) ?? 0) + 1);
}
return seen;
};
const leftSeen = count(left);
const rightSeen = count(right);
const contested = ownerlessContested([left, right], keyOf);
return (member) => {
const key = keyOf(member);
return key !== null &&
contested.has(competitionIdentityKey(member, key) ?? "")
? false
: member.item.declaring_type !== null ||
key === null ||
((leftSeen.get(key) ?? 0) <= 1 && (rightSeen.get(key) ?? 0) <= 1);
};
};
const groupBy = <Item>(
items: readonly Item[],
keyOf: (item: Item) => string | null,
@@ -263,7 +494,7 @@ const observedBy =
* the other side's selection stays one-sided, so a type selection never yields
* a remap to a member of a type the other side did not inspect.
*/
const matchObserved = <Item extends { readonly declaring_type: string | null }>(
const matchObserved = <Item extends Declared>(
left: readonly Item[],
right: readonly Item[],
sides: {
@@ -56,7 +56,8 @@ export const projectionCoverage = (
inventory_complete: boolean;
} => ({
status:
hasCompleteInventoryCoverage(inventory) && budgetComplete
hasCompleteInventoryCoverage(inventory, "container-entries") &&
budgetComplete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
+1 -1
View File
@@ -4,7 +4,7 @@ import type { AnalysisPartialObservation } from "./analysisErrorBase.js";
/** Provider resources could not be proven closed after bounded cleanup. */
export class ProviderCleanupError extends ProviderAdapterError {
override readonly cleanupIncomplete = true;
override cleanupIncomplete = true;
override readonly cleanupResources: readonly string[];
override readonly userMessage =
"Provider cleanup could not be fully confirmed. Review the reported local resources before opening another target.";
+18 -2
View File
@@ -2,6 +2,8 @@
export interface RecordedTransportUrl {
readonly origin: string | null;
readonly path: string | null;
/** WHATWG query spelling, present only when explicitly selected for projection. */
readonly query?: string;
readonly credentials:
| { readonly start: number; readonly end: number }
| "ambiguous"
@@ -15,6 +17,7 @@ export interface RecordedTransportUrl {
*/
export const parseRecordedTransportUrl = (
value: string,
options: { readonly includeQuery?: boolean } = {},
): RecordedTransportUrl => {
const prefix = /^[\x00-\x20]*(?:([A-Za-z][A-Za-z0-9+.-]*):)?\/\//u.exec(
value,
@@ -67,9 +70,22 @@ export const parseRecordedTransportUrl = (
(special && value[authorityEnd] === "\\")
)
return { origin, path: null, credentials };
if (value[authorityEnd] !== "/") return { origin, path: "/", credentials };
const query =
options.includeQuery === true ? { query: absolute!.search } : {};
if (value[authorityEnd] !== "/")
return { origin, path: "/", credentials, ...query };
let pathEnd = authorityEnd;
while (pathEnd < value.length && !"?#".includes(value[pathEnd]!))
pathEnd += 1;
return { origin, path: value.slice(authorityEnd, pathEnd), credentials };
return {
origin,
path: value.slice(authorityEnd, pathEnd),
credentials,
...query,
};
};
/** WHATWG form-query name decoding; preserve order, repeats and empty names. */
export const parseUrlQueryParameterNames = (
query: string,
): IterableIterator<string> => new URLSearchParams(query).keys();
+33 -6
View File
@@ -1,24 +1,51 @@
import { z } from "zod";
const diagnostics = z.array(z.string().min(1)).min(1);
const completeCoverage = z.strictObject({ status: z.literal("complete") });
const diagnostics = z.array(z.string().min(1)).min(1).exactOptional();
const completeCoverage = z.strictObject({
status: z.literal("complete"),
diagnostics,
});
const limitedDirections = z.union([
z.tuple([z.literal("callers")]).check(z.minLength(1), z.maxLength(1)),
z.tuple([z.literal("callees")]).check(z.minLength(1), z.maxLength(1)),
z
.tuple([z.literal("callers"), z.literal("callees")])
.check(z.minLength(2), z.maxLength(2)),
]);
const partialCoverage = z.strictObject({
status: z.literal("partial"),
limitations: z.array(z.string().min(1)).min(1),
limited_directions: limitedDirections.exactOptional(),
diagnostics,
});
const unknownCoverage = z.strictObject({
status: z.literal("unknown"),
reason: z.string().min(1),
limited_directions: limitedDirections.exactOptional(),
diagnostics,
});
/** Explicit coverage state for a provider's observed caller/callee set. */
export const relationshipCoverageSchema = z.union([
export const relationshipCoverageSchema = z.discriminatedUnion("status", [
completeCoverage,
completeCoverage.extend({ diagnostics }),
partialCoverage,
partialCoverage.extend({ diagnostics }),
unknownCoverage,
unknownCoverage.extend({ diagnostics }),
]);
export type RelationshipCoverage = z.infer<typeof relationshipCoverageSchema>;
/** Reasons the observed relationship inventory cannot establish completeness. */
export const relationshipCoverageLimitations = (
coverage: RelationshipCoverage | null | undefined,
): readonly string[] => {
switch (coverage?.status) {
case undefined:
return ["Provider did not report relationship coverage."];
case "complete":
return [];
case "partial":
return coverage.limitations;
case "unknown":
return [coverage.reason];
}
};
+40
View File
@@ -0,0 +1,40 @@
import { z } from "zod";
const objdumpArtifactInputSchema = z
.object({
path: z.string().min(1),
operation: z.enum([
"file_headers",
"section_headers",
"symbols",
"relocations",
"dwarf",
"disassemble",
"disassemble_all",
]),
follow_debug_links: z.boolean().default(false),
})
.strict();
/** Caller-selected artifact facet or pathless provider capability query. */
export const objdumpInputSchema = z.discriminatedUnion("operation", [
objdumpArtifactInputSchema,
z.strictObject({ operation: z.literal("architectures") }),
]);
/** Caller-selected Rizin command against one local artifact. */
export const rizinInputSchema = z
.object({
path: z.string().min(1),
command: z
.string()
.min(1)
.refine(
(value) => !/[\r\n\u0000]/u.test(value),
"A single command line is required",
),
})
.strict();
export type ObjdumpInput = z.input<typeof objdumpInputSchema>;
export type RizinInput = z.input<typeof rizinInputSchema>;
+294
View File
@@ -0,0 +1,294 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { localPathStringSchema } from "../localPath.js";
export const RUST_AUDITABLE_FORMAT_VERSION = 1;
const index = z.number().int().nonnegative();
const rustcHash = z.string().regex(/^[0-9a-f]{40}$/u);
/** One embedded package, with omitted kind and root preserved as null and false. */
export const rustPackageSchema = z.strictObject({
name: z.string().min(1),
version: z.string().min(1),
source: z.string().min(1),
kind: z.enum(["runtime", "build"]).nullable(),
dependencies: z.array(index),
root: z.boolean(),
});
const dependencyEdgeSchema = z.strictObject({
from_index: index,
to_index: index,
});
/** zlib JSON from one `.dep-v0` section, in the section's package order. */
export const rustAuditableMetadataSchema = z.strictObject({
section_name: z.enum([".dep-v0", "__DATA,.dep-v0"]),
file_offset: index,
section_bytes: z.number().int().positive(),
compressed_bytes: z.number().int().positive(),
uncompressed_bytes: z.number().int().positive(),
format_version: z.literal(RUST_AUDITABLE_FORMAT_VERSION).nullable(),
packages: z.array(rustPackageSchema),
root_package_index: index.nullable(),
dependency_edges: z.array(dependencyEdgeSchema),
cyclic_dependency_indices: z.array(index),
});
/** Inferred compiler id from read-only `/rustc/<40-hex>/` paths. */
export const rustcCommitSchema = z.strictObject({
evidence_kind: z.literal("inferred"),
hashes: z
.array(
z.strictObject({
hash: rustcHash,
file_offset: index,
}),
)
.min(1),
});
/** One explicit local executable or library, independent of a disassembler target. */
export const inspectRustBinaryInputSchema = z.strictObject({
path: localPathStringSchema.describe(
"Absolute filesystem path to the selected executable or library",
),
});
/** Bounded cargo-auditable observation. A missing section is null, not an empty dependency list. */
export const rustBinarySchema = z
.strictObject({
artifact: z.strictObject({
path: localPathStringSchema,
sha256: digestSchema,
bytes: index,
}),
format: z.enum(["elf", "pe", "macho"]),
architecture: z.string(),
bits: z.union([z.literal(32), z.literal(64)]),
byte_order: z.enum(["little", "big"]),
auditable_metadata: rustAuditableMetadataSchema.nullable(),
rustc_commit: rustcCommitSchema.nullable(),
limitations: z.array(z.string()),
})
.superRefine((report, context) => {
const metadata = report.auditable_metadata;
if (metadata !== null) {
checkSection(report.artifact.bytes, metadata, context);
checkPackages(metadata, context);
}
checkRustc(report.artifact.bytes, report.rustc_commit, context);
});
export type RustPackage = z.infer<typeof rustPackageSchema>;
export type RustAuditableMetadata = z.infer<typeof rustAuditableMetadataSchema>;
export type RustBinary = z.infer<typeof rustBinarySchema>;
export type InspectRustBinaryInput = z.infer<
typeof inspectRustBinaryInputSchema
>;
const issue = (
context: z.RefinementCtx,
path: (string | number)[],
message: string,
): void => {
context.addIssue({ code: "custom", path, message });
};
const inside = (fileBytes: number, offset: number, size: number): boolean =>
offset <= fileBytes && size <= fileBytes - offset;
const checkSection = (
fileBytes: number,
metadata: RustAuditableMetadata,
context: z.RefinementCtx,
): void => {
if (
!inside(fileBytes, metadata.file_offset, metadata.section_bytes) ||
metadata.compressed_bytes !== metadata.section_bytes
)
issue(
context,
["auditable_metadata", "file_offset"],
"Dependency section range is outside the selected artifact or disagrees with its compressed size.",
);
};
const checkPackages = (
metadata: RustAuditableMetadata,
context: z.RefinementCtx,
): void => {
const roots: number[] = [];
const edgesByPackage = new Map<
number,
z.infer<typeof dependencyEdgeSchema>[]
>();
for (const [position, edge] of metadata.dependency_edges.entries()) {
if (
edge.from_index >= metadata.packages.length ||
edge.to_index >= metadata.packages.length
) {
issue(
context,
["auditable_metadata", "dependency_edges", position],
"Dependency edge index is outside the package list.",
);
continue;
}
const grouped = edgesByPackage.get(edge.from_index);
if (grouped === undefined) edgesByPackage.set(edge.from_index, [edge]);
else grouped.push(edge);
}
for (const [packageIndex, pkg] of metadata.packages.entries()) {
if (pkg.root) roots.push(packageIndex);
const edges = edgesByPackage.get(packageIndex) ?? [];
if (
edges.length !== pkg.dependencies.length ||
edges.some((edge, index) => edge.to_index !== pkg.dependencies[index])
)
issue(
context,
["auditable_metadata", "dependency_edges"],
"Dependency edges do not match package dependency indices.",
);
if (pkg.dependencies.some((target) => target >= metadata.packages.length))
issue(
context,
["auditable_metadata", "packages", packageIndex, "dependencies"],
"Dependency index is outside the package list.",
);
}
const root = metadata.root_package_index;
if (
root === null ? roots.length !== 0 : roots.length !== 1 || roots[0] !== root
)
issue(
context,
["auditable_metadata", "root_package_index"],
"Root package index does not match packages marked root.",
);
const cycles = cyclicDependencyIndices(metadata.packages);
if (
cycles.length !== metadata.cyclic_dependency_indices.length ||
cycles.some(
(index, position) =>
metadata.cyclic_dependency_indices[position] !== index,
)
)
issue(
context,
["auditable_metadata", "cyclic_dependency_indices"],
"Cyclic dependency indices do not match the cycles in package dependencies.",
);
};
/** Package indices that participate in a dependency cycle, in ascending order. */
export const cyclicDependencyIndices = (
packages: readonly { readonly dependencies: readonly number[] }[],
): number[] => {
const edges = packages.map((pkg) => pkg.dependencies);
const order = dependencyPostorder(edges);
const reversed = reversedDependencyEdges(edges);
const seen = new Uint8Array(edges.length);
const cyclic = new Set<number>();
for (let cursor = order.length - 1; cursor >= 0; cursor -= 1) {
const start = order[cursor];
if (start === undefined || seen[start] === 1) continue;
const component = dependencyComponent(start, reversed, seen);
if (dependencyComponentInCycle(component, edges))
for (const index of component) cyclic.add(index);
}
return [...cyclic].sort((left, right) => left - right);
};
interface DependencyWalkFrame {
readonly index: number;
edge: number;
}
const dependencyPostorder = (
edges: readonly (readonly number[])[],
): number[] => {
const seen = new Uint8Array(edges.length);
const order: number[] = [];
for (let start = 0; start < edges.length; start += 1) {
if (seen[start] === 1) continue;
const stack: DependencyWalkFrame[] = [{ index: start, edge: 0 }];
seen[start] = 1;
while (stack.length > 0) {
const frame = stack[stack.length - 1];
if (frame === undefined) break;
const next = edges[frame.index]?.[frame.edge];
if (next === undefined) {
stack.pop();
order.push(frame.index);
continue;
}
frame.edge += 1;
if (seen[next] === 0) {
seen[next] = 1;
stack.push({ index: next, edge: 0 });
}
}
}
return order;
};
const reversedDependencyEdges = (
edges: readonly (readonly number[])[],
): number[][] => {
const reversed = Array.from({ length: edges.length }, () => [] as number[]);
for (let from = 0; from < edges.length; from += 1)
for (const to of edges[from] ?? []) reversed[to]?.push(from);
return reversed;
};
const dependencyComponent = (
start: number,
reversed: readonly (readonly number[])[],
seen: Uint8Array,
): number[] => {
const component: number[] = [];
const stack = [start];
seen[start] = 1;
while (stack.length > 0) {
const index = stack.pop();
if (index === undefined) break;
component.push(index);
for (const next of reversed[index] ?? []) {
if (seen[next] === 0) {
seen[next] = 1;
stack.push(next);
}
}
}
return component;
};
const dependencyComponentInCycle = (
component: readonly number[],
edges: readonly (readonly number[])[],
): boolean => {
if (component.length > 1) return true;
const only = component[0];
return only !== undefined && (edges[only]?.includes(only) ?? false);
};
const checkRustc = (
fileBytes: number,
commit: RustBinary["rustc_commit"],
context: z.RefinementCtx,
): void => {
if (commit === null) return;
const seen = new Set<string>();
for (const [position, entry] of commit.hashes.entries()) {
if (seen.has(entry.hash) || !inside(fileBytes, entry.file_offset, 48))
issue(
context,
["rustc_commit", "hashes", position],
"rustc path hash is duplicated or its file offset is outside the artifact.",
);
seen.add(entry.hash);
}
};
+22
View File
@@ -662,6 +662,28 @@ describe("web metadata key semantics", () => {
});
});
it("reads expression-free template dynamic imports as chunk edges", () => {
const result = analyzeCapturedWebBundle(
inspection(`
import(\`./lazy.js\`);
import("./quoted.js");
import(\`./\${name}.js\`);
`),
);
expect(result.observations.chunks.edges).toEqual([
expect.objectContaining({
kind: "dynamic_import",
specifier: "./lazy.js",
resolved_url: `${origin}/assets/lazy.js`,
}),
expect.objectContaining({
kind: "dynamic_import",
specifier: "./quoted.js",
}),
]);
});
it("does not infer call names from dynamic computed identifiers", () => {
const result = analyzeCapturedWebBundle(
inspection(`
+11 -8
View File
@@ -123,14 +123,17 @@ const inspectNode = (
node,
accumulator,
});
else if (t.isImportExpression(node) && t.isStringLiteral(node.source))
addEdge({
script,
specifier: node.source.value,
kind: "dynamic_import",
node,
accumulator,
});
else if (t.isImportExpression(node)) {
const specifier = stringValue(node.source);
if (specifier !== undefined)
addEdge({
script,
specifier,
kind: "dynamic_import",
node,
accumulator,
});
}
if (t.isObjectProperty(node)) inspectRouteProperty(script, node, accumulator);
if (
t.isCallExpression(node) ||
+10 -6
View File
@@ -70,9 +70,11 @@ const compareDimension = (
after: ReadonlyMap<string, string>,
complete: boolean,
reason: string,
inventoryComplete = complete,
): Dimension => {
// Membership evidence can be complete even when selected content is unknown.
const all = compareIdentities(before, after).filter(
({ change }) => complete || change === "modified",
({ change }) => inventoryComplete || change === "modified",
);
if (all.length > 0)
return {
@@ -160,6 +162,7 @@ const storageDimension = (
),
storageComparable(before, after, keysComplete, usageComplete),
"Storage fingerprints, inventories, usage, or quota were unavailable or truncated in at least one observation.",
keysComplete,
);
};
@@ -683,16 +686,17 @@ const storageMap = (
}),
],
]);
if (!includeKeys) return map;
const add = (kind: string, keys: readonly string[]) => {
for (const key of keys) {
map.set(`storage:${kind}:${key}`, digestCanonicalValue(key));
}
};
add("local_storage", storage.local_storage_keys);
add("session_storage", storage.session_storage_keys);
add("indexed_db", storage.indexed_db_names);
add("cache", storage.cache_names);
if (includeKeys) {
add("local_storage", storage.local_storage_keys);
add("session_storage", storage.session_storage_keys);
add("indexed_db", storage.indexed_db_names);
add("cache", storage.cache_names);
}
for (const fingerprint of storage.content_fingerprints) {
const identity = `${fingerprint.scope}:${fingerprint.identity_sha256}`;
if (!fingerprintIdentities.has(identity)) continue;
+1 -1
View File
@@ -4,7 +4,7 @@ import type { AnalysisErrorOptions } from "./analysisErrorBase.js";
/** Publication failure retaining its input/output target and cleanup state. */
export class WebScriptExportError extends ArtifactOperationError {
override readonly userMessage: string;
override readonly cleanupIncomplete: boolean;
override cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
constructor(
+9 -3
View File
@@ -52,6 +52,12 @@ export const zipPackageFormatForPath = (
return undefined;
};
/** Inventory cannot see bytes that are not central-directory entries. */
export const ZIP_NON_ENTRY_TAIL_LIMITATION =
"ZIP inventory lists central-directory entries only. Bytes after the central directory, including an APK Signing Block or a ZIP comment, are not occurrences.";
/** Inventory lists entries, not all bytes surrounding the central directory. */
export const ZIP_NON_ENTRY_LIMITATION =
"ZIP inventory lists central-directory entries only. Non-entry bytes, including an APK Signing Block before the central directory or a ZIP comment after it, are not occurrences.";
/** Recognize the same inventory scope in current and previously retained Evidence. */
export const isZipInventoryScopeLimitation = (limitation: string): boolean =>
limitation === ZIP_NON_ENTRY_LIMITATION ||
limitation ===
"ZIP inventory lists central-directory entries only. Bytes after the central directory, including an APK Signing Block or a ZIP comment, are not occurrences.";