fix!: repair boundary contracts across CLI and MCP (#597)

* fix(comparisons)!: preserve unknowns across partial observations

Share absence and digest semantics, keep unobserved managed bodies unknown, and match unique managed type/name/signatures before structural fallback.

BREAKING CHANGE: Managed comparison metadata adds exact-signature matching and its count, and name_matching now reports exact-signature-fallback.

* fix(javascript): preserve projected result binding semantics

Share syntax-aware property reads and assigned-result resolution. Retain destructuring paths and downgrade downstream whole-result relationships instead of resolving nested or wrapped calls as aliases.

* fix(native)!: admit complete parser values and preserve typed failures

Decode Mach headers by named columns, validate complete slice keys and lipo alignment, and preserve codesign runtime flags and tagged parser errors. Rename the Ghidra test dossier fixture and connect fake-backed suites to real verification lanes.

BREAKING CHANGE: Native load-command results no longer contain the unused, always-null file_offset field.

* fix(process): preserve host identity and actionable boundary failures

Thread selected platform and environment through process and Doctor seams, stamp observed producer identity in Evidence, and retain PTY, filesystem, lease and lazy-provider failure causes. Drain cancelled lazy loads and omit exited descendants from verified lineage.

* fix(browser): preserve cleanup and document-transition evidence

Make V8 and Playwright teardown cancellation-aware, expose primary failures alongside incomplete cleanup, share frame-tree and navigation rules, and clear stale WebMCP registrations without pruning unrelated child frames.

* fix(adapters): align managed targets and typed CLI outcomes

Inspect managed PE/CLI targets independently of native provider selection, reuse successful managed selections, and keep evidence bound to the actual inspected target. Classify canonical CLI error envelopes and exhaustive setup/update/uninstall outcomes, audit registered CLI coverage, and assert platform-specific runtime results.

* docs: refresh boundary contracts and shipped roadmap behavior
This commit is contained in:
morluto
2026-10-06 00:50:38 +08:00
committed by GitHub
parent f3e6582e9e
commit 9c25dc4ed2
134 changed files with 3547 additions and 812 deletions
@@ -5,6 +5,7 @@ import {
AnalysisInputError,
ArtifactOperationError,
BinaryTargetError,
BrowserObservationError,
HopperProcessError,
HopperRemoteError,
HopperStartError,
@@ -15,6 +16,35 @@ import {
} from "./errors.js";
describe("analysis error projection: provider failures", () => {
it("projects the primary browser failure alongside incomplete cleanup", () => {
const projected = projectAnalysisError(
new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{
cause: new AggregateError([
new BrowserObservationError(
"observe_javascript_runtime",
"target_changed",
),
new Error("socket close failed"),
]),
},
),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
operation: "observe_javascript_runtime",
reason: "cleanup_failed",
cleanup: "incomplete",
resources: ["browser_transport"],
primary_reason: "target_changed",
},
});
});
it("reports a timed-out active Hopper request and actionable retry guidance", () => {
const projected = projectAnalysisError(
new HopperTimeoutError(30_000, "trace_feature", 42, "busy"),
+31 -2
View File
@@ -249,8 +249,22 @@ const providerErrorDetails = (
? {}
: { diagnostics: error.diagnostics }),
};
if (error instanceof BrowserObservationError)
return { operation: error.operation, reason: error.reason };
if (error instanceof BrowserObservationError) {
const primaryReason = primaryBrowserFailureReason(error);
return {
operation: error.operation,
reason: error.reason,
...(error.cleanupIncomplete
? {
cleanup: "incomplete",
resources: [...error.cleanupResources],
...(primaryReason === undefined
? {}
: { primary_reason: primaryReason }),
}
: {}),
};
}
if (error instanceof HopperRemoteError)
return {
stage: "analysis",
@@ -275,6 +289,21 @@ const providerErrorDetails = (
return undefined;
};
const primaryBrowserFailureReason = (
error: BrowserObservationError,
): string | undefined => {
if (!(error.cause instanceof AggregateError)) return undefined;
const primary = error.cause.errors[0];
if (primary instanceof BrowserObservationError) return primary.reason;
if (primary instanceof AnalysisCancelledError) return "cancelled";
if (primary instanceof AnalysisTimeoutError) return "timeout";
if (typeof primary === "object" && primary !== null && "_tag" in primary)
return typeof primary._tag === "string"
? primary._tag
: "execution_failure";
return "execution_failure";
};
const lifecycleErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
+12 -2
View File
@@ -90,7 +90,17 @@ describe("compiled Apple asset catalog projection", () => {
);
expect(() =>
parseAppleAssetCatalogRecords({ Name: "not an array" }),
).toThrow(/JSON array/u);
expect(() => parseAppleAssetCatalogRecords([null])).toThrow(/record 0/u);
).toThrow(
expect.objectContaining({
_tag: "AnalysisOutputError",
reason: "assetutil output must be a JSON array",
}),
);
expect(() => parseAppleAssetCatalogRecords([null])).toThrow(
expect.objectContaining({
_tag: "AnalysisOutputError",
reason: "assetutil record 0 is not a JSON object",
}),
);
});
});
+10 -2
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { AnalysisOutputError } from "./errors.js";
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
@@ -64,11 +65,18 @@ export const parseAppleAssetCatalogRecords = (
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[] => {
if (!Array.isArray(value))
throw new Error("assetutil output must be a JSON array");
throw new AnalysisOutputError(
"inspect_asset_catalog",
"assetutil output must be a JSON array",
);
return value.map((record, index) => {
const parsed = z.record(z.string(), jsonValueSchema).safeParse(record);
if (!parsed.success)
throw new Error(`assetutil record ${index} is not a JSON object`);
throw new AnalysisOutputError(
"inspect_asset_catalog",
`assetutil record ${index} is not a JSON object`,
{ cause: parsed.error },
);
return parsed.data;
});
};
+1 -10
View File
@@ -1,4 +1,3 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import {
@@ -12,6 +11,7 @@ import {
type InventorySet,
} from "./artifactInventoryEvidence.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJson } from "./comparisonSemantics.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const comparisonStatusSchema = z.enum([
@@ -325,15 +325,6 @@ const metadataChanged = (
JSON.stringify(input.leftOccurrence?.limitations) !==
JSON.stringify(input.rightOccurrence?.limitations);
const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"Artifact comparison could not canonicalize graph data",
);
return encoded;
};
const nodeFor = (
occurrence: ArtifactOccurrence | undefined,
nodes: ReadonlyMap<string, ArtifactNode>,
+20 -11
View File
@@ -54,7 +54,7 @@ describe("bundle comparison", () => {
expect(result.left_bundle_sha256).toBe(result.right_bundle_sha256);
});
it("classifies explicit pairs and returns every membership change inline", () => {
it("classifies explicit pairs and leaves one-sided membership unresolved", () => {
const oldRecord = evidence("old");
const newRecord = evidence("new");
const removed = evidence("removed");
@@ -71,19 +71,24 @@ describe("bundle comparison", () => {
const repeated = compareBundles(left, right, pairs);
expect(first).toEqual(repeated);
expect(first).toMatchObject({
status: "changed",
status: "unknown",
summary: {
records_added: 1,
records_removed: 1,
records_added: 0,
records_removed: 0,
records_changed: 1,
unresolved: 2,
},
changes: expect.arrayContaining([
expect.objectContaining({ classification: "changed" }),
expect.objectContaining({
classification: "unknown",
conclusion_kind: "unresolved_branch",
}),
]),
});
expect(first.changes).toHaveLength(3);
expect(first.limitations).toContain(
"One-sided membership proves only bundle inclusion or omission, not behavioral absence.",
"EvidenceBundle has no inventory completeness marker; one-sided membership remains unknown.",
);
});
@@ -176,12 +181,12 @@ describe("bundle comparison history", () => {
[initial, advanced],
);
expect(compareBundles(initialBundle, advancedBundle)).toMatchObject({
status: "changed",
summary: { unknowns_advanced: 1, unresolved: 0 },
status: "unknown",
summary: { unknowns_advanced: 1, unresolved: 1 },
changes: [
expect.objectContaining({
entity: "evidence",
classification: "added",
classification: "unknown",
}),
expect.objectContaining({
entity: "residual_unknown",
@@ -193,14 +198,18 @@ describe("bundle comparison history", () => {
const missing = compareBundles(initialBundle, absent);
expect(missing).toMatchObject({
status: "unknown",
summary: { unknowns_removed: 1, unresolved: 1 },
summary: {
unknowns_added: 0,
unknowns_removed: 0,
unresolved: 2,
},
});
expect(missing.changes).toContainEqual(
expect.objectContaining({
classification: "removed",
classification: "unknown",
conclusion_kind: "unresolved_branch",
limitations: [
"A missing unknown history does not establish resolution.",
"EvidenceBundle has no inventory completeness marker; one-sided history membership remains unknown.",
],
}),
);
+13 -20
View File
@@ -115,7 +115,7 @@ export const compareBundles = (
changes,
limitations: changes.some(({ limitations }) => limitations.length > 0)
? [
"One-sided membership proves only bundle inclusion or omission, not behavioral absence.",
"EvidenceBundle has no inventory completeness marker; one-sided membership remains unknown.",
]
: [],
});
@@ -171,30 +171,30 @@ const compareRecords = (
const added = [...rightIds].filter(
(id) => !leftIds.has(id) && !pairedRight.has(id),
);
for (const [classification, ids, side] of [
["removed", removed, "left"],
["added", added, "right"],
for (const [ids, side] of [
[removed, "left"],
[added, "right"],
] as const)
for (const id of ids)
changes.push({
entity: "evidence",
key: id,
classification,
conclusion_kind: "observed_change",
classification: "unknown",
conclusion_kind: "unresolved_branch",
left_evidence_ids: side === "left" ? [id] : [],
right_evidence_ids: side === "right" ? [id] : [],
left_digest: side === "left" ? id.slice(3) : null,
right_digest: side === "right" ? id.slice(3) : null,
limitations: [
"One-sided membership does not establish behavioral absence.",
"EvidenceBundle has no inventory completeness marker; one-sided membership may reflect incomplete capture.",
],
});
return {
changes,
summary: {
records_unchanged: common.length + pairs.length - changed,
records_added: added.length,
records_removed: removed.length,
records_added: 0,
records_removed: 0,
records_changed: changed,
},
};
@@ -216,16 +216,7 @@ const compareUnknowns = (left: EvidenceBundle, right: EvidenceBundle) => {
const leftHistory = leftHistories.get(id);
const rightHistory = rightHistories.get(id);
if (leftHistory === undefined || rightHistory === undefined) {
const added = leftHistory === undefined;
summary[added ? "unknowns_added" : "unknowns_removed"] += 1;
changes.push(
unknownChange(
id,
added ? "added" : "removed",
leftHistory,
rightHistory,
),
);
changes.push(unknownChange(id, "unknown", leftHistory, rightHistory));
continue;
}
const leftDigests = leftHistory.map(
@@ -275,7 +266,9 @@ const unknownChange = (
right_digest: right?.at(-1)?.revision_digest ?? null,
limitations:
left === undefined || right === undefined
? ["A missing unknown history does not establish resolution."]
? [
"EvidenceBundle has no inventory completeness marker; one-sided history membership remains unknown.",
]
: [],
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import { absenceClaimable, canonicalDigest } from "./comparisonSemantics.js";
describe("shared comparison semantics", () => {
it("permits absence claims only for complete, non-truncated inventories", () => {
expect(
absenceClaimable({
status: "complete",
truncated: false,
omitted_count: 0,
}),
).toBe(true);
expect(
absenceClaimable({
status: "complete",
truncated: true,
omitted_count: 2,
}),
).toBe(false);
expect(
absenceClaimable({
status: "complete",
truncated: false,
omitted_count: 1,
}),
).toBe(false);
expect(absenceClaimable({ status: "partial" })).toBe(false);
});
it("produces one stable SHA-256 for equivalent canonical JSON values", () => {
expect(canonicalDigest({ b: 2, a: 1 })).toBe(
canonicalDigest({ a: 1, b: 2 }),
);
});
});
+34
View File
@@ -0,0 +1,34 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
/** Whether an inventory can support a claim that an item is absent. */
export const absenceClaimable = (coverage: {
readonly status: string;
readonly truncated?: boolean;
readonly omitted_count?: number | null;
}): boolean =>
coverage.status === "complete" &&
coverage.truncated !== true &&
(coverage.omitted_count === undefined || coverage.omitted_count === 0);
/** SHA-256 of canonical JSON for stable, provider-neutral comparison IDs. */
export const canonicalDigest = (
value: unknown,
context = "Comparison",
): string => {
return createHash("sha256")
.update(canonicalJson(value, context))
.digest("hex");
};
/** Canonical JSON used for deterministic tie breaking and stable digests. */
export const canonicalJson = (
value: unknown,
context = "Comparison",
): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(`${context} could not canonicalize data`);
return encoded;
};
+10
View File
@@ -248,6 +248,9 @@ export class ProviderAdapterError extends AnalysisError {
/** A bounded passive browser observation failed at its CDP boundary. */
export class BrowserObservationError extends AnalysisError {
readonly _tag = "BrowserObservationError";
override readonly cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
override readonly userCategory: "cancelled" | undefined;
constructor(
readonly operation: BrowserObservationOperation,
@@ -255,6 +258,13 @@ export class BrowserObservationError extends AnalysisError {
options?: ErrorOptions,
) {
super(`Browser observation ${operation} failed: ${reason}`, options);
this.cleanupIncomplete = reason === "cleanup_failed";
this.cleanupResources =
reason === "cleanup_failed" ? ["browser_transport"] : [];
this.userCategory =
reason === "cancelled" || options?.cause instanceof AnalysisCancelledError
? "cancelled"
: undefined;
}
}
+6 -9
View File
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import {
canonicalDigest,
canonicalJson as encodeCanonicalJson,
} from "./comparisonSemantics.js";
import type {
DimensionName,
FunctionComparisonResult,
@@ -94,11 +94,8 @@ export const summarize = (dimensions: readonly FunctionDimension[]) => ({
});
export const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Function comparison could not canonicalize data");
return encoded;
return encodeCanonicalJson(value, "Function comparison");
};
const digest = (value: unknown): string =>
createHash("sha256").update(canonicalJson(value)).digest("hex");
canonicalDigest(value, "Function comparison");
+20 -21
View File
@@ -1,7 +1,8 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import {
absenceClaimable,
canonicalDigest,
canonicalJson,
} from "./comparisonSemantics.js";
import type { Evidence } from "./evidence.js";
import {
compareCodePoints,
@@ -165,7 +166,7 @@ const leftOnlyItem = (
dimensions: ["availability"],
limitations: [AMBIGUOUS_MATCH_LIMITATION],
});
const absenceObserved = context.rightGraph.coverage.status === "complete";
const absenceObserved = absenceClaimable(context.rightGraph.coverage);
return itemWithId({
...common,
status: absenceObserved ? "removed" : "unknown",
@@ -205,7 +206,7 @@ const rightOnlyItem = (
dimensions: ["availability"],
limitations: [AMBIGUOUS_MATCH_LIMITATION],
});
const absenceObserved = context.leftGraph.coverage.status === "complete";
const absenceObserved = absenceClaimable(context.leftGraph.coverage);
return itemWithId({
...common,
status: absenceObserved ? "added" : "unknown",
@@ -289,9 +290,14 @@ const changedDimensions = (
leftContent !== rightContent
)
dimensions.push("content");
if (canonical(locations(pair.left)) !== canonical(locations(pair.right)))
if (
canonicalJson(locations(pair.left)) !== canonicalJson(locations(pair.right))
)
dimensions.push("location");
if (canonical(properties(pair.left)) !== canonical(properties(pair.right)))
if (
canonicalJson(properties(pair.left)) !==
canonicalJson(properties(pair.right))
)
dimensions.push("properties");
if (
relationshipSignature(pair.left, "left", context) !==
@@ -320,14 +326,14 @@ const locations = (node: ApplicationNode) =>
evidence.location.available ? evidence.location.value : evidence.location,
)
.sort((left, right) =>
compareCodePoints(canonical(left), canonical(right)),
compareCodePoints(canonicalJson(left), canonicalJson(right)),
);
const properties = (node: ApplicationNode) =>
node.observations
.map(({ label, properties: values }) => ({ label, properties: values }))
.sort((left, right) =>
compareCodePoints(canonical(left), canonical(right)),
compareCodePoints(canonicalJson(left), canonicalJson(right)),
);
const relationshipSignature = (
@@ -361,7 +367,7 @@ const relationshipSignature = (
];
return [];
});
return canonical(signatures.sort(compareCodePoints));
return canonicalJson(signatures.sort(compareCodePoints));
};
interface EdgeSignatureContext {
@@ -450,15 +456,8 @@ const stringProperty = (node: ApplicationNode, key: string): string | null => {
};
const graphsComplete = (context: ItemContext): boolean =>
context.leftGraph.coverage.status === "complete" &&
context.rightGraph.coverage.status === "complete";
const canonical = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Application version item could not canonicalize data");
return encoded;
};
absenceClaimable(context.leftGraph.coverage) &&
absenceClaimable(context.rightGraph.coverage);
const digestCanonical = (value: unknown): string =>
createHash("sha256").update(canonical(value)).digest("hex");
canonicalDigest(value, "Application version item");
+9
View File
@@ -7,3 +7,12 @@ export const propertyName = (node: t.Node): string => {
return String(node.value);
return "";
};
/** Read a property name only when its syntax commits to one exact key. */
export const semanticStaticPropertyName = (
property: t.Node,
computed: boolean,
): string =>
computed && !t.isStringLiteral(property) && !t.isNumericLiteral(property)
? ""
: propertyName(property);
+56 -36
View File
@@ -20,6 +20,9 @@ import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
dataEffectLiteralString,
dataEffectMemberCallee,
assignedSemanticResultBindings,
scalarAssignedResultBinding,
semanticProjectedBindingFacts,
} from "./javascriptSemanticDataEffectHelpers.js";
const EVENT_REGISTER_METHODS = [
@@ -61,14 +64,19 @@ interface TimerCandidate {
readonly kind: JavaScriptSemanticTimerOperation["kind"];
readonly ownerCallableId: string | null;
readonly handleBindingId: string | null;
readonly projectedResultBindings: readonly {
readonly bindingId: string;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}[];
}
interface TimerCollectionInput {
readonly node: t.CallExpression | t.OptionalCallExpression;
readonly parent: t.Node | null;
readonly ownerCallableId: string | null;
readonly state: JavaScriptSemanticAnalysisState;
readonly output: TimerCandidate[];
readonly ancestors: readonly t.Node[];
}
/** Recover explicit EventEmitter and Node timer candidates from inert syntax. */
@@ -81,19 +89,28 @@ export const collectJavaScriptSemanticAsyncEffects = (
const timers: TimerCandidate[] = [];
const callableIds = new Set(callables.map(({ callableId }) => callableId));
const callableStack: string[] = [];
const ancestors: t.Node[] = [];
traverseJavaScriptAst(program, {
enter: (node, parent) => {
enter: (node) => {
const callableId = semanticCallableIdForNode(node);
if (callableId !== null && callableIds.has(callableId))
callableStack.push(callableId);
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return;
const ownerCallableId = callableStack.at(-1) ?? null;
collectEvent(node, ownerCallableId, state, events);
collectTimer({ node, parent, ownerCallableId, state, output: timers });
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
const ownerCallableId = callableStack.at(-1) ?? null;
collectEvent(node, ownerCallableId, state, events);
collectTimer({
node,
ownerCallableId,
state,
output: timers,
ancestors,
});
}
ancestors.push(node);
},
exit: (node) => {
const callableId = semanticCallableIdForNode(node);
ancestors.pop();
if (callableId !== null && callableStack.at(-1) === callableId)
callableStack.pop();
},
@@ -187,12 +204,17 @@ const emitterIdentity = (
};
const collectTimer = (input: TimerCollectionInput): void => {
const { node, parent, ownerCallableId, state, output } = input;
const { node, ownerCallableId, state, output, ancestors } = input;
const method = timerMethod(node.callee, state);
if (method === null) return;
const kind = TIMER_SCHEDULE_METHODS.some((candidate) => candidate === method)
? "schedule"
: "cancel";
const projectedResultBindings = assignedSemanticResultBindings(
node,
ancestors,
state,
);
output.push({
node,
method,
@@ -200,8 +222,16 @@ const collectTimer = (input: TimerCollectionInput): void => {
ownerCallableId,
handleBindingId:
kind === "schedule"
? assignedBindingId(parent, node, state)
? scalarAssignedResultBinding(projectedResultBindings)
: bindingId(node.arguments[0], state),
projectedResultBindings:
kind === "schedule"
? semanticProjectedBindingFacts(
projectedResultBindings.filter(
({ projectionPath }) => projectionPath.length > 0,
),
)
: [],
});
};
@@ -210,11 +240,18 @@ const resolveTimers = (
): JavaScriptSemanticTimerOperation[] => {
const schedulesByBinding = new Map<string, TimerCandidate[]>();
for (const candidate of candidates) {
if (candidate.kind !== "schedule" || candidate.handleBindingId === null)
continue;
const existing = schedulesByBinding.get(candidate.handleBindingId) ?? [];
existing.push(candidate);
schedulesByBinding.set(candidate.handleBindingId, existing);
if (candidate.kind !== "schedule") continue;
const ids = [
...(candidate.handleBindingId === null
? []
: [candidate.handleBindingId]),
...candidate.projectedResultBindings.map(({ bindingId }) => bindingId),
];
for (const id of ids) {
const existing = schedulesByBinding.get(id) ?? [];
existing.push(candidate);
schedulesByBinding.set(id, existing);
}
}
return candidates.map((candidate) => {
const linked =
@@ -228,6 +265,7 @@ const resolveTimers = (
location: range(candidate.node),
ownerCallableId: candidate.ownerCallableId,
handleBindingId: candidate.handleBindingId,
projectedResultBindings: candidate.projectedResultBindings,
linkedTimerId:
linked.length === 1 && linked[0] !== undefined
? timerId(linked[0])
@@ -236,7 +274,10 @@ const resolveTimers = (
resolution:
candidate.kind === "schedule"
? "complete"
: linked.length === 1
: linked.length === 1 &&
!linked[0]?.projectedResultBindings.some(
({ bindingId }) => bindingId === candidate.handleBindingId,
)
? "complete"
: linked.length > 1
? "partial"
@@ -303,27 +344,6 @@ const timerNamespaceBinding = (
const timerModule = (specifier: string): boolean =>
specifier === "timers" || specifier === "node:timers";
const assignedBindingId = (
parent: t.Node | null,
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | null => {
const identifier =
t.isVariableDeclarator(parent) &&
parent.init === node &&
t.isIdentifier(parent.id)
? parent.id
: t.isAssignmentExpression(parent) &&
parent.right === node &&
t.isIdentifier(parent.left)
? parent.left
: null;
return identifier === null
? null
: (resolveSemanticBindingState(state, identifier, identifier.name)
?.bindingId ?? null);
};
const bindingId = (
node:
| t.Expression
+29 -31
View File
@@ -27,6 +27,7 @@ import {
} from "./javascriptSemanticCallResolution.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import { assignedSemanticResultBindings } from "./javascriptSemanticDataEffectHelpers.js";
/** Local call, flow, capture, and unsupported-frontier facts. */
export interface JavaScriptSemanticCallAnalysis {
@@ -56,6 +57,7 @@ interface CallCollectionContext {
string,
readonly JavaScriptSemanticBindingState[]
>;
readonly ancestors: t.Node[];
}
/** Recover direct-call and lexical-capture candidates from inert syntax. */
@@ -81,6 +83,7 @@ export const collectJavaScriptSemanticCalls = (
output,
bindingResolutionCache: new Map(),
parameterBindingCache: new Map(),
ancestors: [],
};
const callableStack: JavaScriptSemanticCallable[] = [];
traverseJavaScriptAst(program, {
@@ -99,8 +102,10 @@ export const collectJavaScriptSemanticCalls = (
t.isNewExpression(node)
)
collectCallSite(node, parent, owner, context);
context.ancestors.push(node);
},
exit: (node) => {
context.ancestors.pop();
const callableId = semanticCallableIdForNode(node);
if (
callableId !== null &&
@@ -151,7 +156,7 @@ const collectCallSite = (
arguments: argumentsValue,
};
output.callSites.push(site);
collectCallResultFlow(site, node, parent, context);
collectCallResultFlow(site, node, context);
if (site.resolution !== "exact")
addFrontier(
{
@@ -171,39 +176,32 @@ const collectCallSite = (
const collectCallResultFlow = (
site: JavaScriptSemanticCallSite,
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
parent: t.Node | null,
context: CallCollectionContext,
): void => {
const identifier =
t.isVariableDeclarator(parent) &&
parent.init === node &&
t.isIdentifier(parent.id)
? parent.id
: t.isAssignmentExpression(parent) &&
parent.right === node &&
t.isIdentifier(parent.left)
? parent.left
: null;
if (identifier === null) return;
const binding = resolveSemanticBindingState(
for (const assigned of assignedSemanticResultBindings(
node,
context.ancestors,
context.state,
identifier,
identifier.name,
);
const identifierRange = range(identifier);
const definition = binding?.definitions.find(
({ location }) =>
location.start.line === identifierRange.start.line &&
location.start.column === identifierRange.start.column &&
location.end.line === identifierRange.end.line &&
location.end.column === identifierRange.end.column,
);
if (binding === undefined || definition === undefined) return;
context.output.callResultFlows.push({
callSiteId: site.callSiteId,
bindingId: binding.bindingId,
definitionLocation: definition.location,
});
).filter(({ projectionPath }) => projectionPath.length === 0)) {
const binding = [...context.state.bindingsById.values()].find(
({ bindingId }) => bindingId === assigned.bindingId,
);
if (binding === undefined) continue;
const identifierRange = range(assigned.identifier);
const definition = binding.definitions.find(
({ location }) =>
location.start.line === identifierRange.start.line &&
location.start.column === identifierRange.start.column &&
location.end.line === identifierRange.end.line &&
location.end.column === identifierRange.end.column,
);
if (definition === undefined) continue;
context.output.callResultFlows.push({
callSiteId: site.callSiteId,
bindingId: binding.bindingId,
definitionLocation: definition.location,
});
}
};
const retainedArguments = (
+56 -43
View File
@@ -15,14 +15,13 @@ import {
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
compareCodePoints,
propertyName,
range,
} from "./javascriptStaticAnalysisHelpers.js";
import { compareCodePoints, range } from "./javascriptStaticAnalysisHelpers.js";
import {
dataEffectLiteralString,
dataEffectMemberCallee,
assignedSemanticResultBindings,
scalarAssignedResultBinding,
semanticProjectedBindingFacts,
} from "./javascriptSemanticDataEffectHelpers.js";
const CHILD_PROCESS_METHODS = ["spawn", "exec", "execFile", "fork"] as const;
@@ -38,6 +37,11 @@ interface SpawnCandidate {
readonly method: JavaScriptSemanticChildProcessSpawn["method"];
readonly ownerCallableId: string | null;
readonly resultBindingId: string | null;
readonly projectedResultBindings: readonly {
readonly bindingId: string;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}[];
}
interface ChildInteractionContext {
@@ -77,23 +81,41 @@ const collectSpawns = (
callables.map(({ callableId }) => callableId),
);
const callableStack: string[] = [];
const ancestors: t.Node[] = [];
traverseJavaScriptAst(program, {
enter: (node, parent) => {
enter: (node) => {
const callableId = semanticCallableIdForNode(node);
if (callableId !== null && admittedCallables.has(callableId))
callableStack.push(callableId);
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return;
const method = childProcessMethod(node.callee, state);
if (method === null) return;
output.push({
node,
method,
ownerCallableId: callableStack.at(-1) ?? null,
resultBindingId: assignedBindingId(parent, node, state),
});
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
const method = childProcessMethod(node.callee, state);
if (method !== null) {
const projectedResultBindings = assignedSemanticResultBindings(
node,
ancestors,
state,
);
output.push({
node,
method,
ownerCallableId: callableStack.at(-1) ?? null,
resultBindingId: scalarAssignedResultBinding(
projectedResultBindings,
),
projectedResultBindings: semanticProjectedBindingFacts(
projectedResultBindings.filter(
({ projectionPath }) => projectionPath.length > 0,
),
),
});
}
}
ancestors.push(node);
},
exit: (node) => {
ancestors.pop();
popCallable(node, callableStack);
},
exit: (node) => popCallable(node, callableStack),
});
return output;
};
@@ -109,6 +131,7 @@ const immutableSpawn = (
location: range(candidate.node),
ownerCallableId: candidate.ownerCallableId,
resultBindingId: candidate.resultBindingId,
projectedResultBindings: candidate.projectedResultBindings,
command,
argvCount: spawnArgvCount(candidate),
environmentSupplied: objectHasProperty(options, "env"),
@@ -130,10 +153,15 @@ const collectInteractions = (
const spawnsByBinding = new Map<string, SpawnCandidate[]>();
for (const spawn of spawns) {
spawnByNode.set(spawn.node, spawn);
if (spawn.resultBindingId === null) continue;
const existing = spawnsByBinding.get(spawn.resultBindingId) ?? [];
existing.push(spawn);
spawnsByBinding.set(spawn.resultBindingId, existing);
const ids = [
...(spawn.resultBindingId === null ? [] : [spawn.resultBindingId]),
...spawn.projectedResultBindings.map(({ bindingId }) => bindingId),
];
for (const id of ids) {
const existing = spawnsByBinding.get(id) ?? [];
existing.push(spawn);
spawnsByBinding.set(id, existing);
}
}
const context: ChildInteractionContext = {
state,
@@ -198,7 +226,13 @@ const childInteraction = (
: null,
listenerLocation:
kind === "listener" && t.isNode(listener) ? range(listener) : null,
resolution: linked.length === 1 ? "complete" : "partial",
resolution:
linked.length === 1 &&
!linked[0]?.projectedResultBindings.some(
({ bindingId }) => bindingId === binding?.bindingId,
)
? "complete"
: "partial",
};
};
@@ -334,27 +368,6 @@ const objectBinding = (
? resolveSemanticBindingState(state, node, node.name)
: undefined;
const assignedBindingId = (
parent: t.Node | null,
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | null => {
const identifier =
t.isVariableDeclarator(parent) &&
parent.init === node &&
t.isIdentifier(parent.id)
? parent.id
: t.isAssignmentExpression(parent) &&
parent.right === node &&
t.isIdentifier(parent.left)
? parent.left
: null;
return identifier === null
? null
: (resolveSemanticBindingState(state, identifier, identifier.name)
?.bindingId ?? null);
};
const popCallable = (node: t.Node, stack: string[]): void => {
const callableId = semanticCallableIdForNode(node);
if (callableId !== null && stack.at(-1) === callableId) stack.pop();
+122 -35
View File
@@ -1,9 +1,6 @@
import * as t from "@babel/types";
import {
semanticCallableIdForNode,
semanticStaticPropertyName,
} from "./javascriptSemanticProjection.js";
import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
@@ -11,6 +8,124 @@ import {
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { semanticStaticPropertyName } from "./javascriptAstValues.js";
export interface SemanticProjectedBinding {
readonly bindingId: string;
readonly identifier: t.Identifier;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}
/** Resolve bindings written by the nearest variable or assignment owner. */
export const assignedSemanticResultBindings = (
node: t.Node,
ancestors: readonly t.Node[],
state: JavaScriptSemanticAnalysisState,
): SemanticProjectedBinding[] => {
for (let index = ancestors.length - 1; index >= 0; index -= 1) {
const owner = ancestors[index];
if (owner === undefined) continue;
let pattern: t.Node | undefined;
let source: t.Node | null = null;
if (t.isVariableDeclarator(owner)) {
pattern = owner.id;
source = owner.init ?? null;
} else if (t.isAssignmentExpression(owner)) {
pattern = owner.left;
source = owner.right;
}
if (
pattern !== undefined &&
source !== null &&
assignedSourceIs(node, source)
)
return projectedPatternBindings(pattern, state);
if (semanticCallableIdForNode(owner) !== null) return [];
}
return [];
};
const assignedSourceIs = (node: t.Node, source: t.Node): boolean => {
let value = source;
while (true) {
if (t.isAwaitExpression(value)) value = value.argument;
else if (
t.isParenthesizedExpression(value) ||
t.isTSAsExpression(value) ||
t.isTSTypeAssertion(value) ||
t.isTypeCastExpression(value) ||
t.isTSSatisfiesExpression(value)
)
value = value.expression;
else break;
}
return value === node;
};
const projectedPatternBindings = (
pattern: t.Node,
state: JavaScriptSemanticAnalysisState,
): SemanticProjectedBinding[] => {
const output: SemanticProjectedBinding[] = [];
const visit = (
current: t.Node,
path: readonly (string | number | null)[],
partial: boolean,
): void => {
if (t.isIdentifier(current)) {
const binding = resolveSemanticBindingState(state, current, current.name);
if (binding !== undefined)
output.push({
bindingId: binding.bindingId,
identifier: current,
projectionPath: path,
resolution: partial ? "partial" : "complete",
});
return;
}
if (t.isAssignmentPattern(current)) return visit(current.left, path, true);
if (t.isRestElement(current))
return visit(current.argument, [...path, null], true);
if (t.isObjectPattern(current)) {
for (const property of current.properties) {
if (t.isRestElement(property))
visit(property.argument, [...path, null], true);
else
visit(
property.value,
[
...path,
semanticStaticPropertyName(property.key, property.computed) ||
null,
],
partial ||
semanticStaticPropertyName(property.key, property.computed) ===
"",
);
}
} else if (t.isArrayPattern(current)) {
current.elements.forEach((element, index) => {
if (element !== null) visit(element, [...path, index], partial);
});
}
};
visit(pattern, [], false);
return output;
};
export const semanticProjectedBindingFacts = (
bindings: readonly SemanticProjectedBinding[],
): Omit<SemanticProjectedBinding, "identifier">[] =>
bindings.map(({ identifier: _identifier, ...fact }) => fact);
/** Return a scalar owner only for an unprojected identifier result. */
export const scalarAssignedResultBinding = (
bindings: readonly SemanticProjectedBinding[],
): string | null =>
bindings.length === 1 && bindings[0]?.projectionPath.length === 0
? (bindings[0]?.bindingId ?? null)
: null;
/** Shared mutable stacks reset before each deterministic data-effect pass. */
export interface DataEffectTraversalContext {
@@ -80,37 +195,9 @@ export const outerDataEffectBinding = (
node: t.Node,
context: DataEffectTraversalContext,
): string | null => {
for (let index = context.ancestors.length - 1; index >= 0; index -= 1) {
const ancestor = context.ancestors[index];
if (ancestor === undefined) continue;
if (
t.isVariableDeclarator(ancestor) &&
t.isNode(ancestor.init) &&
containsSemanticNode(ancestor.init, node) &&
t.isIdentifier(ancestor.id)
)
return (
resolveSemanticBindingState(
context.state,
ancestor.id,
ancestor.id.name,
)?.bindingId ?? null
);
if (
t.isAssignmentExpression(ancestor) &&
containsSemanticNode(ancestor.right, node) &&
t.isIdentifier(ancestor.left)
)
return (
resolveSemanticBindingState(
context.state,
ancestor.left,
ancestor.left.name,
)?.bindingId ?? null
);
if (semanticCallableIdForNode(ancestor) !== null) return null;
}
return null;
return scalarAssignedResultBinding(
assignedSemanticResultBindings(node, context.ancestors, context.state),
);
};
/** Traverse with exact callable and ancestor stacks. */
+37 -11
View File
@@ -22,14 +22,12 @@ import {
dataEffectPrimitive as primitiveValue,
isSemanticProcessObject as isProcessObject,
outerDataEffectBinding as outerAssignedBinding,
assignedSemanticResultBindings,
semanticProjectedBindingFacts,
traverseDataEffects as traverseWithContext,
type DataEffectTraversalContext as TraversalContext,
} from "./javascriptSemanticDataEffectHelpers.js";
import {
compareCodePoints,
propertyName,
range,
} from "./javascriptStaticAnalysisHelpers.js";
import { compareCodePoints, range } from "./javascriptStaticAnalysisHelpers.js";
interface DataEffectAnalysis {
readonly configurationOperations: readonly JavaScriptSemanticConfigurationOperation[];
@@ -207,6 +205,13 @@ const collectRequests = (
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
projectedResultBindings: semanticProjectedBindingFacts(
assignedSemanticResultBindings(
node,
context.ancestors,
context.state,
).filter(({ projectionPath }) => projectionPath.length > 0),
),
linkedRequestIds: [],
endpoint,
fields: requestFields(node, method, context.state),
@@ -224,11 +229,19 @@ const collectResponseConsumers = (
): JavaScriptSemanticRequestOperation[] => {
const requestsByBinding = new Map<string, RequestCandidate[]>();
for (const request of requests) {
const bindingId = request.operation.resultBindingId;
if (bindingId === null) continue;
const existing = requestsByBinding.get(bindingId) ?? [];
existing.push(request);
requestsByBinding.set(bindingId, existing);
const bindingIds = [
...(request.operation.resultBindingId === null
? []
: [request.operation.resultBindingId]),
...request.operation.projectedResultBindings.map(
({ bindingId }) => bindingId,
),
];
for (const bindingId of bindingIds) {
const existing = requestsByBinding.get(bindingId) ?? [];
existing.push(request);
requestsByBinding.set(bindingId, existing);
}
}
const output: JavaScriptSemanticRequestOperation[] = [];
traverseWithContext(program, context, (node) => {
@@ -255,12 +268,25 @@ const collectResponseConsumers = (
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
projectedResultBindings: semanticProjectedBindingFacts(
assignedSemanticResultBindings(
node,
context.ancestors,
context.state,
).filter(({ projectionPath }) => projectionPath.length > 0),
),
linkedRequestIds: linked
.map(({ operation }) => operation.requestId)
.sort(compareCodePoints),
endpoint: null,
fields: [],
resolution: linked.length === 1 ? "complete" : "partial",
resolution:
linked.length === 1 &&
!linked[0]?.operation.projectedResultBindings.some(
({ bindingId }) => bindingId === binding?.bindingId,
)
? "complete"
: "partial",
});
});
return output;
+10
View File
@@ -257,6 +257,7 @@ export interface JavaScriptSemanticTimerOperation {
readonly location: JavaScriptSourceRange;
readonly ownerCallableId: string | null;
readonly handleBindingId: string | null;
readonly projectedResultBindings: readonly JavaScriptSemanticProjectedResultBinding[];
readonly linkedTimerId: string | null;
readonly delayMilliseconds: number | null;
readonly resolution: "complete" | "partial" | "unresolved";
@@ -269,6 +270,7 @@ export interface JavaScriptSemanticChildProcessSpawn {
readonly location: JavaScriptSourceRange;
readonly ownerCallableId: string | null;
readonly resultBindingId: string | null;
readonly projectedResultBindings: readonly JavaScriptSemanticProjectedResultBinding[];
readonly command: string | null;
readonly argvCount: number | null;
readonly environmentSupplied: boolean;
@@ -319,6 +321,7 @@ export interface JavaScriptSemanticRequestOperation {
readonly location: JavaScriptSourceRange;
readonly ownerCallableId: string | null;
readonly resultBindingId: string | null;
readonly projectedResultBindings: readonly JavaScriptSemanticProjectedResultBinding[];
readonly linkedRequestIds: readonly string[];
readonly endpoint: string | null;
readonly fields: readonly {
@@ -328,6 +331,13 @@ export interface JavaScriptSemanticRequestOperation {
readonly resolution: "complete" | "partial" | "unresolved";
}
/** A destructured result binding with its known projection path. */
export interface JavaScriptSemanticProjectedResultBinding {
readonly bindingId: string;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}
/** One parse, coercion, or validation boundary candidate. */
export interface JavaScriptSemanticBoundaryOperation {
readonly boundaryId: string;
+3 -13
View File
@@ -25,6 +25,7 @@ import {
range,
stringValue,
} from "./javascriptStaticAnalysisHelpers.js";
import { semanticStaticPropertyName } from "./javascriptAstValues.js";
interface CollectCallableInput {
readonly node: t.Node;
@@ -201,14 +202,7 @@ const semanticModuleOrigin = (
};
};
/** Read a property only when its syntax commits an exact name. */
export const semanticStaticPropertyName = (
property: t.Node,
computed: boolean,
): string =>
computed && !t.isStringLiteral(property) && !t.isNumericLiteral(property)
? ""
: propertyName(property);
export { semanticStaticPropertyName } from "./javascriptAstValues.js";
const callableKind = (
node: t.Node,
@@ -642,8 +636,4 @@ const commonJsExportName = (
const memberKey = (
node: t.MemberExpression | t.OptionalMemberExpression,
): string | null =>
node.computed &&
!t.isStringLiteral(node.property) &&
!t.isNumericLiteral(node.property)
? null
: propertyName(node.property);
semanticStaticPropertyName(node.property, node.computed) || null;
+19 -30
View File
@@ -19,7 +19,12 @@ import {
range,
sourceRangesEqual,
} from "./javascriptStaticAnalysisHelpers.js";
import { dataEffectMemberCallee } from "./javascriptSemanticDataEffectHelpers.js";
import {
assignedSemanticResultBindings,
containsSemanticNode,
dataEffectMemberCallee,
scalarAssignedResultBinding,
} from "./javascriptSemanticDataEffectHelpers.js";
type PromiseMethod = JavaScriptSemanticPromiseOperation["method"];
type PromiseKind = JavaScriptSemanticPromiseOperation["kind"];
@@ -244,21 +249,15 @@ const assignedPromiseBinding = (
ancestor: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | null | undefined => {
if (
t.isVariableDeclarator(ancestor) &&
ancestor.init !== null &&
t.isIdentifier(ancestor.id)
)
return (
resolveSemanticBindingState(state, ancestor.id, ancestor.id.name)
?.bindingId ?? null
);
if (t.isAssignmentExpression(ancestor) && t.isIdentifier(ancestor.left))
return (
resolveSemanticBindingState(state, ancestor.left, ancestor.left.name)
?.bindingId ?? null
);
return undefined;
if (!t.isVariableDeclarator(ancestor) && !t.isAssignmentExpression(ancestor))
return undefined;
const source = t.isVariableDeclarator(ancestor)
? ancestor.init
: ancestor.right;
if (source == null) return undefined;
return scalarAssignedResultBinding(
assignedSemanticResultBindings(source, [ancestor], state),
);
};
const returnedPromiseOwnership = (
@@ -280,30 +279,20 @@ const outerConsumesCandidate = (
(t.isCallExpression(outer.node) || t.isOptionalCallExpression(outer.node))
) {
const member = dataEffectMemberCallee(outer.node);
return member !== null && containsNode(member.object, candidate.node);
return (
member !== null && containsSemanticNode(member.object, candidate.node)
);
}
if (
outer.kind === "aggregate" &&
(t.isCallExpression(outer.node) || t.isOptionalCallExpression(outer.node))
) {
const input = outer.node.arguments[0];
return t.isNode(input) && containsNode(input, candidate.node);
return t.isNode(input) && containsSemanticNode(input, candidate.node);
}
return false;
};
const containsNode = (outer: t.Node, inner: t.Node): boolean =>
outer.start !== null &&
outer.start !== undefined &&
outer.end !== null &&
outer.end !== undefined &&
inner.start !== null &&
inner.start !== undefined &&
inner.end !== null &&
inner.end !== undefined &&
outer.start <= inner.start &&
outer.end >= inner.end;
const emptyOwnership = (
ownership: JavaScriptSemanticPromiseOperation["ownership"],
): PromiseOwnership => ({
+3 -4
View File
@@ -17,6 +17,7 @@ import {
propertyName,
stringValue,
} from "./javascriptStaticAnalysisHelpers.js";
import { semanticStaticPropertyName } from "./javascriptAstValues.js";
import {
semanticAmbiguousProvenance,
semanticLocalProvenance,
@@ -454,10 +455,8 @@ const mergeValues = (
const memberKey = (
node: t.MemberExpression | t.OptionalMemberExpression,
): string | number | undefined => {
if (!node.computed) return propertyName(node.property) || undefined;
if (t.isStringLiteral(node.property) || t.isNumericLiteral(node.property))
return node.property.value;
return undefined;
const name = semanticStaticPropertyName(node.property, node.computed);
return name === "" ? undefined : name;
};
const nestedContext = (
@@ -3,6 +3,15 @@ import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
describe("JavaScript static analysis findings", () => {
it("does not infer a webpack push from a dynamic computed key", () => {
const analysis = analyzeJavaScriptStaticSource(`
const push = "push";
const arr = {};
arr[push]([[1], { 1: function () {} }]);
`);
expect(analysis.bundler_registrations).toEqual([]);
});
it("retains every static reference and Electron property in large literals", () => {
const names = Array.from({ length: 10_001 }, (_, index) => `key${index}`);
const source = [
+3 -3
View File
@@ -12,7 +12,7 @@ import {
calleeName,
endpointArgument as endpointArgumentHelper,
prefixedArgument,
propertyName,
semanticStaticPropertyName,
range,
rangeForOffsets,
sourceSlice,
@@ -176,7 +176,7 @@ export const inspectRouteProperty = (
node: t.ObjectProperty,
context: FindingContext,
): void => {
const key = propertyName(node.key);
const key = semanticStaticPropertyName(node.key, node.computed);
if ((key === "path" || key === "route") && t.isStringLiteral(node.value))
addEndpoint(context, {
node,
@@ -190,7 +190,7 @@ export const inspectRoleProperty = (
node: t.ObjectProperty,
context: FindingContext,
): void => {
if (propertyName(node.key) !== "preload") return;
if (semanticStaticPropertyName(node.key, node.computed) !== "preload") return;
const path = staticPath(node.value);
if (path === undefined) return;
addLocatedFinding(context, {
+14 -7
View File
@@ -10,9 +10,12 @@ import type {
JavaScriptStaticPathContext,
JavaScriptStaticStorage,
} from "./javascriptStaticAnalysisTypes.js";
import { propertyName } from "./javascriptAstValues.js";
import { semanticStaticPropertyName } from "./javascriptAstValues.js";
export { propertyName } from "./javascriptAstValues.js";
export {
propertyName,
semanticStaticPropertyName,
} from "./javascriptAstValues.js";
/** Explicit result for source text that Babel cannot parse. */
export const failedJavaScriptStaticAnalysis = (): JavaScriptStaticAnalysis => ({
@@ -59,7 +62,11 @@ export const chunkRuntime = (call: t.CallExpression): string | undefined => {
!t.isOptionalMemberExpression(call.callee)
)
return undefined;
if (propertyName(call.callee.property) !== "push") return undefined;
if (
semanticStaticPropertyName(call.callee.property, call.callee.computed) !==
"push"
)
return undefined;
return findChunkRuntime(call.callee.object);
};
@@ -67,7 +74,7 @@ const findChunkRuntime = (node: t.Node): string | undefined => {
if (t.isIdentifier(node) && /(?:webpack|rspack)Chunk/iu.test(node.name))
return node.name;
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const property = propertyName(node.property);
const property = semanticStaticPropertyName(node.property, node.computed);
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
return t.isNode(node.object) ? findChunkRuntime(node.object) : undefined;
}
@@ -107,7 +114,7 @@ export const modulePropertyName = (
!t.isStringLiteral(property.key) &&
!t.isNumericLiteral(property.key)
? `[computed@${String(property.start ?? -1)}]`
: propertyName(property.key) ||
: semanticStaticPropertyName(property.key, property.computed) ||
`[unknown@${String(property.start ?? -1)}]`
: `[unknown@${String(property.start ?? -1)}]`;
@@ -241,7 +248,7 @@ const isFileIdentity = (node: t.Node | undefined): boolean => {
t.isMetaProperty(node.object) &&
node.object.meta.name === "import" &&
node.object.property.name === "meta" &&
propertyName(node.property) === "url"
semanticStaticPropertyName(node.property, node.computed) === "url"
)
return true;
if (!t.isCallExpression(node)) return false;
@@ -312,7 +319,7 @@ const memberPropertyName = (
!t.isStringLiteral(node.property) &&
!t.isNumericLiteral(node.property)
? `[computed@${String(node.property.start ?? -1)}]`
: propertyName(node.property);
: semanticStaticPropertyName(node.property, node.computed);
/** Return a string literal value without evaluating an expression. */
export const stringValue = (
@@ -0,0 +1,124 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { compareManagedMembers } from "./managedMemberComparison.js";
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "../dotnet/ManagedPe.fixture.js";
const inspect = (bytes: Buffer, path: string) => {
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target);
return { result, evidenceId: `ev_${hash(Buffer.from(path))}` };
};
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
describe("managed member partial body comparison", () => {
it("keeps unavailable body facets unknown while retaining an observed signature change", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-body-partial.dll");
const right = inspect(
buildManagedPeFixture(),
"/tmp/right-body-partial.dll",
);
const leftMethod = left.result.methods[0];
const rightMethod = right.result.methods[0];
expect(leftMethod).toBeDefined();
expect(rightMethod).toBeDefined();
if (leftMethod === undefined || rightMethod === undefined) return;
const leftResult = {
...left.result,
methods: [
{
...leftMethod,
body: {
...leftMethod.body,
status: "partial" as const,
normalized_il_sha256: null,
},
},
],
};
const rightResult = {
...right.result,
methods: [
{
...rightMethod,
body: {
...rightMethod.body,
status: "partial" as const,
normalized_il_sha256: null,
opcode_counts: { nop: 1 },
},
},
],
};
const partial = compareManagedMembers(
{ evidenceId: left.evidenceId, result: leftResult },
{ evidenceId: right.evidenceId, result: rightResult },
);
expect(partial.methods[0]).toMatchObject({
status: "unknown",
dimensions: ["body-coverage"],
});
const rightSignatureChanged = {
...right.result,
methods: [
{
...rightMethod,
signature: {
...rightMethod.signature,
raw_sha256: "f".repeat(64),
},
},
],
};
const signatureChanged = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{
evidenceId: right.evidenceId,
result: rightSignatureChanged,
},
);
expect(signatureChanged.methods[0]).toMatchObject({
status: "changed",
dimensions: ["signature"],
});
const bothAbsent = compareManagedMembers(
{
evidenceId: left.evidenceId,
result: {
...left.result,
methods: [
{
...leftMethod,
body: { ...leftMethod.body, status: "absent" as const },
},
],
},
},
{
evidenceId: right.evidenceId,
result: {
...right.result,
methods: [
{
...rightMethod,
body: { ...rightMethod.body, status: "absent" as const },
},
],
},
},
);
expect(bothAbsent.methods[0]).toMatchObject({
status: "unchanged",
dimensions: [],
});
});
});
+5 -5
View File
@@ -29,7 +29,7 @@ describe("managed member comparison", () => {
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.algorithm.name_matching).toBe("not-used");
expect(result.algorithm.name_matching).toBe("exact-signature-fallback");
expect(result.left.mvid).toBe("00112233-4455-6677-8899-aabbccddeeff");
expect(result.right.mvid).toBe("33221100-5544-7766-8899-aabbccddeefe");
expect(result.matching.exact_il_signature).toBe(1);
@@ -47,7 +47,7 @@ describe("managed member comparison", () => {
}),
]);
expect(result.limitations).toContain(
"Names are reported as observations but are not used as a matching basis.",
"Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.",
);
expect(
managedMemberComparisonResultSchema.safeParse({
@@ -57,7 +57,7 @@ describe("managed member comparison", () => {
).toBe(true);
});
it("uses structural method shape when build-local token operands drift", () => {
it("compares changed CIL after pairing by exact signature", () => {
const leftBytes = buildManagedPeFixture();
const rightBytes = buildManagedPeFixture({
ilBody: Buffer.from([
@@ -73,10 +73,10 @@ describe("managed member comparison", () => {
);
expect(result.matching.exact_il_signature).toBe(0);
expect(result.matching.structural_method_shape).toBe(1);
expect(result.matching.exact_signature).toBe(1);
expect(result.methods[0]).toMatchObject({
status: "changed",
match: { status: "matched", basis: "structural-method-shape" },
match: { status: "matched", basis: "exact-signature" },
dimensions: ["cil"],
});
});
+7 -4
View File
@@ -42,6 +42,7 @@ export const compareManagedMembersInputSchema = z
const concreteMatchBasisSchema = z.enum([
"exact-il-signature",
"exact-signature",
"structural-method-shape",
"field-signature",
]);
@@ -85,7 +86,7 @@ const comparisonItemSchema = <
z.union([
z.strictObject({
...base,
status: z.enum(["unchanged", "changed"]),
status: z.enum(["unchanged", "changed", "unknown"]),
left: identity,
right: identity,
match: matchedComparisonSchema,
@@ -131,6 +132,7 @@ const methodComparisonItemSchema = comparisonItemSchema(
"field-shape",
"exception-shape",
"availability",
"body-coverage",
]),
),
},
@@ -151,7 +153,7 @@ export const managedMemberComparisonResultSchema = z.strictObject({
algorithm: z.strictObject({
name: z.literal("rea-managed-member-comparison"),
token_identity: z.literal("build-local"),
name_matching: z.literal("not-used"),
name_matching: z.literal("exact-signature-fallback"),
}),
left: z.strictObject({
evidence_id: evidenceIdSchema,
@@ -180,6 +182,7 @@ export const managedMemberComparisonResultSchema = z.strictObject({
}),
matching: z.strictObject({
exact_il_signature: z.number().int().min(0),
exact_signature: z.number().int().min(0),
structural_method_shape: z.number().int().min(0),
field_signature: z.number().int().min(0),
ambiguous: z.number().int().min(0),
@@ -209,7 +212,7 @@ export interface ManagedMemberComparisonSide {
readonly result: ManagedMemberInspection;
}
/** Compare two parsed managed member observations without name-based matching. */
/** Compare managed members with constrained exact and structural identities. */
export const compareManagedMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
@@ -247,7 +250,7 @@ export const compareManagedMembers = (
algorithm: {
name: "rea-managed-member-comparison" as const,
token_identity: "build-local" as const,
name_matching: "not-used" as const,
name_matching: "exact-signature-fallback" as const,
},
left: sideManifest(left),
right: sideManifest(right),
@@ -68,6 +68,9 @@ export const buildComparisonMatching = (
exact_il_signature: methodItems.filter(
({ match }) => match.basis === "exact-il-signature",
).length,
exact_signature: methodItems.filter(
({ match }) => match.basis === "exact-signature",
).length,
structural_method_shape: methodItems.filter(
({ match }) => match.basis === "structural-method-shape",
).length,
@@ -88,7 +91,7 @@ export const comparisonLimitations = (
): string[] => {
const limitations: string[] = [
"Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.",
"Names are reported as observations but are not used as a matching basis.",
"Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.",
];
if (left.coverage.state !== "complete" || right.coverage.state !== "complete")
limitations.push("At least one managed member observation is partial.");
+38 -7
View File
@@ -28,13 +28,30 @@ interface ComparisonItemContext {
readonly rightComplete: boolean;
}
const changedMethodDimensions = (
const methodDimensions = (
left: Method,
right: Method,
): MethodItem["dimensions"] => {
): {
readonly dimensions: MethodItem["dimensions"];
readonly bodyUnknown: boolean;
} => {
const dimensions: MethodItem["dimensions"] = [];
if (left.signature.raw_sha256 !== right.signature.raw_sha256)
dimensions.push("signature");
const leftBodyComplete =
left.body.status === "present" && left.body.truncated_instructions === 0;
const rightBodyComplete =
right.body.status === "present" && right.body.truncated_instructions === 0;
const bothAbsent =
left.body.status === "absent" && right.body.status === "absent";
if (
(left.body.status === "absent" && rightBodyComplete) ||
(right.body.status === "absent" && leftBodyComplete)
)
dimensions.push("availability");
if (bothAbsent) return { dimensions, bodyUnknown: false };
if (!leftBodyComplete || !rightBodyComplete)
return { dimensions, bodyUnknown: true };
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
dimensions.push("cil");
if (
@@ -51,8 +68,7 @@ const changedMethodDimensions = (
canonicalize(right.body.exception_regions)
)
dimensions.push("exception-shape");
if (left.body.status !== right.body.status) dimensions.push("availability");
return dimensions;
return { dimensions, bodyUnknown: false };
};
const callShape = (anchors: Method["body"]["anchors"]): string =>
@@ -174,14 +190,25 @@ export const buildMethodItems = (
): MethodItem[] => {
const items: MethodItem[] = [];
for (const pair of matches.pairs) {
const dimensions = changedMethodDimensions(pair.left.item, pair.right.item);
const { dimensions: observedDimensions, bodyUnknown } = methodDimensions(
pair.left.item,
pair.right.item,
);
const dimensions = bodyUnknown
? [...observedDimensions, "body-coverage" as const]
: observedDimensions;
const observedChange = observedDimensions.length > 0;
items.push({
item_id: `mmc_method_${sha256({
left: pair.left.item.token,
right: pair.right.item.token,
basis: pair.basis,
})}`,
status: dimensions.length === 0 ? "unchanged" : "changed",
status: observedChange
? "changed"
: bodyUnknown
? "unknown"
: "unchanged",
left: methodIdentity(pair.left.item),
right: methodIdentity(pair.right.item),
match: {
@@ -193,7 +220,11 @@ export const buildMethodItems = (
},
dimensions,
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations: [],
limitations: bodyUnknown
? [
"Method body facets are unknown because at least one side has unavailable or partial body data.",
]
: [],
});
}
for (const ambiguous of matches.ambiguous) {
+27 -6
View File
@@ -29,6 +29,7 @@ type ConcreteMatchBasis = Exclude<MatchBasis, "none">;
interface Keyed<Item> {
readonly item: Item;
readonly exactKey: string | null;
readonly signatureKey: string | null;
readonly structuralKey: string | null;
}
@@ -57,6 +58,15 @@ const keyMethod = (item: Method): Keyed<Method> => ({
item.body.normalized_il_sha256,
])
: null,
signatureKey:
item.signature.parse_status === "decoded"
? stableKey([
"method-signature",
item.declaring_type,
item.name,
item.signature.raw_sha256,
])
: null,
structuralKey:
item.body.status === "present"
? stableKey([
@@ -94,6 +104,7 @@ const keyField = (item: Field): Keyed<Field> => ({
item.signature.parse_status === "decoded"
? stableKey(["field-exact", item.signature.raw_sha256])
: null,
signatureKey: null,
structuralKey: stableKey([
"field-structural",
item.signature.kind,
@@ -112,7 +123,16 @@ const matchMethods = (
left,
right,
exactBasis: "exact-il-signature",
fallbackBases: ["structural-method-shape"],
fallbackBases: [
{
basis: "exact-signature",
key: ({ signatureKey }) => signatureKey,
},
{
basis: "structural-method-shape",
key: ({ structuralKey }) => structuralKey,
},
],
});
const matchFields = (
@@ -133,7 +153,10 @@ interface MatchByKeysInput<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly exactBasis: ConcreteMatchBasis;
readonly fallbackBases: readonly ConcreteMatchBasis[];
readonly fallbackBases: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[];
}
const matchByKeys = <Item>({
@@ -156,10 +179,7 @@ const matchByKeys = <Item>({
readonly key: (item: Keyed<Item>) => string | null;
}[] = [
{ basis: exactBasis, key: ({ exactKey }) => exactKey },
...fallbackBases.map((basis) => ({
basis,
key: ({ structuralKey }: Keyed<Item>) => structuralKey,
})),
...fallbackBases,
];
for (const round of rounds) {
const leftGroups = groupBy(
@@ -185,6 +205,7 @@ const matchByKeys = <Item>({
basis: round.basis,
confidence:
round.basis === "exact-il-signature" ||
round.basis === "exact-signature" ||
round.basis === "field-signature"
? "exact"
: "high",
-1
View File
@@ -73,7 +73,6 @@ const dependencySchema = z.object({
const loadCommandSchema = z.object({
index: z.number().int().min(0),
kind: z.string(),
file_offset: z.number().int().min(0).nullable(),
fields: z.record(z.string(), z.union([z.string(), z.number(), z.null()])),
});
const buildMetadataSchema = z.object({
+4 -11
View File
@@ -1,6 +1,4 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { absenceClaimable, canonicalDigest } from "./comparisonSemantics.js";
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
import type { HistoricalSourceGraph } from "./referenceSourceGraph.js";
@@ -102,8 +100,7 @@ const projectComparison = (
index,
absenceComplete:
input.reference.inventory_state === "complete" &&
input.application.graph.coverage.status === "complete" &&
!input.application.graph.coverage.truncated,
absenceClaimable(input.application.graph.coverage),
factors: {
input,
},
@@ -367,12 +364,8 @@ const compareCandidates = (
right.score - left.score ||
compareText(left.current_node_id, right.current_node_id);
const digestCanonical = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Source-to-bundle comparison could not canonicalize");
return createHash("sha256").update(encoded).digest("hex");
};
const digestCanonical = (value: unknown): string =>
canonicalDigest(value, "Source-to-bundle comparison");
const uniqueSorted = (values: readonly string[]): string[] =>
[...new Set(values)].sort(compareText);
+2 -9
View File
@@ -1,7 +1,4 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { canonicalDigest } from "./comparisonSemantics.js";
import type { WebPageInspection } from "./browserObservation.js";
import {
webCaptureDiffSchema,
@@ -333,11 +330,7 @@ const metadataProjection = (inspection: WebPageInspection) => ({
const singleton = (key: string, value: string): ReadonlyMap<string, string> =>
new Map([[key, value]]);
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
const digest = (value: unknown): string => canonicalDigest(value);
const accessibilityComparable = (
inspection: WebPageInspection,