chore: reconcile iNES inventory with current main

This commit is contained in:
64579525
2026-10-13 09:36:35 +08:00
646 changed files with 49020 additions and 6280 deletions
+29 -10
View File
@@ -679,6 +679,8 @@ export const adbResultSchemas = {
package_name: packageNameSchema,
component: z.string().min(1),
started_activity: z.string().nullable(),
reported_activity: z.string().nullable().optional(),
reported_status: z.string().nullable().optional(),
}),
start_adb_activity: z.strictObject({
client,
@@ -694,6 +696,8 @@ export const adbResultSchemas = {
}),
),
started_activity: z.string().nullable(),
reported_activity: z.string().nullable().optional(),
reported_status: z.string().nullable().optional(),
}),
stop_adb_app: z.strictObject({
client,
@@ -702,6 +706,19 @@ export const adbResultSchemas = {
}),
} as const;
/** Launch-attempt facts retained when Activity Manager does not report success. */
export type AdbActivityStartPartialObservation =
| {
readonly provider_id: "adb";
readonly operation: "start_adb_app";
readonly result: z.infer<typeof adbResultSchemas.start_adb_app>;
}
| {
readonly provider_id: "adb";
readonly operation: "start_adb_activity";
readonly result: z.infer<typeof adbResultSchemas.start_adb_activity>;
};
/** Acquired package facts retained when cancellation leaves caller-owned output. */
export type AdbPackagePullPartialObservation = {
readonly provider_id: "adb";
@@ -709,7 +726,7 @@ export type AdbPackagePullPartialObservation = {
readonly result: z.infer<typeof adbResultSchemas.pull_adb_package>;
};
/** A completed acquisition whose digest read was cancelled before verification. */
/** Acquired file facts retained when publication, digest verification or cleanup fails. */
export type AdbAcquiredFilePartialObservation =
| {
readonly provider_id: "adb";
@@ -727,13 +744,15 @@ export type AdbAcquiredFilePartialObservation =
| {
readonly provider_id: "adb";
readonly operation: "collect_adb_bugreport";
readonly result: {
readonly client: z.infer<
typeof adbResultSchemas.collect_adb_bugreport
>["client"];
readonly serial: string;
readonly local_path: string;
readonly adb_reported_path: string;
readonly digest_status: "unknown";
};
readonly result:
| z.infer<typeof adbResultSchemas.collect_adb_bugreport>
| {
readonly client: z.infer<
typeof adbResultSchemas.collect_adb_bugreport
>["client"];
readonly serial: string;
readonly local_path: string;
readonly adb_reported_path: string;
readonly digest_status: "unknown";
};
};
+19
View File
@@ -1,3 +1,5 @@
import type { JsonValue } from "./jsonValue.js";
/** Stable tags exposed by safe analysis-error projections. */
const ANALYSIS_ERROR_TAGS = [
"AnalysisProtocolError",
@@ -51,6 +53,8 @@ export interface AnalysisCleanupObservation {
/** Optional provider-neutral context that must survive typed error projection. */
export interface AnalysisErrorOptions extends ErrorOptions {
/** Producer-owned, caller-safe facts retained through every typed projection. */
readonly diagnostics?: Readonly<Record<string, JsonValue>> | undefined;
readonly capturedOutput?: AnalysisCapturedOutput | undefined;
readonly cleanup?: AnalysisCleanupObservation | undefined;
readonly partialObservation?: AnalysisPartialObservation | undefined;
@@ -58,12 +62,17 @@ export interface AnalysisErrorOptions extends ErrorOptions {
/** Base class for expected analysis, provider, and session failures. */
export abstract class AnalysisError extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>> | undefined;
readonly capturedOutput: AnalysisCapturedOutput | undefined;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupIncomplete: boolean;
readonly cleanupResources: readonly string[];
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
this.diagnostics =
options?.diagnostics === undefined
? undefined
: structuredClone(options.diagnostics);
this.capturedOutput =
options?.capturedOutput === undefined
? undefined
@@ -105,10 +114,16 @@ import type { Evidence } from "./evidence.js";
import type { AndroidPartialObservation } from "./android/androidPartialObservation.js";
import type { FirmwarePartialObservation } from "./firmware/firmwareAnalysis.js";
import type {
AdbActivityStartPartialObservation,
AdbAcquiredFilePartialObservation,
AdbPackagePullPartialObservation,
} from "./adb/adbDeviceAnalysis.js";
import type { NativeUiObservationResult } from "./native/nativeUiObservation.js";
import type { BinaryLayout } from "./native/binaryLayout.js";
import type {
RecordedCrash,
RecordedCrashPartialObservation,
} from "./native/recordedCrash.js";
/** Provider-neutral evidence collected before a typed analysis failure. */
export type AnalysisPartialObservation =
@@ -123,8 +138,12 @@ export type AnalysisPartialObservation =
| WebScriptExportPartialObservation
| JavaScriptRecoveryPartialObservation
| Evidence
| BinaryLayout
| RecordedCrash
| RecordedCrashPartialObservation
| AndroidPartialObservation
| FirmwarePartialObservation
| NativeUiObservationResult
| AdbActivityStartPartialObservation
| AdbAcquiredFilePartialObservation
| AdbPackagePullPartialObservation;
+10 -1
View File
@@ -21,13 +21,22 @@ export class AnalysisUnsupportedTargetError extends AnalysisError {
}
/** An analysis or transport resource failure, distinct from malformed input or unsupported coverage. */
export const ANALYSIS_RESOURCE_KINDS = [
"memory",
"cpu",
"file-size",
"transport",
"capacity",
] as const;
/** A measured resource constraint or bounded admission refusal. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
readonly remediationAction: string | undefined;
constructor(
readonly operation: string,
readonly resource: "memory" | "cpu" | "file-size" | "transport",
readonly resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
options?: AnalysisErrorOptions & { readonly remediationAction?: string },
+9 -7
View File
@@ -45,13 +45,15 @@ export const analysisErrorRemediationAction = (
if (error instanceof AnalysisResourceConstraintError)
return (
error.remediationAction ??
(error.resource === "transport"
? "Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable."
: error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.")
(error.resource === "capacity"
? "Wait for an active analysis to complete, then retry within the reported admission limits."
: error.resource === "transport"
? "Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable."
: error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.")
);
if (error instanceof HopperTimeoutError)
return error.operation === undefined
+60 -18
View File
@@ -116,6 +116,40 @@ it("distinguishes unsupported target formats from unavailable provider capabilit
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it.each([false, true])(
"marks occupied capacity retryable only while cleanup is confirmed: %s",
(cleanupIncomplete) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_sqlite_database",
"capacity",
"Inspection slots are occupied",
{ max_concurrent_inspections: 2 },
cleanupIncomplete
? {
cleanup: {
reason: "Snapshot removal denied",
resources: ["/private/snapshot"],
},
}
: undefined,
),
);
expect(projected.retryable).toBe(!cleanupIncomplete);
expect(projected.code).toBe(
cleanupIncomplete ? "cleanup_incomplete" : "resource_constraint",
);
expect(projected.details).toMatchObject({
resource: "capacity",
reported_limits: { max_concurrent_inspections: 2 },
});
expect(projected.remediation.action).toContain("Wait");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
@@ -369,25 +403,33 @@ describe("analysis error projection: provider failures", () => {
});
});
it("preserves detached, actionable provider diagnostics", () => {
const diagnostics = {
runtime_root: "/tmp/rea-ghidra-fixture",
profile_digest: "a".repeat(64),
exit_code: 1,
};
const error = new ProviderAdapterError("ghidra", "health", {
diagnostics,
});
it.each(["adapter", "cancelled", "timeout"])(
"preserves detached, actionable diagnostics for %s errors",
(kind) => {
const diagnostics = {
runtime_root: "/tmp/rea-ghidra-fixture",
profile_digest: "a".repeat(64),
exit_code: 1,
};
const error =
kind === "adapter"
? new ProviderAdapterError("ghidra", "health", { diagnostics })
: kind === "cancelled"
? new AnalysisCancelledError("health", { diagnostics })
: new AnalysisTimeoutError("health", 250, { diagnostics });
expect(error.diagnostics).not.toBe(diagnostics);
expect(projectAnalysisError(error)).toMatchObject({
details: {
provider_id: "ghidra",
operation: "health",
diagnostics,
},
});
});
expect(error.diagnostics).not.toBe(diagnostics);
expect(projectAnalysisError(error)).toMatchObject({
details: {
...(kind === "adapter" ? { provider_id: "ghidra" } : {}),
operation: "health",
diagnostics,
},
});
diagnostics.exit_code = 2;
expect(error.diagnostics?.exit_code).toBe(1);
},
);
it("maps the Linux startup compatibility exit codes without host internals", () => {
const expected = [
+8 -4
View File
@@ -52,6 +52,9 @@ export const projectAnalysisError = (
const primaryDetails = errorDetails(error);
const details = {
...primaryDetails,
...(error.diagnostics === undefined
? {}
: { diagnostics: error.diagnostics }),
...(error.cleanupIncomplete
? {
cleanup: "incomplete",
@@ -78,7 +81,11 @@ export const projectAnalysisError = (
code,
category: analysisErrorCategory(error),
message: analysisErrorUserMessage(error),
retryable: RETRYABLE_CODES.has(code),
retryable:
RETRYABLE_CODES.has(code) ||
(code === "resource_constraint" &&
error instanceof AnalysisResourceConstraintError &&
error.resource === "capacity"),
remediation: {
action: analysisErrorRemediationAction(error),
},
@@ -354,9 +361,6 @@ const providerErrorDetails = (
resources: [...error.cleanupResources],
}
: {}),
...(error.diagnostics === undefined
? {}
: { diagnostics: error.diagnostics }),
};
if (error instanceof BrowserObservationError) {
const primaryReason = primaryBrowserFailureReason(error);
@@ -733,6 +733,14 @@ it("does not match unavailable layout names using a display placeholder", () =>
});
it("rejects unsupported parent operations and incompatible collections", () => {
expect(
projectAnalysisView(layoutParent(), {
kind: "managed",
collection: "attributes",
offset: 0,
limit: 1,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const unsupported = projectAnalysisView(
{
evidenceId: `ev_${"d".repeat(64)}`,
+67 -11
View File
@@ -35,7 +35,20 @@ import {
apiSurfaceViewSchema,
} from "./webNetworkApiSurfaceView.js";
import { projectNativeFunctionView } from "./nativeFunctionView.js";
import {
projectEvmInterfaceView,
evmViewRequestSchema,
evmViewItemSchema,
evmSummarySchema,
} from "./evmInterfaceView.js";
import { projectArtifactInventoryView } from "./artifactInventoryView.js";
import {
projectManagedArtifactView,
managedViewRequestSchema,
managedViewItemSchema,
managedSummarySchema,
managedViewContextSchema,
} from "./managedArtifactView.js";
import {
projectWasmArtifactView,
wasmViewRequestSchema,
@@ -154,6 +167,8 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
nativeViewSchema,
inventoryViewSchema,
wasmViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
apiSurfaceViewSchema,
]);
@@ -266,6 +281,8 @@ const viewResultBase = {
"inspect_artifact",
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -309,6 +326,20 @@ export const wasmArtifactSummaryViewResultSchema = z.strictObject({
summary: wasmSummarySchema,
});
/** Exact inferred-interface summary for EVM's caller-selected delivery. */
export const evmInterfaceSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_evm_interface"),
summary: evmSummarySchema,
});
/** Exact metadata overview for the managed artifact's selected delivery. */
export const managedArtifactSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_managed_artifact"),
summary: managedSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -329,6 +360,8 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
javascriptSummarySchema,
inventorySummarySchema,
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
]),
}),
z.strictObject({
@@ -362,6 +395,21 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
item: wasmViewItemSchema,
...viewResultBase,
}),
z.strictObject({
kind: z.literal("evm"),
view: evmViewRequestSchema,
item: evmViewItemSchema,
...viewResultBase,
parent_operation: z.literal("inspect_evm_interface"),
}),
z.strictObject({
kind: z.literal("managed"),
view: managedViewRequestSchema,
item: managedViewItemSchema,
...viewResultBase,
...managedViewContextSchema.shape,
parent_operation: z.literal("inspect_managed_artifact"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -427,7 +475,12 @@ export type UnsignedAnalysisView =
Extract<AnalysisViewResult, { readonly kind: "inventory" }>,
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">;
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
export const sealAnalysisView = (
@@ -472,7 +525,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -496,6 +549,15 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
return parent.evidenceId;
};
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
/** Project one selected view from authenticated parent analysis Evidence. */
export const projectAnalysisView = (
parent: AnalysisViewParent,
@@ -567,15 +629,9 @@ export const projectAnalysisView = (
const projected = projectNativeFunctionView(parent, native.data, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_wasm_artifact") {
const projected = projectWasmArtifactView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (
parent.operation === "inspect_artifact" ||
parent.operation === "inventory_artifact"
) {
const projected = projectArtifactInventoryView(parent, view);
const project = retainedViewProjectors.get(parent.operation);
if (project !== undefined) {
const projected = project(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
return err(unsupportedParent(parent));
@@ -164,6 +164,10 @@ export const projectBinaryLayoutView = (
return err(
layoutIncompatible("WASM views require inspect_wasm_artifact Evidence."),
);
if (view.kind === "evm")
return err(
layoutIncompatible("EVM views require inspect_evm_interface Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -214,6 +218,12 @@ export const projectBinaryLayoutView = (
...shared,
});
}
if (view.kind !== "page")
return err(
layoutIncompatible(
"Layout views require summary, facet, item or page selections.",
),
);
if (view.collection === "modules")
return err(
layoutIncompatible(
+145
View File
@@ -0,0 +1,145 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { evmInterfaceSchema } from "../evm/evmInterface.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
import { analysisTextPage } from "./analysisViewText.js";
/** Retained inferred candidates or exact text; offsets for text count UTF-16 code units. */
export const evmViewRequestSchema = z.strictObject({
kind: z.literal("evm"),
facet: z.enum(["functions", "bytecode_hex", "stdout", "stderr"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
export const evmViewItemSchema = z.union([
evmInterfaceSchema.shape.functions,
z.strictObject({ text: z.string(), unit: z.literal("utf16-code-units") }),
]);
/** Complete inferred interface facts without the unrequested hex or duplicated stdout. */
export const evmSummarySchema = z.strictObject({
artifact: evmInterfaceSchema.shape.artifact,
bytecode: evmInterfaceSchema.shape.bytecode.omit({ hex: true }),
evidence_kind: evmInterfaceSchema.shape.evidence_kind,
functions: evmInterfaceSchema.shape.functions,
discovery_completeness: evmInterfaceSchema.shape.discovery_completeness,
runtime_execution: evmInterfaceSchema.shape.runtime_execution,
diagnostics: evmInterfaceSchema.shape.diagnostics
.omit({ stdout: true })
.extend({
stdout_code_units: z.number().int().nonnegative(),
}),
limitations: evmInterfaceSchema.shape.limitations,
});
/** Select already authenticated producer facts; no interpreter or provider is invoked. */
export const projectEvmInterfaceView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "evm")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message: "EVM Evidence supports summary and evm views.",
},
]),
);
const parsed = evmInterfaceSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
if (
parent.subject == null ||
parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"EVM parent subject must identify the report's exact carrier path and SHA-256.",
},
]),
);
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_evm_interface" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: uniqueSorted([...parent.limitations, ...report.limitations]),
unknowns: [
"Candidates remain inferred; discovery completeness, bytecode kind, hardfork and deployment authenticity are unknown. Runtime execution was not performed.",
],
};
if (view.kind === "summary") {
const { hex: _hex, ...bytecode } = report.bytecode;
const { stdout, ...diagnostics } = report.diagnostics;
return ok({
kind: "summary",
view,
...shared,
summary: {
artifact: report.artifact,
bytecode,
evidence_kind: report.evidence_kind,
functions: report.functions,
discovery_completeness: report.discovery_completeness,
runtime_execution: report.runtime_execution,
diagnostics: { ...diagnostics, stdout_code_units: stdout.length },
limitations: report.limitations,
},
coverage: completeWithinViewCoverage(
report.functions.length,
report.functions.length,
),
});
}
if (view.facet === "functions") {
const item = report.functions.slice(view.offset, view.offset + view.limit);
return ok({
kind: "evm",
view,
item,
...shared,
coverage: pageViewCoverage(
view.offset,
item.length,
report.functions.length,
),
});
}
const text =
view.facet === "bytecode_hex"
? report.bytecode.hex
: report.diagnostics[view.facet];
const page = analysisTextPage(text, view.offset, view.limit, view.facet);
return page.ok ? ok({ kind: "evm", view, ...page.value, ...shared }) : page;
};
@@ -253,6 +253,10 @@ export const projectJavaScriptApplicationView = (
return err(
jsIncompatible("WASM views require inspect_wasm_artifact Evidence."),
);
if (view.kind === "evm")
return err(
jsIncompatible("EVM views require inspect_evm_interface Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -0,0 +1,140 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../managed/managedArtifact.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
/** Original metadata rows; offsets count entries in the returned parent collection. */
export const managedViewRequestSchema = z.strictObject({
kind: z.literal("managed"),
collection: z.enum(["references", "resources", "attributes"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
export const managedViewItemSchema = z.union([
managedArtifactInspectionSchema.shape.references,
managedArtifactInspectionSchema.shape.resources,
managedArtifactInspectionSchema.shape.attributes,
]);
/** Keep complete classification and coverage; unrequested inventories remain retained. */
export const managedSummarySchema = managedArtifactInspectionSchema
.omit({ references: true, resources: true, attributes: true })
.extend({
reported_counts: z.strictObject({
references: z.number().int().nonnegative(),
resources: z.number().int().nonnegative(),
attributes: z.number().int().nonnegative(),
}),
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
});
export const managedViewContextSchema = z.strictObject({
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
source_metadata_status:
managedArtifactInspectionSchema.shape.metadata.shape.status,
source_coverage: managedArtifactInspectionSchema.shape.coverage,
});
/** Project authenticated metadata without reading a path or invoking a provider. */
export const projectManagedArtifactView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "managed")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Managed artifact inspection supports summary and managed views.",
},
]),
);
const parsed = managedArtifactInspectionSchema.safeParse(
parent.normalizedResult,
);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
const identity_scope = {
token_identity: "build-local" as const,
requires_artifact_sha256: report.artifact.sha256,
requires_mvid: report.module?.mvid ?? null,
};
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_managed_artifact" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: uniqueSorted([...parent.limitations, ...report.limitations]),
unknowns: [
"Collection counts and pages cover producer-returned rows; metadata completeness remains the original metadata status and coverage, not an absence claim about unreturned rows.",
"Metadata tokens are build-local coordinates bound to the recorded artifact SHA-256 and module MVID; this view does not load or execute the assembly.",
...(parent.subject == null
? [
"The parent has no recorded subject; its normalized artifact identity cannot be cross-checked against a subject digest.",
]
: []),
...(identity_scope.requires_mvid === null
? [
"The module MVID is unknown; tokens cannot establish a cross-observation module match.",
]
: []),
],
};
if (view.kind === "summary") {
const { references, resources, attributes, ...summary } = report;
const reported_counts = {
references: references.length,
resources: resources.length,
attributes: attributes.length,
};
const total = references.length + resources.length + attributes.length;
return ok({
kind: "summary",
view,
...shared,
summary: { ...summary, reported_counts, identity_scope },
coverage: completeWithinViewCoverage(total, total),
});
}
const collection = report[view.collection];
const item = collection.slice(view.offset, view.offset + view.limit);
return ok({
kind: "managed",
view,
item,
...shared,
identity_scope,
source_metadata_status: report.metadata.status,
source_coverage: report.coverage,
coverage: pageViewCoverage(view.offset, item.length, collection.length),
});
};
+7 -3
View File
@@ -1,6 +1,9 @@
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
} from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
@@ -62,6 +65,7 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
@@ -95,8 +99,8 @@ export const projectAndroidApplication = (
);
const components = classified;
const limitations = [
...(!inventory.complete
? ["Source inventory pages are incomplete; absence is unknown."]
...(!hasCompleteInventoryCoverage(inventory)
? ["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.",
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.",
@@ -138,6 +138,7 @@ const inventoryEvidence = (
occurrences: sortedOccurrences,
edges: [],
provenance: [],
coverage_status: "complete",
limitations: [],
}),
},
+9 -4
View File
@@ -17,7 +17,10 @@ import {
isSwiftRuntimeLibrary,
nativeRuntimeConvention,
} from "../nativeConvention.js";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
} from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
@@ -88,6 +91,7 @@ export const appleApplicationProjectionResultSchema = z.strictObject({
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
@@ -165,9 +169,10 @@ export const projectAppleApplication = (
);
const uninventoriedImage =
rootFormat === "dmg" && inventory.occurrences.length === 1;
const complete = inventory.complete && !uninventoriedImage;
const inventoryComplete = hasCompleteInventoryCoverage(inventory);
const complete = inventoryComplete && !uninventoriedImage;
const limitations = projectionLimitations({
complete: inventory.complete,
complete: inventoryComplete,
uninventoriedImage,
roots,
bundles,
@@ -390,7 +395,7 @@ const projectionLimitations = (facts: {
readonly bridgeCandidateCoverage: AppleApplicationProjectionResult["bridge_candidate_coverage"];
}): string[] => [
...(!facts.complete
? ["Source inventory pages are incomplete; absence is unknown."]
? ["Source inventory coverage is partial; absence is unknown."]
: []),
...(facts.uninventoriedImage
? [
+12
View File
@@ -0,0 +1,12 @@
const BINARY_PLIST_MAGIC = [0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30];
const NIB_ARCHIVE_MAGIC = [
0x4e, 0x49, 0x42, 0x41, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65,
];
/** Recognize the exact binary plist version supported by the decoder, without validating its body. */
export const hasBinaryPlistSignature = (bytes: Uint8Array): boolean =>
BINARY_PLIST_MAGIC.every((byte, index) => bytes[index] === byte);
/** Recognize the serialized signature without claiming a valid NIB object table. */
export const hasNibArchiveSignature = (bytes: Uint8Array): boolean =>
NIB_ARCHIVE_MAGIC.every((byte, index) => bytes[index] === byte);
+23
View File
@@ -3,6 +3,29 @@ import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Recognized direct scalar resource fields; nested dictionaries are not inferred. */
export const appleResourceKeyFields = (
attributes: Readonly<Record<string, unknown>>,
): [string, string][] =>
Object.entries(attributes).filter(
(entry): entry is [string, string] =>
RESOURCE_KEY_FIELDS.has(entry[0]) &&
typeof entry[1] === "string" &&
entry[1].length > 0,
);
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
+13 -3
View File
@@ -3,6 +3,7 @@ import type {
DylibTreeView,
MachoSlice,
} from "./dylibResolution.js";
import { machoCpuSubtypeBase } from "./machoCpuIdentity.js";
const MAX_SYMLINK_HOPS = 32;
@@ -105,10 +106,19 @@ const COMPATIBLE_ARCHITECTURES: Readonly<Record<string, readonly string[]>> = {
export const compatibleSlice = (
slices: readonly MachoSlice[],
process: string,
process: Pick<MachoSlice, "architecture" | "cpu_type" | "cpu_subtype">,
): MachoSlice | undefined => {
for (const architecture of COMPATIBLE_ARCHITECTURES[process] ?? [process]) {
const slice = slices.find((item) => item.architecture === architecture);
for (const architecture of COMPATIBLE_ARCHITECTURES[process.architecture] ?? [
process.architecture,
]) {
const slice = slices.find(
(item) =>
item.architecture === architecture &&
(process.architecture !== "arm64e" ||
(item.cpu_type === process.cpu_type &&
machoCpuSubtypeBase(item.cpu_subtype) ===
machoCpuSubtypeBase(process.cpu_subtype))),
);
if (slice !== undefined) return slice;
}
return undefined;
+14 -7
View File
@@ -220,7 +220,10 @@ interface LoadedImage {
interface ProcessContext {
readonly view: DylibTreeView;
readonly root: string;
readonly architecture: string;
readonly processIdentity: Pick<
MachoSlice,
"architecture" | "cpu_type" | "cpu_subtype"
>;
readonly searchOverrides: readonly DyldSearchOverride[];
readonly environmentRoots: Set<string>;
readonly platforms: readonly number[];
@@ -304,7 +307,7 @@ const evaluateCandidate = async (
let outcome: Candidate["outcome"];
if (facts.status !== "parsed") outcome = facts.status;
else {
const slice = compatibleSlice(facts.slices, context.architecture);
const slice = compatibleSlice(facts.slices, context.processIdentity);
if (slice === undefined) outcome = "architecture-missing";
// Dependency commands require a dylib; generic dyld image loadability
// also admits main executables and bundles for different operations.
@@ -314,7 +317,7 @@ const evaluateCandidate = async (
context.platforms,
slice.platforms,
slice.file_type_code,
context.architecture,
context.processIdentity.architecture,
);
outcome =
platformResult === "compatible"
@@ -470,11 +473,11 @@ const resolveDependency = async (
resolved.image === null ? undefined : context.images.get(resolved.image);
const slice =
image?.status === "parsed"
? compatibleSlice(image.slices, context.architecture)
? compatibleSlice(image.slices, context.processIdentity)
: undefined;
return {
root: context.root,
architecture: context.architecture,
architecture: context.processIdentity.architecture,
loader,
via: [...chain],
...dependency,
@@ -522,7 +525,7 @@ const traceProcess = async (
const facts = context.images.get(image);
const slice =
facts?.status === "parsed"
? compatibleSlice(facts.slices, context.architecture)
? compatibleSlice(facts.slices, context.processIdentity)
: undefined;
if (slice === undefined) continue;
context.loaded.set(image, {
@@ -593,7 +596,11 @@ export const traceDylibLoading = async (
{
view,
root,
architecture: slice.architecture,
processIdentity: {
architecture: slice.architecture,
cpu_type: slice.cpu_type,
cpu_subtype: slice.cpu_subtype,
},
searchOverrides,
environmentRoots,
platforms: slice.platforms,
@@ -34,6 +34,16 @@ const connection = z.strictObject({
type InterfaceBuilderObject = z.infer<typeof objectNode>;
type InterfaceBuilderConnection = z.infer<typeof connection>;
/** UIKit runtime connection classes store their endpoints and labels under UI-prefixed keys. */
export const isUIKitRuntimeConnectionClass = (className: string): boolean =>
/^UIRuntime\w*Connection$/u.test(className);
/** The connection class selects the source archive field namespace. */
export const interfaceBuilderConnectionFieldNames = (className: string) =>
isUIKitRuntimeConnectionClass(className)
? { source: "UISource", destination: "UIDestination", label: "UILabel" }
: { source: "NSSource", destination: "NSDestination", label: "NSLabel" };
/** Parse ibtool dictionaries or compiled keyed archives into typed records. */
export const parseInterfaceBuilderRecords = (
value: unknown,
@@ -349,35 +359,41 @@ const parseKeyedArchive = (
)
) {
const controlAction = /ControlConnector/iu.test(className);
// AppKit connectors (NSNibOutletConnector, NSNibControlConnector)
// archive NSSource as the outlet owner or sending control and
// NSDestination as the outlet value or action target, so they are read
// in that order without the inversion the unprefixed fields use.
const source = firstObjectReference(
controlAction ? fields.destination : fields.source,
archivedObjectReference(fields.NSSource),
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
const uiKit = isUIKitRuntimeConnectionClass(className);
// AppKit and UIKit archive the same endpoint roles under their own
// class-specific field namespaces; the source is the outlet owner.
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = uiKit
? archivedObjectReference(fields[connectionFields.source])
: firstObjectReference(
controlAction ? fields.destination : fields.source,
archivedObjectReference(fields[connectionFields.source]),
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
kind,
source_id: source,
destination_id: firstObjectReference(
controlAction ? fields.source : fields.destination,
archivedObjectReference(fields.NSDestination),
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: firstString(
fields.label,
fields.NSLabel,
fields.selector,
fields.identifier,
fields.action,
),
destination_id: uiKit
? archivedObjectReference(fields[connectionFields.destination])
: firstObjectReference(
controlAction ? fields.source : fields.destination,
archivedObjectReference(fields[connectionFields.destination]),
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: uiKit
? firstString(fields[connectionFields.label])
: firstString(
fields.label,
fields[connectionFields.label],
fields.selector,
fields.identifier,
fields.action,
),
attributes: jsonSafeRecord(fields),
});
if (connections.length < 40_000) connections.push(parsedConnection);
+170 -11
View File
@@ -8,6 +8,136 @@ export interface FatSliceDeclaration {
readonly cpuSubtype: number;
}
export interface FatSliceRangeIssue {
readonly category: "malformed" | "unsupported";
readonly reason: string;
}
export type FatContainerHeader =
| { readonly state: "not-fat" }
| { readonly state: "needs-data"; readonly requiredBytes: number }
| { readonly state: "malformed"; readonly reason: string }
| {
readonly state: "parsed";
readonly magic: number;
readonly count: number;
readonly wide: boolean;
readonly littleEndian: boolean;
readonly tableEnd: number;
readonly slices: readonly FatSliceDeclaration[];
readonly rangeIssues: readonly (FatSliceRangeIssue | null)[];
};
export type FatContainerIdentity =
| { readonly state: "mach-o" }
| { readonly state: "not-mach-o" }
| {
readonly state: "needs-slice-header";
readonly offsets: readonly number[];
}
| {
readonly state: "malformed";
readonly category: "malformed" | "unsupported";
readonly reason: string;
};
const FAT_MAGIC = 0xcafebabe;
const FAT_MAGIC_64 = 0xcafebabf;
const FAT_CIGAM = 0xbebafeca;
const FAT_CIGAM_64 = 0xbfbafeca;
const MAX_FAT_ARCHITECTURES = 128;
const KNOWN_MACHO_CPU_TYPES: readonly number[] = [
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
];
const MACHO_HEADER_MAGICS: readonly number[] = [
0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe,
];
/** Parse a bounded FAT header and table without treating the magic alone as proof. */
export const readFatContainerHeader = (
bytes: Uint8Array,
fileSize: number,
): FatContainerHeader => {
if (bytes.byteLength < 4) return { state: "not-fat" };
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const magic = view.getUint32(0, false);
if (![FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic))
return { state: "not-fat" };
if (bytes.byteLength < 8) {
return fileSize < 8
? { state: "malformed", reason: "FAT header is truncated" }
: { state: "needs-data", requiredBytes: 8 };
}
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
const count = view.getUint32(4, littleEndian);
if (count === 0)
return {
state: "malformed",
reason: "FAT header declares no architectures",
};
if (count > MAX_FAT_ARCHITECTURES) return { state: "not-fat" };
const tableEnd = 8 + count * (wide ? 32 : 20);
if (tableEnd > fileSize) return { state: "not-fat" };
if (tableEnd > bytes.byteLength)
return { state: "needs-data", requiredBytes: tableEnd };
const declarations = readFatSliceDeclarations(bytes.subarray(8, tableEnd), {
count,
wide,
littleEndian,
});
return declarations.status === "parsed"
? {
state: "parsed",
magic,
count,
wide,
littleEndian,
tableEnd,
slices: declarations.slices,
rangeIssues: declarations.slices.map((slice) =>
inspectFatSliceRange(slice, fileSize, tableEnd),
),
}
: { state: "malformed", reason: declarations.reason };
};
/** Confirm FAT identity from architecture records and observed slice headers. */
export const classifyFatContainerIdentity = (
header: Extract<FatContainerHeader, { readonly state: "parsed" }>,
sliceHeaderAt: (offset: number) => number | null | undefined,
): FatContainerIdentity => {
const hasKnownCpu = header.slices.some(({ cpuType }) =>
KNOWN_MACHO_CPU_TYPES.includes(cpuType),
);
const invalidRange = header.rangeIssues.find(
(issue): issue is FatSliceRangeIssue => issue !== null,
);
if (hasKnownCpu)
return invalidRange === undefined
? { state: "mach-o" }
: { state: "malformed", ...invalidRange };
const validRanges = header.slices.filter(
(_slice, index) => header.rangeIssues[index] === null,
);
const missingHeaders: number[] = [];
let observedMachO = false;
for (const slice of validRanges) {
const magic = sliceHeaderAt(slice.offset);
if (magic === undefined) missingHeaders.push(slice.offset);
else if (magic !== null && MACHO_HEADER_MAGICS.includes(magic))
observedMachO = true;
}
if (observedMachO) {
return invalidRange === undefined
? { state: "mach-o" }
: { state: "malformed", ...invalidRange };
}
if (missingHeaders.length > 0)
return { state: "needs-slice-header", offsets: missingHeaders };
return { state: "not-mach-o" };
};
/** Decode FAT table entries once so artifact and native readers share identity facts. */
export const readFatSliceDeclarations = (
tableBytes: Uint8Array,
@@ -64,32 +194,61 @@ export const validateFatSlice = (
tableEnd: number,
embedded?: { readonly cpuType: number; readonly cpuSubtype: number },
): string | null => {
const { index, offset, size, alignmentExponent, cpuType, cpuSubtype } =
declaration;
const rangeIssue = inspectFatSliceRange(declaration, containerSize, tableEnd);
if (rangeIssue !== null) return rangeIssue.reason;
return embedded === undefined
? null
: validateFatSliceIdentity(declaration, embedded);
};
/** Validate table placement, container bounds, and alignment with a typed failure. */
export const inspectFatSliceRange = (
declaration: FatSliceDeclaration,
containerSize: number,
tableEnd: number,
): FatSliceRangeIssue | null => {
const { index, offset, size, alignmentExponent } = declaration;
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(size) ||
size <= 0 ||
offset < tableEnd
)
return `FAT architecture ${index} has an invalid slice range`;
return {
category: "malformed",
reason: `FAT architecture ${index} has an invalid slice range`,
};
if (offset > containerSize || size > containerSize - offset)
return `FAT architecture ${index} slice range extends beyond the file`;
return {
category: "malformed",
reason: `FAT architecture ${index} slice range extends beyond the file`,
};
if (
!Number.isInteger(alignmentExponent) ||
alignmentExponent < 0 ||
alignmentExponent > 52
)
return `FAT architecture ${index} alignment exponent ${alignmentExponent} is unsupported`;
return {
category: "unsupported",
reason: `FAT architecture ${index} alignment exponent ${alignmentExponent} is unsupported`,
};
if (offset % 2 ** alignmentExponent !== 0)
return `FAT architecture ${index} offset is not aligned to 2^${alignmentExponent}`;
if (
embedded !== undefined &&
(embedded.cpuType !== cpuType || embedded.cpuSubtype !== cpuSubtype)
)
return `FAT architecture ${index} CPU type/subtype disagrees with its Mach-O header`;
return {
category: "malformed",
reason: `FAT architecture ${index} offset is not aligned to 2^${alignmentExponent}`,
};
return null;
};
/** Validate only the identity claim after the owner has validated its range. */
export const validateFatSliceIdentity = (
declaration: FatSliceDeclaration,
embedded: { readonly cpuType: number; readonly cpuSubtype: number },
): string | null =>
embedded.cpuType === declaration.cpuType &&
embedded.cpuSubtype === declaration.cpuSubtype
? null
: `FAT architecture ${declaration.index} CPU type/subtype disagrees with its Mach-O header`;
const safeNumber = (value: bigint): number | null =>
value > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(value);
+6
View File
@@ -0,0 +1,6 @@
/** CPU subtype bits reserved for ABI/capability flags, not the base subtype. */
const CPU_SUBTYPE_CAPABILITY_MASK = 0xff000000;
/** Return the CPU subtype identity shared across capability-flag variations. */
export const machoCpuSubtypeBase = (cpuSubtype: number): number =>
cpuSubtype & ~CPU_SUBTYPE_CAPABILITY_MASK;
+6 -1
View File
@@ -2,7 +2,12 @@ import { z } from "zod";
import type { JsonValue } from "../jsonValue.js";
const MAX_PLIST_DEPTH = 128;
/**
* Maximum plist value nesting the JSON projection supports. The XML decode
* preflight shares this limit so oversized documents are rejected before any
* recursive pass rather than during one.
*/
export const MAX_PLIST_DEPTH = 128;
/** A decoded plist projected into JSON, with values JSON cannot express. */
export interface ProjectedPlistValue {
+3 -12
View File
@@ -8,12 +8,12 @@ import type {
} from "./artifactGraph.js";
import { evidenceSchema } from "./evidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
type InventorySet,
} from "./artifactInventoryEvidence.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJson } from "./comparisonSemantics.js";
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "./zipPackageFormat.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const comparisonStatusSchema = z.enum([
@@ -104,10 +104,8 @@ export const compareArtifacts = (
const right = parseArtifactInventoryEvidence(rightEvidence);
const leftComplete = left.inventory.complete;
const rightComplete = right.inventory.complete;
const leftCovered =
leftComplete && !hasCoverageLimitation(left.inventory.limitations);
const rightCovered =
rightComplete && !hasCoverageLimitation(right.inventory.limitations);
const leftCovered = hasCompleteInventoryCoverage(left.inventory);
const rightCovered = hasCompleteInventoryCoverage(right.inventory);
const limitations = [
...left.inventory.limitations.map((item) => `Left: ${item}`),
...right.inventory.limitations.map((item) => `Right: ${item}`),
@@ -433,13 +431,6 @@ const summarize = (
};
};
const hasCoverageLimitation = (limitations: readonly string[]): boolean =>
limitations.some(
(limitation) =>
limitation !== ZIP_NON_ENTRY_TAIL_LIMITATION &&
!/integrity contradiction\(s\) were recorded/u.test(limitation),
);
// Differing manifest root digests prove a root content change even when node
// details are unavailable. Fold that fact into an existing root row so one
// logical path keeps one classification.
+35
View File
@@ -0,0 +1,35 @@
/**
* Aggregate decompression ceiling for one archive-backed artifact operation.
*
* A ZIP/APK/IPA/MSIX member is attacker-controlled and can expand far beyond the
* archive that carries it, so a small input can drive unbounded decompression
* work during inventory hashing and extraction. A fixed per-entry byte cap is
* the wrong shape: it rejects legitimately large members inside large packages
* and cannot distinguish a bomb from a large file.
*
* The ceiling instead scales with the archive's own compressed size, so a large
* package keeps a proportionally large budget while a small archive cannot
* amplify into unbounded CPU time or disk writes. The floor keeps ordinary
* small archives usable, and the ratio sits above real-world artifact
* compression (measured ~3:1-15:1, up to ~350:1 for pure text) but below the
* DEFLATE ceiling (~1030:1) that a single-entry bomb relies on.
*/
/** Allow a whole archive to expand by this factor before decompression is refused. */
export const ARTIFACT_DECOMPRESSION_RATIO = 500;
/**
* Smallest aggregate budget granted to any archive, so small packages stay usable.
* This floor keeps ordinary archives extractable and stays well above the largest
* single members real packages carry; it is not a per-entry cap.
*/
export const MINIMUM_ARTIFACT_DECOMPRESSION_BYTES = 256 * 1024 * 1024;
/** Largest total decompressed bytes allowed for an archive of this compressed size. */
export const artifactDecompressionBudgetBytes = (
compressedBytes: number,
): number =>
Math.max(
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
Math.floor(compressedBytes) * ARTIFACT_DECOMPRESSION_RATIO,
);
+17
View File
@@ -191,6 +191,12 @@ 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"]);
export type ArtifactInventoryCoverage = z.infer<
typeof artifactInventoryCoverageSchema
>;
/** Complete inventory observation containing the stable artifact graph. */
export const artifactInventoryResultSchema = z.object({
manifest: artifactGraphManifestSchema,
@@ -201,8 +207,19 @@ export const artifactInventoryResultSchema = z.object({
integrity_contradictions: z.array(integrityContradictionSchema).default([]),
ines: inesInventorySchema.optional(),
limitations: z.array(z.string()),
/** Optional only for persisted inventory Evidence written before this field. */
coverage_status: artifactInventoryCoverageSchema.optional(),
});
/** Current inventory producers always classify the coverage they examined. */
export const artifactInventoryOutputSchema =
artifactInventoryResultSchema.extend({
coverage_status: artifactInventoryCoverageSchema,
});
export type ArtifactInventoryOutput = z.infer<
typeof artifactInventoryOutputSchema
>;
/** One safely materialized artifact beneath caller-approved output root. */
const extractedArtifactSchema = z.object({
artifact_id: artifactIdSchema,
+2 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import {
artifactInventoryOutputSchema,
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "./artifactGraph.js";
@@ -120,7 +121,7 @@ export const artifactInspectionOutputSchema =
artifactInspectionResultSchema.shape.substeps.element.safeExtend({
evidence: evidenceSchema.safeExtend({
normalized_result:
artifactInventoryResultSchema.and(jsonValueSchema),
artifactInventoryOutputSchema.and(jsonValueSchema),
}),
}),
)
+39 -5
View File
@@ -1,5 +1,6 @@
import {
artifactInventoryResultSchema,
type ArtifactInventoryCoverage,
type ArtifactInventoryResult,
type ArtifactNode,
type ArtifactOccurrence,
@@ -17,6 +18,7 @@ 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";
/** Complete or partially assembled inventory used by comparison workflows. */
export interface InventorySet {
@@ -26,9 +28,16 @@ export interface InventorySet {
readonly edges: readonly ArtifactInventoryResult["edges"][number][];
readonly integrityContradictions: readonly IntegrityContradiction[];
readonly limitations: readonly string[];
/** True when merged node, occurrence, and edge counts match the manifest. */
readonly complete: boolean;
readonly coverage_status: 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";
export interface ParsedInventorySet {
readonly evidence: readonly Evidence[];
readonly inventory: InventorySet;
@@ -123,6 +132,10 @@ 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 nodes = new Map<string, ArtifactNode>();
const occurrences = new Map<string, ArtifactOccurrence>();
@@ -152,11 +165,12 @@ const assembleInventoryResults = (
for (const edge of page.edges)
mergeExact(edges, edge.edge_id, edge, "edge");
}
const inventory = orderedInventory(first, pages, {
nodes,
occurrences,
edges,
});
const inventory = orderedInventory(
first,
pages,
{ nodes, occurrences, edges },
coverageStatus,
);
if (inventory.complete) validateCompleteInventory(inventory);
return inventory;
};
@@ -172,6 +186,7 @@ const orderedInventory = (
ArtifactInventoryResult["edges"][number]
>;
},
coverageStatus: ArtifactInventoryCoverage,
): InventorySet => {
const nodes = [...values.nodes.values()].sort((left, right) =>
compareUnicodeCodePoints(left.artifact_id, right.artifact_id),
@@ -195,9 +210,28 @@ const orderedInventory = (
nodes.length === first.manifest.node_count &&
occurrences.length === first.manifest.occurrence_count &&
edges.length === first.manifest.edge_count,
coverage_status: coverageStatus,
};
};
const resolveInventoryCoverageStatus = (
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 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,
);
const validateCompleteInventory = (inventory: InventorySet): void => {
const nodeIds = new Set(inventory.nodes.map(({ artifact_id: id }) => id));
const occurrenceIds = new Set(
+2
View File
@@ -1,4 +1,5 @@
import type {
ArtifactInventoryCoverage,
ArtifactInventoryResult,
ArtifactNode,
IntegrityContradiction,
@@ -6,6 +7,7 @@ import type {
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly coverage_status: ArtifactInventoryCoverage;
readonly manifest: ArtifactInventoryResult["manifest"];
readonly nodes: readonly ArtifactNode[];
readonly occurrences: ArtifactInventoryResult["occurrences"];
+10 -3
View File
@@ -5,9 +5,16 @@ export const elf = (
machine: number,
): Buffer => {
const bytes = Buffer.alloc(class_ === 1 ? 52 : 64);
bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian]);
if (endian === 1) bytes.writeUInt16LE(machine, 18);
else bytes.writeUInt16BE(machine, 18);
bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian, 1]);
if (endian === 1) {
bytes.writeUInt16LE(machine, 18);
bytes.writeUInt32LE(1, 20);
bytes.writeUInt16LE(class_ === 1 ? 52 : 64, class_ === 1 ? 40 : 52);
} else {
bytes.writeUInt16BE(machine, 18);
bytes.writeUInt32BE(1, 20);
bytes.writeUInt16BE(class_ === 1 ? 52 : 64, class_ === 1 ? 40 : 52);
}
return bytes;
};
+4
View File
@@ -7,10 +7,14 @@ const header = (little: boolean, bits: 32 | 64 = 32): Buffer => {
if (little) {
bytes.writeUInt16LE(2, 16);
bytes.writeUInt16LE(8, 18);
bytes.writeUInt32LE(1, 20);
bytes.writeUInt16LE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52);
bytes.writeUInt32LE(0x70001001, bits === 32 ? 36 : 48);
} else {
bytes.writeUInt16BE(2, 16);
bytes.writeUInt16BE(8, 18);
bytes.writeUInt32BE(1, 20);
bytes.writeUInt16BE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52);
bytes.writeUInt32BE(0x70001001, bits === 32 ? 36 : 48);
}
return bytes;
+102
View File
@@ -0,0 +1,102 @@
import { describe, expect, it } from "vitest";
import { parseExecutableHeader } from "./binaryTarget.js";
const header = (
little: boolean,
bits: 32 | 64 = 32,
flags = 0x5,
type = 2,
machine = 243,
): 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(type, 16);
bytes.writeUInt16LE(machine, 18);
bytes.writeUInt32LE(1, 20);
bytes.writeUInt16LE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52);
bytes.writeUInt32LE(flags, bits === 32 ? 36 : 48);
} else {
bytes.writeUInt16BE(type, 16);
bytes.writeUInt16BE(machine, 18);
bytes.writeUInt32BE(1, 20);
bytes.writeUInt16BE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52);
bytes.writeUInt32BE(flags, bits === 32 ? 36 : 48);
}
return bytes;
};
describe("RISC-V ELF header boundaries", () => {
it.each([
[true, 32],
[false, 32],
[true, 64],
[false, 64],
] as const)(
"retains class, endian, e_type and e_flags (little=%s, class=%s)",
(little, bits) => {
const parsed = parseExecutableHeader(header(little, bits), "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toEqual({
format: "elf",
architecture: "riscv",
availableArchitectures: ["riscv"],
riscv: {
elfClass: bits,
byteOrder: little ? "little" : "big",
type: 2,
flags: 0x5,
},
});
},
);
it("reads ELF64 flags at their own offset", () => {
const bytes = header(true, 64);
bytes.writeUInt32LE(0xdeadbeef, 36);
bytes.writeUInt32LE(0x00000014, 48);
const parsed = parseExecutableHeader(bytes, "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toMatchObject({
architecture: "riscv",
riscv: { elfClass: 64, flags: 0x14 },
});
});
it("does not attach ELF metadata to a family that declares none", () => {
const parsed = parseExecutableHeader(header(true, 64, 0x5, 2, 62), "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toEqual({
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
});
});
it("rejects a truncated header before reading flags", () => {
const parsed = parseExecutableHeader(header(true).subarray(0, 39), "x64");
expect(parsed).toEqual({
ok: false,
error:
"truncated ELF header: an ELF32 header needs 52 bytes; the file has 39",
});
});
it("does not turn invalid byte order into little-endian RISC-V", () => {
const bytes = header(true);
bytes[5] = 0;
expect(parseExecutableHeader(bytes, "x64")).toEqual({
ok: false,
error: "unsupported ELF endianness",
});
});
it("keeps an unknown e_machine outside the recognized family set", () => {
expect(parseExecutableHeader(header(true, 32, 0x5, 2, 244), "x64")).toEqual(
{
ok: false,
error: "unsupported ELF architecture",
},
);
});
});
+58 -24
View File
@@ -26,6 +26,13 @@ describe("executable header parsing", () => {
expect(result.ok && result.value).toMatchObject({ format, architecture });
});
it("retains ELF32 x86-64 identity for the x32 ABI", () => {
expect(parseExecutableHeader(elf(1, 1, 62), "x64")).toMatchObject({
ok: true,
value: { format: "elf", architecture: "x86_64" },
});
});
it("distinguishes native PE applications, DLLs, and managed assemblies", () => {
const application = parseExecutableHeader(pe(0x8664), "x64");
const library = parseExecutableHeader(pe(0x8664, 64, 0x2002), "x64");
@@ -176,42 +183,53 @@ describe("executable header completeness", () => {
expect(reason(header, 132)).toBeNull();
});
it("rejects a FAT file whose host slice extends past the file", () => {
it("rejects an invalid FAT slice even when another host slice is valid", () => {
const bytes = fat([0x01000007, 0x0100000c]);
bytes.writeUInt32BE(4096, 8 + 20 + 8);
bytes.writeUInt32BE(64, 8 + 20 + 12);
expect(reason(bytes, 4100)).toBe(
"truncated FAT slice: the arm64 slice ends at byte 4160; the file has 4100",
"FAT architecture 1 slice range extends beyond the file",
);
expect(reason(bytes, 4160)).toBeNull();
// Only the slice REA would analyze must be present.
expect(parseExecutableHeader(bytes, "x64", 4100).ok).toBe(true);
expect(parseExecutableHeader(bytes, "x64", 4100)).toMatchObject({
ok: false,
error: "FAT architecture 1 slice range extends beyond the file",
});
});
it.each([
{
label: "empty range",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(bytes, wide, little, "size", 0n),
error: "FAT slice for arm64 is shorter than its Mach-O header",
corruptRange: (bytes: Buffer, wide: boolean, littleEndian: boolean) =>
setFatSliceRange(bytes, {
wide,
littleEndian,
field: "size",
value: 0n,
}),
error: "FAT architecture 1 has an invalid slice range",
},
{
label: "table overlap",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(
bytes,
corruptRange: (bytes: Buffer, wide: boolean, littleEndian: boolean) =>
setFatSliceRange(bytes, {
wide,
little,
"offset",
BigInt(8 + 2 * (wide ? 32 : 20) - 1),
),
error: "FAT slice for arm64 overlaps the architecture table",
littleEndian,
field: "offset",
value: BigInt(8 + 2 * (wide ? 32 : 20) - 1),
}),
error: "FAT architecture 1 has an invalid slice range",
},
{
label: "undersized 64-bit header",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(bytes, wide, little, "size", 31n),
corruptRange: (bytes: Buffer, wide: boolean, littleEndian: boolean) =>
setFatSliceRange(bytes, {
wide,
littleEndian,
field: "size",
value: 31n,
}),
error: "FAT slice for arm64 is shorter than its Mach-O header",
},
])("rejects a selected FAT slice with $label", ({ corruptRange, error }) => {
@@ -234,11 +252,23 @@ describe("executable header completeness", () => {
it("uses a 28-byte minimum for a selected 32-bit Mach-O header", () => {
const exactHeader = fat([7]);
setFatSliceRange(exactHeader, false, false, "size", 28n, 0);
setFatSliceRange(exactHeader, {
wide: false,
littleEndian: false,
field: "size",
value: 28n,
index: 0,
});
expect(parseExecutableHeader(exactHeader, "ia32").ok).toBe(true);
const undersizedHeader = Buffer.from(exactHeader);
setFatSliceRange(undersizedHeader, false, false, "size", 27n, 0);
setFatSliceRange(undersizedHeader, {
wide: false,
littleEndian: false,
field: "size",
value: 27n,
index: 0,
});
expect(parseExecutableHeader(undersizedHeader, "ia32")).toMatchObject({
ok: false,
@@ -249,12 +279,16 @@ describe("executable header completeness", () => {
const setFatSliceRange = (
bytes: Buffer,
wide: boolean,
littleEndian: boolean,
field: "offset" | "size",
value: bigint,
index = 1,
options: {
readonly wide: boolean;
readonly littleEndian: boolean;
readonly field: "offset" | "size";
readonly value: bigint;
readonly index?: number;
},
): void => {
const { wide, littleEndian, field, value } = options;
const index = options.index ?? 1;
const entry = 8 + index * (wide ? 32 : 20);
const fieldOffset = entry + (field === "offset" ? 8 : wide ? 16 : 12);
if (wide) {
+136 -102
View File
@@ -1,11 +1,19 @@
import type {
BinaryArchitecture,
ElfFamilyMetadata,
HeaderArchitecture,
MipsElfMetadata,
RiscvElfMetadata,
UniversalMachOSlice,
} from "./binaryTargetTypes.js";
import { err, ok, type Result } from "./result.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
import { readElfFixedHeader } from "./elfFixedHeader.js";
import { observeMzWindowsHeader, parseDosMzHeader } from "./dosMz.js";
import { decodePeMachine } from "./peMachine.js";
import {
classifyFatContainerIdentity,
readFatContainerHeader,
} from "./apple/machoContainer.js";
/** Format and architecture facts recovered from an executable header. */
export type ExecutableMetadata =
@@ -15,31 +23,28 @@ export type ExecutableMetadata =
readonly availableArchitectures: readonly "mips"[];
readonly mips: MipsElfMetadata;
}
| {
readonly format: "elf";
readonly architecture: "riscv";
readonly availableArchitectures: readonly "riscv"[];
readonly riscv: RiscvElfMetadata;
}
| {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
readonly architecture: HeaderArchitecture;
readonly availableArchitectures: readonly HeaderArchitecture[];
readonly universalSlice?: never;
}
| {
readonly format: "mach-o-universal";
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
readonly architecture: HeaderArchitecture;
readonly availableArchitectures: readonly HeaderArchitecture[];
readonly universalSlice: UniversalMachOSlice;
}
| {
readonly format: "pe";
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
readonly architecture: HeaderArchitecture;
readonly availableArchitectures: readonly HeaderArchitecture[];
readonly executableRole:
| "application"
| "shared-library"
@@ -55,6 +60,7 @@ export const parseExecutableHeader = (
bytes: Buffer,
hostArchitecture: NodeJS.Architecture,
fileSize = bytes.length,
mzWindowsHeaderSignature?: Buffer,
): Result<ExecutableMetadata, string> => {
if (
bytes.length >= 4 &&
@@ -62,13 +68,14 @@ export const parseExecutableHeader = (
)
return parseElf(bytes, fileSize);
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a)
return parseMz(bytes, fileSize);
return parseMz(bytes, fileSize, mzWindowsHeaderSignature);
if (bytes.length < 8) return err("truncated or unsupported binary header");
const magic = bytes.readUInt32BE(0);
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return parseThinMachO(bytes, magic, fileSize);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return parseFatMachO(bytes, magic, hostArchitecture, fileSize);
const fatHeader = readFatContainerHeader(bytes, fileSize);
if (fatHeader.state !== "not-fat")
return parseFatMachO(bytes, hostArchitecture, fatHeader);
return err("unsupported binary format");
};
@@ -102,109 +109,120 @@ const parseThinMachO = (
const parseFatMachO = (
bytes: Buffer,
magic: number,
host: NodeJS.Architecture,
fileSize: number,
header: Exclude<
ReturnType<typeof readFatContainerHeader>,
{ state: "not-fat" }
>,
): Result<ExecutableMetadata, string> => {
const little = magic === 0xbebafeca || magic === 0xbfbafeca;
const is64 = magic === 0xcafebabf || magic === 0xbfbafeca;
if (bytes.length < 8) return err("truncated FAT header");
const read = (offset: number): number =>
little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
const count = read(4);
const entrySize = is64 ? 32 : 20;
if (count === 0 || count > 128 || bytes.length < 8 + count * entrySize)
if (header.state === "needs-data")
return err("truncated or invalid FAT architecture table");
const architectures: Exclude<BinaryArchitecture, "mips">[] = [];
if (header.state === "malformed") return err(header.reason);
const identityError = fatIdentityError(bytes, header);
if (identityError !== null) return err(identityError);
const architectures: HeaderArchitecture[] = [];
const slices = new Map<
Exclude<BinaryArchitecture, "mips">,
{ readonly offset: bigint; readonly size: bigint }
HeaderArchitecture,
{ readonly offset: number; readonly size: number }
>();
for (let index = 0; index < count; index += 1) {
const entry = 8 + index * entrySize;
const architecture = machArchitecture(read(entry));
for (const declaration of header.slices) {
const architecture = machArchitecture(declaration.cpuType);
if (architecture === undefined || architectures.includes(architecture))
continue;
architectures.push(architecture);
const offset = is64
? little
? bytes.readBigUInt64LE(entry + 8)
: bytes.readBigUInt64BE(entry + 8)
: BigInt(read(entry + 8));
const size = is64
? little
? bytes.readBigUInt64LE(entry + 16)
: bytes.readBigUInt64BE(entry + 16)
: BigInt(read(entry + 12));
slices.set(architecture, { offset, size });
slices.set(architecture, {
offset: declaration.offset,
size: declaration.size,
});
}
const preferred =
host === "arm64"
? "arm64"
: host === "x64"
? "x86_64"
: host === "ia32"
? "x86"
: host === "arm"
? "arm"
: undefined;
const preferred = fatHostArchitecture(host);
const slice = preferred === undefined ? undefined : slices.get(preferred);
if (preferred === undefined || slice === undefined)
return err(`FAT binary has no host-compatible ${host} architecture`);
const tableEnd = BigInt(8 + count * entrySize);
if (slice.offset < tableEnd)
return err(`FAT slice for ${preferred} overlaps the architecture table`);
const minimumHeaderSize =
preferred === "arm64" || preferred === "x86_64" ? 32n : 28n;
preferred === "arm64" || preferred === "x86_64" ? 32 : 28;
if (slice.size < minimumHeaderSize)
return err(`FAT slice for ${preferred} is shorter than its Mach-O header`);
const sliceEnd = slice.offset + slice.size;
if (sliceEnd > BigInt(fileSize))
return err(
`truncated FAT slice: the ${preferred} slice ends at byte ${sliceEnd}; the file has ${fileSize}`,
);
const sliceOffset = Number(slice.offset);
const sliceSize = Number(slice.size);
if (!Number.isSafeInteger(sliceOffset) || !Number.isSafeInteger(sliceSize))
return err(`FAT slice for ${preferred} exceeds addressable byte bounds`);
return ok({
format: "mach-o-universal",
architecture: preferred,
availableArchitectures: architectures,
universalSlice: { offset: sliceOffset, size: sliceSize },
universalSlice: { offset: slice.offset, size: slice.size },
});
};
const fatHostArchitecture = (
host: NodeJS.Architecture,
): HeaderArchitecture | undefined => {
switch (host) {
case "arm64":
return "arm64";
case "x64":
return "x86_64";
case "ia32":
return "x86";
case "arm":
return "arm";
default:
return undefined;
}
};
const fatIdentityError = (
bytes: Buffer,
header: Extract<
ReturnType<typeof readFatContainerHeader>,
{ state: "parsed" }
>,
): string | null => {
const identity = classifyFatContainerIdentity(header, (offset) => {
if (offset >= bytes.length) return undefined;
if (offset + 4 > bytes.length) return null;
return bytes.readUInt32BE(offset);
});
if (identity.state === "needs-slice-header")
return "FAT slice identity is outside the bounded prefix";
if (identity.state === "not-mach-o")
return "FAT table does not identify a Mach-O image";
if (identity.state === "malformed") return identity.reason;
return null;
};
const parseElf = (
bytes: Buffer,
fileSize: number,
): Result<ExecutableMetadata, string> => {
if (bytes.length < 6) return err("truncated ELF header");
if (bytes[4] !== 1 && bytes[4] !== 2) return err("unsupported ELF class");
const little = bytes[5] === 1;
if (!little && bytes[5] !== 2) return err("unsupported ELF endianness");
const headerSize = bytes[4] === 1 ? 52 : 64;
if (bytes.length < headerSize)
return err(
`truncated ELF header: an ELF${bytes[4] === 1 ? 32 : 64} header needs ${headerSize} bytes; the file has ${fileSize}`,
);
const fixedHeader = readElfFixedHeader(bytes, fileSize);
if (!fixedHeader.ok) return fixedHeader;
const { elfClass, byteOrder } = fixedHeader.value;
const little = byteOrder === "little";
const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18);
const architecture = elfArchitecture(machine);
if (architecture === undefined) return err("unsupported ELF architecture");
if (architecture === "mips")
return ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
mips: {
elfClass: bytes[4] === 1 ? 32 : 64,
byteOrder: little ? "little" : "big",
type: little ? bytes.readUInt16LE(16) : bytes.readUInt16BE(16),
flags: little
? bytes.readUInt32LE(bytes[4] === 1 ? 36 : 48)
: bytes.readUInt32BE(bytes[4] === 1 ? 36 : 48),
},
});
if (architecture === "mips" || architecture === "riscv") {
const flagsOffset = elfClass === 32 ? 36 : 48;
const metadata: ElfFamilyMetadata = {
elfClass,
byteOrder: little ? "little" : "big",
type: little ? bytes.readUInt16LE(16) : bytes.readUInt16BE(16),
flags: little
? bytes.readUInt32LE(flagsOffset)
: bytes.readUInt32BE(flagsOffset),
};
return architecture === "mips"
? ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
mips: metadata,
})
: ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
riscv: metadata,
});
}
return ok({
format: "elf",
architecture,
@@ -215,17 +233,33 @@ const parseElf = (
const parseMz = (
bytes: Buffer,
fileSize: number,
signatureAtOffset?: Buffer,
): Result<ExecutableMetadata, string> => {
const offset = mzWindowsHeaderOffset(bytes);
if (offset !== null) {
const windowsHeader = observeMzWindowsHeader(
bytes,
fileSize,
signatureAtOffset,
);
if (
windowsHeader.state === "header-needed" ||
windowsHeader.state === "signature-needed"
)
return err(
"Windows new-header pointer or signature is outside the bounded prefix",
);
if (windowsHeader.state === "declared") {
const { offset } = windowsHeader;
if (offset < 64 || offset > bytes.length - 24)
return err("invalid or truncated Windows executable header in MZ image");
const signature = bytes.toString("ascii", offset, offset + 2);
if (["NE", "LE", "LX"].includes(signature))
return err(`unsupported ${signature} executable in MZ image`);
if (["NE", "LE", "LX"].includes(windowsHeader.signature))
return err(
`unsupported ${windowsHeader.signature} executable in MZ image`,
);
if (windowsHeader.signature !== "PE")
return err("invalid or truncated Windows executable header in MZ image");
return parsePeRecord(bytes.subarray(offset));
}
const parsed = parseDosMzHeader(bytes, fileSize);
const parsed = parseDosMzHeader(bytes, fileSize, signatureAtOffset);
return parsed.ok
? ok({
format: "dos-mz",
@@ -299,9 +333,7 @@ const peManagedStatus = (
);
};
const machArchitecture = (
cpu: number,
): Exclude<BinaryArchitecture, "mips"> | undefined => {
const machArchitecture = (cpu: number): HeaderArchitecture | undefined => {
switch (cpu) {
case 7:
return "x86";
@@ -327,6 +359,8 @@ const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
return "arm";
case 183:
return "arm64";
case 243: // EM_RISCV: XLEN, byte order and e_flags remain separate ELF facts.
return "riscv";
}
return undefined;
};
+48 -7
View File
@@ -5,15 +5,44 @@ export const BINARY_ARCHITECTURES = [
"arm",
"arm64",
"mips",
"riscv",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
export interface MipsElfMetadata {
/**
* ELF header facts for a family whose ISA and ABI are not established by the
* family name alone. Consumers admit a lane from these declarations rather than
* re-reading the header.
*/
export interface ElfFamilyMetadata {
readonly elfClass: 32 | 64;
readonly byteOrder: "little" | "big";
readonly type: number;
readonly flags: number;
}
/** Families whose parsed target variant carries `ElfFamilyMetadata`. */
export const ELF_METADATA_ARCHITECTURES = [
"mips",
"riscv",
] as const satisfies readonly BinaryArchitecture[];
export type ElfMetadataArchitecture =
(typeof ELF_METADATA_ARCHITECTURES)[number];
/** Families whose ISA and ABI need a separate ELF declaration to be admitted. */
export const isElfMetadataArchitecture = (
architecture: BinaryArchitecture,
): architecture is ElfMetadataArchitecture =>
(ELF_METADATA_ARCHITECTURES as readonly string[]).includes(architecture);
/** Recognized family with no ELF metadata member; the header alone is the fact. */
export type HeaderArchitecture = Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>;
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
export interface MipsElfMetadata extends ElfFamilyMetadata {
/** Undefined until inspected; null means no ABI record was observed. */
readonly abiFlags?: MipsAbiFlags | null;
/** Unavailable declaration sources; missing records there remain unknown. */
@@ -44,6 +73,12 @@ export interface MipsAbiFlags {
readonly flags2: number;
}
/**
* ELF class and flags retain the width and ABI declarations used by this lane.
* ISA extensions in `.riscv.attributes` are not inspected by this header parser.
*/
export type RiscvElfMetadata = ElfFamilyMetadata;
/** Byte range of the selected slice inside its universal Mach-O container. */
export interface UniversalMachOSlice {
readonly offset: number;
@@ -67,11 +102,8 @@ type NonExecutableMetadata = {
type ExecutableTarget = BinaryTargetIdentity & {
readonly kind: "executable";
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
readonly architecture: HeaderArchitecture;
readonly availableArchitectures: readonly HeaderArchitecture[];
};
/**
@@ -88,6 +120,15 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "elf";
readonly architecture: "riscv";
readonly availableArchitectures: readonly "riscv"[];
readonly riscv: RiscvElfMetadata;
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly universalSlice?: never;
+4
View File
@@ -19,6 +19,8 @@ describe("browser observation contracts", () => {
"https://*.example.com",
"https://example.com/path",
"https://example.com/?token=secret",
"https://example.com/?",
"https://example.com/#",
"https://user:pass@example.com",
"file:///tmp/page.html",
])
@@ -37,6 +39,8 @@ describe("browser observation contracts", () => {
"http://192.168.1.2:9222",
"https://127.0.0.1:9222",
"http://127.0.0.1:9222/json/list",
"http://127.0.0.1:9222/?",
"http://127.0.0.1:9222/#",
"http://user:pass@127.0.0.1:9222",
])
expect(browserEndpointSchema.safeParse(value).success, value).toBe(false);
+16 -9
View File
@@ -1,5 +1,7 @@
import { z } from "zod";
import { urlDeclaresQueryOrFragment } from "./urlComponents.js";
const parseExactOrigin = (value: string): string | undefined => {
let url: URL;
try {
@@ -15,8 +17,7 @@ const parseExactOrigin = (value: string): string | undefined => {
url.username !== "" ||
url.password !== "" ||
url.pathname !== "/" ||
url.search !== "" ||
url.hash !== ""
urlDeclaresQueryOrFragment(url)
)
return undefined;
return url.origin;
@@ -63,8 +64,7 @@ export const browserEndpointSchema = z
url.username !== "" ||
url.password !== "" ||
url.pathname !== "/" ||
url.search !== "" ||
url.hash !== ""
urlDeclaresQueryOrFragment(url)
) {
context.addIssue({
code: "custom",
@@ -105,7 +105,7 @@ const inspectWebPageInputFacts = {
const inspectWebPageWithoutSourceSchema = z.strictObject({
...inspectWebPageInputFacts,
include_script_sources: z.literal(false).default(false),
include_script_sources: z.literal(false).optional().default(false),
});
const inspectWebPageWithSourceShapeSchema = z.strictObject({
@@ -134,10 +134,17 @@ export const inspectWebPageWithSourceInputSchema =
inspectWebPageWithSourceShapeSchema.superRefine(refineInspectWebPageInput);
/** Caller-visible schema for one passive inspection. */
export const inspectWebPageInputSchema = z.union([
inspectWebPageWithoutSourceSchema.superRefine(refineInspectWebPageInput),
inspectWebPageWithSourceInputSchema,
]);
export const inspectWebPageInputSchema = z.discriminatedUnion(
"include_script_sources",
[
inspectWebPageWithoutSourceSchema.superRefine(refineInspectWebPageInput),
inspectWebPageWithSourceShapeSchema
.extend({
include_script_sources: z.literal(true),
})
.superRefine(refineInspectWebPageInput),
],
);
export type ListBrowserTargetsInput = z.infer<
typeof listBrowserTargetsInputSchema
+2
View File
@@ -3,6 +3,7 @@ import { browserNetworkContentSelectionValuesSchema } from "./browserNetworkEvid
import {
browserScenarioCompletenessSchema,
browserScenarioEventFamilySchema,
browserScenarioEventSchema,
browserScenarioStepSchema,
} from "./browserScenarioCaptureValues.js";
@@ -22,6 +23,7 @@ export const browserScenarioCaptureSchema = z
action_count: z.number().int().min(1),
secret_references: z.array(z.string().min(1)),
network_content: browserNetworkContentSelectionValuesSchema,
event_families: z.array(browserScenarioEventFamilySchema).optional(),
}),
duration_ms: z.number().int().min(0),
steps: z.array(browserScenarioStepSchema).min(1),
@@ -119,6 +119,21 @@ export const browserStepArtifactsSchema = z.strictObject({
});
export type BrowserStepArtifacts = z.infer<typeof browserStepArtifactsSchema>;
/** Event families a scenario can select for capture. */
export const browserScenarioEventFamilySchema = z.enum([
"console",
"page-errors",
"network",
"websockets",
"frames",
"workers",
"popups",
"downloads",
]);
export type BrowserScenarioEventFamily = z.infer<
typeof browserScenarioEventFamilySchema
>;
const eventBase = {
sequence: z.number().int().min(1),
step_index: z.number().int().min(0),
+90
View File
@@ -62,6 +62,7 @@ const networkCapture = (sourceSequence: number, receiptStep: number) => {
response_body: false,
header_values: false,
},
event_families: ["network"],
},
events: { items: events, retained: 2, dropped: 0 },
});
@@ -146,6 +147,94 @@ it("reports content-selection mismatch as unknown instead of a website change",
).toBe(false);
});
it("reports event-family mismatch and legacy selection as unknown", () => {
const consoleOnly = scenarioCapture({});
const withFamilies = (
capture: BrowserScenarioCapture,
families: BrowserScenarioCapture["scenario"]["event_families"],
) =>
browserScenarioCaptureSchema.parse({
...capture,
scenario: { ...capture.scenario, event_families: families },
});
const compare = (
before: BrowserScenarioCapture,
after: BrowserScenarioCapture,
) =>
compareBrowserScenarios(
compareBrowserScenariosInputSchema.parse({
before_scenario: before,
after_scenario: after,
}),
);
const eventDiffs = (compared: ReturnType<typeof compare>) =>
compared.steps
.flatMap((step) => step.artifact_diffs)
.filter(({ artifact }) => artifact === "events");
const widened = withFamilies(consoleOnly, ["page-errors", "console"]);
const mismatched = compare(consoleOnly, widened);
expect(mismatched.overall_status).toBe("unknown");
expect(eventDiffs(mismatched)).toContainEqual(
expect.objectContaining({
status: "unknown",
before_state: "captured",
after_state: "captured",
reason: expect.stringContaining(
"Event family selections differ (console before, console, page-errors after)",
),
}),
);
expect(
compare(
withFamilies(consoleOnly, ["console", "page-errors"]),
withFamilies(consoleOnly, ["page-errors", "console"]),
).overall_status,
).toBe("unchanged");
const legacy = withFamilies(consoleOnly, undefined);
expect(legacy.scenario.event_families).toBeUndefined();
for (const [before, after] of [
[legacy, consoleOnly],
[legacy, legacy],
] as const)
expect(eventDiffs(compare(before, after))).toContainEqual(
expect.objectContaining({
status: "unknown",
reason: expect.stringContaining("Event family selection is unknown"),
}),
);
expect(
compareBrowserScenariosInputSchema.safeParse({
before_scenario: {
...consoleOnly,
scenario: { ...consoleOnly.scenario, event_families: ["dialogs"] },
},
after_scenario: consoleOnly,
}).success,
).toBe(false);
const quiet = browserScenarioCaptureSchema.parse({
...withFamilies(consoleOnly, []),
events: { retained: 0, dropped: 0, items: [] },
});
const differentEvents = compare(quiet, widened);
expect(differentEvents.overall_status).toBe("unknown");
expect(eventDiffs(differentEvents).map(({ status }) => status)).toEqual([
"unknown",
"unknown",
]);
const both = eventDiffs(compare(networkCapture(1, 0), consoleOnly));
expect(both).toContainEqual(
expect.objectContaining({
reason: expect.stringMatching(
/Event family selections differ.*content selections differ/u,
),
}),
);
});
describe("browser scenario comparison", () => {
it("records canonical literal normalization and ignores declared volatile fields", () => {
const before = scenarioCapture({
@@ -485,6 +574,7 @@ const scenarioCapture = (
response_body: false,
header_values: false,
},
event_families: ["console"],
},
duration_ms: options.elapsedMs ?? 10,
steps: [
+13 -1
View File
@@ -5,6 +5,7 @@ import {
artifactEvidenceState,
captured,
eventEvidenceState,
eventFamilyCoverageReason,
eventsFor,
networkContentCoverageReason,
screenshotProjection,
@@ -332,7 +333,7 @@ const compareStepArtifacts = (
),
beforeState: eventEvidenceState(input.beforeCapture, input.beforeStep),
afterState: eventEvidenceState(input.afterCapture, input.afterStep),
incomparableReason: networkContentCoverageReason(
incomparableReason: eventCoverageReason(
input.beforeCapture,
input.afterCapture,
),
@@ -340,6 +341,17 @@ const compareStepArtifacts = (
];
};
const eventCoverageReason = (
before: BrowserScenarioCapture,
after: BrowserScenarioCapture,
): string | undefined => {
const reasons = [
eventFamilyCoverageReason(before, after),
networkContentCoverageReason(before, after),
].filter((reason) => reason !== undefined);
return reasons.length === 0 ? undefined : reasons.join(" ");
};
interface CompareCapturedValuesInput<Value> {
readonly artifact: BrowserScenarioArtifactKind;
readonly before: CaptureState<Value>;
+20
View File
@@ -130,6 +130,26 @@ export const networkContentCoverageReason = (
: undefined;
};
/** Different or unrecorded event-family selection is missing comparability, not an observed website change. */
export const eventFamilyCoverageReason = (
before: BrowserScenarioCapture,
after: BrowserScenarioCapture,
): string | undefined => {
const left = before.scenario.event_families;
const right = after.scenario.event_families;
if (left === undefined || right === undefined)
return "Event family selection is unknown in a legacy capture; capture both sides with matching event families before comparing event evidence.";
const leftFamilies = new Set(left);
const rightFamilies = new Set(right);
return leftFamilies.size === rightFamilies.size &&
[...leftFamilies].every((family) => rightFamilies.has(family))
? undefined
: `Event family selections differ (${familyList(leftFamilies)} before, ${familyList(rightFamilies)} after); capture both sides with matching event families before comparing event evidence.`;
};
const familyList = (families: ReadonlySet<string>): string =>
families.size === 0 ? "none" : [...families].sort().join(", ");
/** Wrap one value as captured comparison evidence. */
export const captured = <Value>(value: Value): CaptureState<Value> => ({
state: "captured",
+2 -14
View File
@@ -5,6 +5,7 @@ import { IDENTIFIER_PATTERN } from "./stringPatterns.js";
import { localPathStringSchema } from "./localPath.js";
import { browserNetworkContentSelectionSchema } from "./browserNetworkEvidence.js";
import { browserScenarioEventFamilySchema } from "./browserScenarioCaptureValues.js";
import {
browserEndpointSchema,
@@ -289,20 +290,7 @@ export const browserScenarioCaptureSchema = z
.strictObject({
after_each_step: z.array(snapshotKindSchema).default([]),
at_end: z.array(snapshotKindSchema).default(["url"]),
events: z
.array(
z.enum([
"console",
"page-errors",
"network",
"websockets",
"frames",
"workers",
"popups",
"downloads",
]),
)
.default([]),
events: z.array(browserScenarioEventFamilySchema).default([]),
network: browserNetworkContentSelectionSchema,
})
.default({
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
const argument = z
.string()
.min(1)
.max(8192)
.refine((value) => !value.includes("\0"), "NUL is not an argument character");
const captureInputShape = z.strictObject({
path: localPathStringSchema.describe("Absolute local capture path"),
fields: z
.array(argument)
.max(1024)
.min(1)
.describe(
"TShark field names to return, e.g. ip.addr, usb.endpoint_address, btatt.opcode; frame.number is always included",
),
display_filter: argument
.nullable()
.default(null)
.describe(
"Optional Wireshark display filter (-Y), applied within the read limit",
),
decode_as: z
.array(argument)
.max(1024)
.default([])
.describe("Explicit TShark decode-as selections, e.g. tcp.port==8888,http"),
packet_limit: z
.number()
.int()
.positive()
.max(2147483647)
.nullable()
.default(null)
.describe(
"Maximum input packets to read before filtering; omitted scans to EOF within resource limits",
),
two_pass: z
.boolean()
.default(true)
.describe(
"Use two-pass analysis for fields requiring later packets; false requests a single pass",
),
match_offset: z
.number()
.int()
.nonnegative()
.default(0)
.describe("Skip this many matching packets after filtering; default 0"),
match_limit: z
.number()
.int()
.positive()
.nullable()
.default(50)
.describe(
"Return at most this many matching packets after filtering; default 50. Null explicitly returns all remaining matches within producer resource limits.",
),
});
// Bound UTF-8 selector text, terminators, option names and 64-bit argv pointers
// before Set/flatMap expansion. 32 KiB reserves headroom below Linux execve's
// 32-page argv+environment floor; ambient environments can still exhaust it.
export const withinPacketCaptureSelectorBudget = (input: {
fields: readonly string[];
decode_as: readonly string[];
display_filter: string | null;
}): boolean => {
if (input.fields.length > 1024 || input.decode_as.length > 1024) return false;
let bytes = 0;
for (const selections of [input.fields, input.decode_as])
for (const value of selections) {
bytes += Buffer.byteLength(value, "utf8") + 20;
if (bytes > 32768) return false;
}
if (input.display_filter !== null)
bytes += Buffer.byteLength(input.display_filter, "utf8") + 20;
return bytes <= 32768;
};
export const packetCaptureSelectorBudgetIssue = {
message:
"Packet selectors exceed the 32 KiB encoded argument budget; reduce fields, decode-as rules or filter text.",
};
export const inspectPacketCaptureInputSchema = captureInputShape.refine(
withinPacketCaptureSelectorBudget,
packetCaptureSelectorBudgetIssue,
);
export const packetCaptureOptionsSchema = captureInputShape
.omit({ path: true })
.refine(withinPacketCaptureSelectorBudget, packetCaptureSelectorBudgetIssue);
export type InspectPacketCaptureInput = z.infer<
typeof inspectPacketCaptureInputSchema
>;
/** Values remain strings; repeated occurrences remain ordered arrays. */
export const packetFieldsSchema = z
.object({
"frame.number": z.tuple([z.string().regex(/^[1-9][0-9]*$/)]),
})
.catchall(z.array(z.string()));
export const packetCaptureSchema = z
.strictObject({
artifact: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: z.number().int().nonnegative(),
}),
selection: inspectPacketCaptureInputSchema,
packets: z.array(packetFieldsSchema),
output_window: z.strictObject({
matching_packets: z
.number()
.int()
.nonnegative()
.describe(
"Matches in the completed producer output within the indicated input read scope, not total capture packets",
),
returned_packets: z.number().int().nonnegative(),
has_more: z.boolean(),
}),
read_scope: z.enum(["to-eof", "up-to-input-packet-limit"]),
diagnostics: z.string(),
tool: z.strictObject({
configured_path: z.string(),
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
version_banner: z.string(),
version_diagnostics: z.string(),
arguments: z.array(z.string()),
}),
configuration: z.literal("private-empty-personal-profile"),
resource_limiter: z.strictObject({
configured_path: z.string(),
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
arguments: z.array(z.string()),
}),
limits: z.strictObject({
input_bytes: z.number().int().positive(),
output_bytes: z.number().int().positive(),
command_timeout_ms: z.number().int().positive(),
address_space_bytes: z.number().int().nonnegative(),
file_bytes: z.number().int().nonnegative(),
cpu_seconds: z.number().int().nonnegative(),
}),
hardware_acquisition: z.literal("not-performed"),
})
.superRefine((report, context) => {
const remaining = Math.max(
report.output_window.matching_packets - report.selection.match_offset,
0,
);
const expected =
report.selection.match_limit === null
? remaining
: Math.min(remaining, report.selection.match_limit);
if (
report.packets.length !== expected ||
report.output_window.returned_packets !== expected ||
report.output_window.has_more !== remaining > expected
)
context.addIssue({
code: "custom",
path: ["output_window"],
message:
"Returned packet window must match examined matches and caller-selected offset/limit",
});
});
+138 -3
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { dosMz, pe } from "./binaryTarget.fixture.js";
import { parseExecutableHeader } from "./binaryTarget.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
import { observeMzWindowsHeader, parseDosMzHeader } from "./dosMz.js";
describe("DOS MZ load-module validation", () => {
it("separates initialized module and appended overlay bytes", () => {
@@ -33,7 +33,7 @@ describe("DOS MZ load-module validation", () => {
bytes.writeUInt16LE(1, 62);
bytes.writeUInt16LE(8, 66);
expect(bytes.readUInt32LE(60)).toBe(65536);
expect(mzWindowsHeaderOffset(bytes)).toBeNull();
expect(observeMzWindowsHeader(bytes)).toEqual({ state: "absent" });
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: { format: "dos-mz" },
@@ -53,12 +53,54 @@ describe("DOS MZ load-module validation", () => {
});
});
it("keeps a partial DOS prefix unknown until the Windows pointer is examined", () => {
const bytes = dosMz(64);
expect(observeMzWindowsHeader(bytes.subarray(0, 32), bytes.length)).toEqual(
{
state: "header-needed",
},
);
expect(
parseExecutableHeader(bytes.subarray(0, 32), "x64", bytes.length),
).toMatchObject({ ok: false });
expect(observeMzWindowsHeader(bytes.subarray(0, 32))).toEqual({
state: "absent",
});
});
it("parses a tiny known-length DOS module without requiring an impossible pointer", () => {
const bytes = Buffer.alloc(33);
bytes.write("MZ", 0, "ascii");
bytes.writeUInt16LE(bytes.length, 2);
bytes.writeUInt16LE(1, 4);
bytes.writeUInt16LE(2, 8);
bytes.writeUInt16LE(28, 24);
bytes[32] = 0xc3;
expect(observeMzWindowsHeader(bytes.subarray(0, 28), bytes.length)).toEqual(
{
state: "absent",
},
);
expect(
parseExecutableHeader(bytes.subarray(0, 28), "x64", bytes.length),
).toMatchObject({
ok: true,
value: { format: "dos-mz", architecture: "x86" },
});
});
it("preserves PE classification when low relocation records do not overlap e_lfanew", () => {
const bytes = pe(0x8664);
bytes.writeUInt16LE(4, 8);
bytes.writeUInt16LE(1, 6);
bytes.writeUInt16LE(28, 24);
expect(mzWindowsHeaderOffset(bytes)).toBe(64);
expect(observeMzWindowsHeader(bytes)).toEqual({
state: "declared",
offset: 64,
signature: "PE",
});
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: { format: "pe", architecture: "x86_64" },
@@ -100,7 +142,9 @@ describe("DOS MZ load-module validation", () => {
},
);
});
});
describe("MZ Windows header observations", () => {
it.each(["NE", "LE", "LX"])(
"distinguishes unsupported %s from DOS",
(signature) => {
@@ -115,6 +159,97 @@ describe("DOS MZ load-module validation", () => {
},
);
it("keeps a short-header nonzero module value as DOS without a signature", () => {
const bytes = dosMz(64);
bytes.writeUInt32LE(bytes.length, 60);
expect(observeMzWindowsHeader(bytes)).toEqual({ state: "absent" });
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: { format: "dos-mz", architecture: "x86" },
});
});
it.each(["PEZZ", "NE", "LE", "LX", "PE"])(
"keeps a non-Windows %s signature candidate as DOS",
(signature) => {
const bytes = dosMz(64);
const offset = 32;
bytes.writeUInt32LE(offset, 60);
const candidate = Buffer.from(
[...Buffer.from(signature)].map((byte) =>
signature === "PEZZ" ? byte : byte | 0x80,
),
);
bytes.set(candidate, offset);
expect(observeMzWindowsHeader(bytes)).toEqual({ state: "absent" });
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: { format: "dos-mz", architecture: "x86" },
});
},
);
it("accepts a short-header candidate only when it points at a Windows signature", () => {
const stub = dosMz(64);
const offset = stub.length;
stub.writeUInt32LE(offset, 60);
const record = pe(0x8664).subarray(64);
const bytes = Buffer.concat([stub, record]);
expect(observeMzWindowsHeader(bytes)).toMatchObject({
state: "declared",
offset,
signature: "PE",
});
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: { format: "pe", architecture: "x86_64" },
});
});
it.each(["NE", "LE", "LX"])(
"recognizes short-header %s signatures as Windows declarations",
(signature) => {
const stub = dosMz(64);
const offset = stub.length;
stub.writeUInt32LE(offset, 60);
const bytes = Buffer.concat([stub, Buffer.alloc(24)]);
bytes.write(signature, offset, "ascii");
expect(observeMzWindowsHeader(bytes)).toMatchObject({
state: "declared",
offset,
signature,
});
expect(parseExecutableHeader(bytes, "x64")).toEqual({
ok: false,
error: `unsupported ${signature} executable in MZ image`,
});
},
);
it("requests the signature when a short-header candidate is outside its prefix", () => {
const offset = 8192;
const bytes = dosMz(64);
bytes.writeUInt32LE(offset, 60);
const prefix = Buffer.alloc(4096);
bytes.copy(prefix);
expect(observeMzWindowsHeader(prefix, offset + 512)).toEqual({
state: "signature-needed",
offset,
});
expect(
observeMzWindowsHeader(
prefix,
offset + 512,
Buffer.from("PE\0\0", "binary"),
),
).toEqual({ state: "declared", offset, signature: "PE" });
});
it("does not fall back to DOS when a Windows declaration is damaged", () => {
const bytes = Buffer.alloc(256);
dosMz().copy(bytes, 0, 0, 28);
+67 -12
View File
@@ -12,17 +12,31 @@ export interface DosMzHeader {
readonly entryOffset: number;
}
export type MzWindowsHeaderObservation =
| { readonly state: "absent" }
| { readonly state: "header-needed" }
| { readonly state: "signature-needed"; readonly offset: number }
| {
readonly state: "declared";
readonly offset: number;
readonly signature: "PE" | "NE" | "LE" | "LX" | "other" | "unobserved";
};
/**
* Locate a Windows new-header declaration without interpreting a short DOS
* header's load-module or relocation-table bytes at 0x3c as e_lfanew. A
* new-header pointer must lie in a sufficiently large header and outside
* actual relocation records. Zero-sized legacy stubs remain eligible for
* PE signature validation.
* Observe the Windows new-header pointer without mistaking short DOS module
* bytes for e_lfanew. Complete DOS headers declare their pointer; for shorter
* headers, only a PE/NE/LE/LX signature at that pointer confirms the candidate.
* A bounded prefix that does not reach the candidate requests one bounded read
* from its owner instead of treating unexamined bytes as absent.
*/
export const mzWindowsHeaderOffset = (bytes: Buffer): number | null => {
if (bytes.length < 64) return null;
export const observeMzWindowsHeader = (
bytes: Buffer,
fileSize = bytes.length,
signatureAtOffset?: Buffer,
): MzWindowsHeaderObservation => {
if (bytes.length < 64)
return fileSize >= 64 ? { state: "header-needed" } : { state: "absent" };
const headerBytes = bytes.readUInt16LE(8) * 16;
if (headerBytes !== 0 && headerBytes < 64) return null;
const relocationCount = bytes.readUInt16LE(6);
const tableStart = bytes.readUInt16LE(24);
if (
@@ -31,9 +45,40 @@ export const mzWindowsHeaderOffset = (bytes: Buffer): number | null => {
tableStart < 64 &&
tableStart + relocationCount * 4 > 60
)
return null;
return { state: "absent" };
const offset = bytes.readUInt32LE(60);
return offset === 0 ? null : offset;
if (offset === 0) return { state: "absent" };
const inlineSignature =
offset < bytes.length
? bytes.subarray(offset, Math.min(offset + 4, bytes.length))
: undefined;
const available = signatureAtOffset ?? inlineSignature;
const signature = windowsHeaderSignature(available);
if (headerBytes === 0 || headerBytes >= 64)
return { state: "declared", offset, signature };
if (signature !== "other" && signature !== "unobserved")
return { state: "declared", offset, signature };
if (signature === "other") return { state: "absent" };
const observedPePrefix =
available !== undefined &&
available.length >= 2 &&
available.toString("latin1", 0, 2) === "PE";
if (fileSize - offset < (observedPePrefix ? 4 : 2))
return { state: "absent" };
return { state: "signature-needed", offset };
};
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";
if (bytes.length < 4) return "unobserved";
return bytes.subarray(0, 4).equals(Buffer.from("PE\0\0", "binary"))
? "PE"
: "other";
};
/**
@@ -44,13 +89,21 @@ export const mzWindowsHeaderOffset = (bytes: Buffer): number | null => {
export const parseDosMzHeader = (
bytes: Buffer,
fileSize = bytes.length,
signatureAtOffset?: Buffer,
): Result<DosMzHeader, string> => {
if (bytes.length < 28 || bytes.toString("ascii", 0, 2) !== "MZ")
if (bytes.length < 28 || bytes.toString("latin1", 0, 2) !== "MZ")
return err("invalid or truncated DOS MZ header");
if (!Number.isSafeInteger(fileSize) || fileSize < bytes.length)
return err("invalid DOS MZ file length");
if (mzWindowsHeaderOffset(bytes) !== null)
const windowsHeader = observeMzWindowsHeader(
bytes,
fileSize,
signatureAtOffset,
);
if (windowsHeader.state === "declared")
return err("MZ declares a Windows new header; it is not a DOS-only image");
if (windowsHeader.state === "signature-needed")
return err("MZ Windows new-header signature is outside the bounded prefix");
const lastPageBytes = bytes.readUInt16LE(2);
const pages = bytes.readUInt16LE(4);
if (pages === 0 || lastPageBytes > 511)
@@ -71,6 +124,8 @@ export const parseDosMzHeader = (
return err("DOS MZ relocation table lies outside its header");
if (relocationCount > 0 && tableEnd > bytes.length)
return err("truncated DOS MZ relocation table");
if (windowsHeader.state === "header-needed")
return err("MZ Windows new-header pointer is outside the bounded prefix");
const moduleBytes = imageBytes - headerBytes;
const relocations = validateRelocations(
bytes,
+61
View File
@@ -0,0 +1,61 @@
import { expect, it } from "vitest";
import { readElfFixedHeader } from "./elfFixedHeader.js";
import { elf } from "./binaryTarget.fixture.js";
it.each([
["ELF32 little endian", 1, 1],
["ELF32 big endian", 1, 2],
["ELF64 little endian", 2, 1],
["ELF64 big endian", 2, 2],
] as const)(
"reads common fixed header commitments for %s",
(_name, cls, data) => {
const bytes = elf(cls, data, cls === 1 ? 3 : 62);
expect(readElfFixedHeader(bytes)).toEqual({
ok: true,
value: {
elfClass: cls === 1 ? 32 : 64,
byteOrder: data === 1 ? "little" : "big",
headerSize: cls === 1 ? 52 : 64,
},
});
},
);
it.each([
[
"identification version",
(bytes: Buffer) => {
bytes[6] = 0;
},
],
[
"header version",
(bytes: Buffer) => {
bytes.writeUInt32LE(0, 20);
},
],
[
"undersized declared header",
(bytes: Buffer) => {
bytes.writeUInt16LE(51, 40);
},
],
[
"declared header beyond file",
(bytes: Buffer) => {
bytes.writeUInt16LE(53, 40);
},
],
])("rejects an invalid %s", (_name, corrupt) => {
const bytes = elf(1, 1, 3);
corrupt(bytes);
expect(readElfFixedHeader(bytes)).toMatchObject({ ok: false });
});
it("checks declared header size against the whole file, not the prefix", () => {
const bytes = elf(2, 1, 62);
bytes.writeUInt16LE(128, 52);
expect(readElfFixedHeader(bytes, 128)).toMatchObject({ ok: true });
expect(readElfFixedHeader(bytes, 127)).toMatchObject({ ok: false });
});
+55
View File
@@ -0,0 +1,55 @@
import { err, ok, type Result } from "./result.js";
export interface ElfFixedHeader {
readonly elfClass: 32 | 64;
readonly byteOrder: "little" | "big";
readonly headerSize: number;
}
/**
* Validate the common, fixed ELF header commitments.
*
* `bytes` may be a bounded prefix. `totalBytes` is the containing file size,
* so the declared header extent is checked against the file without requiring
* the whole declared extent to be present in this prefix.
*/
export const readElfFixedHeader = (
bytes: Buffer,
totalBytes = bytes.length,
): Result<ElfFixedHeader, string> => {
if (bytes.length >= 4 && bytes.toString("hex", 0, 4) !== "7f454c46")
return err("not an ELF image");
if (bytes.length < 16) return err("ELF identification is truncated");
const classByte = bytes[4];
if (classByte !== 1 && classByte !== 2) return err("unsupported ELF class");
const dataByte = bytes[5];
if (dataByte !== 1 && dataByte !== 2)
return err("unsupported ELF endianness");
if (bytes[6] !== 1) return err("unsupported ELF identification version");
const elfClass = classByte === 1 ? 32 : 64;
const minimumSize = elfClass === 32 ? 52 : 64;
if (
!Number.isSafeInteger(totalBytes) ||
totalBytes < bytes.length ||
totalBytes < minimumSize ||
bytes.length < minimumSize
)
return err(
`truncated ELF header: an ELF${elfClass} header needs ${minimumSize} bytes; the file has ${totalBytes}`,
);
const littleEndian = dataByte === 1;
const readU16 = (offset: number): number =>
littleEndian ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset);
const readU32 = (offset: number): number =>
littleEndian ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
if (readU32(20) !== 1) return err("unsupported ELF header version");
const headerSize = readU16(elfClass === 32 ? 40 : 52);
if (headerSize < minimumSize || headerSize > totalBytes)
return err("invalid ELF header size");
return ok({
elfClass,
byteOrder: littleEndian ? "little" : "big",
headerSize,
});
};
@@ -3,14 +3,74 @@ import { expect, it } from "vitest";
import {
AnalysisInputError,
AnalysisCapabilityUnavailableError,
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisArtifactChangedError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
import { ProviderAdapterError } from "./providerAdapterError.js";
import {
redactExplicitFailure,
redactExplicitPointer,
} from "./explicitSensitiveFailure.js";
const context = {
diagnostics: {
note: "explicit-secret warning",
nested: { "explicit-secret-key": 5, observed: 7 },
caller_path: "/tmp/password-fixture?token=public-value",
},
capturedOutput: {
stdout: "explicit-secret output",
stderr: "public stderr",
stdout_bytes: 22,
truncated: false,
},
};
it.each([
new AnalysisCancelledError("inspect", context),
new AnalysisTimeoutError("inspect", 250, context),
new AnalysisInputError("inspect", context),
new AnalysisAccessDeniedError("inspect", "/public", "EACCES", context),
new AnalysisArtifactChangedError("inspect", "/public", "changed", context),
new AnalysisOutputError("inspect", "invalid", context),
new AnalysisCapabilityUnavailableError(
"provider",
"inspect",
"unsupported",
context,
),
new AnalysisResourceConstraintError(
"inspect",
"memory",
"capacity",
null,
context,
),
new ProviderAdapterError("provider", "inspect", context),
])("preserves sanitized common context for $._tag", (error) => {
const sanitized = redactExplicitFailure(error, ["explicit-secret"]);
expect(sanitized._tag).toBe(error._tag);
const projected = projectAnalysisError(sanitized);
expect(projected.details).toMatchObject({
diagnostics: {
note: "[REDACTED] warning",
nested: { observed: 7 },
caller_path: context.diagnostics.caller_path,
},
captured_output: {
stdout: "[REDACTED] output",
stdout_bytes: 22,
stderr: "public stderr",
},
});
expect(JSON.stringify(projected)).not.toContain("explicit-secret");
});
it.each([
["/metadata/private~1~0/numeric", ["private/~"], "/metadata"],
["/metadata/private/child", ["private"], "/metadata"],
+46 -23
View File
@@ -6,6 +6,8 @@ import {
AnalysisOutputError,
AnalysisCapabilityUnavailableError,
AnalysisResourceConstraintError,
AnalysisCancelledError,
AnalysisTimeoutError,
} from "./analysisErrorCore.js";
import { redactExplicitText } from "./explicitSensitiveValues.js";
import type { JsonValue } from "./jsonValue.js";
@@ -72,24 +74,57 @@ export const redactExplicitFailure = (
if (typeof value === "object" && value !== null) return diagnostics(value);
return value;
};
const context = {
cause: error,
...(error.diagnostics === undefined
? {}
: { diagnostics: diagnostics(error.diagnostics) }),
...(error.capturedOutput === undefined
? {}
: {
capturedOutput: {
...error.capturedOutput,
stdout: text(error.capturedOutput.stdout),
stderr: text(error.capturedOutput.stderr),
},
}),
...(error.cleanup === undefined
? {}
: {
cleanup: {
reason: text(error.cleanup.reason),
resources: error.cleanup.resources.map(text),
},
}),
};
if (error instanceof AnalysisCancelledError)
return new AnalysisCancelledError(error.operation, {
...context,
partialObservation: error.partialObservation,
});
if (error instanceof AnalysisTimeoutError)
return new AnalysisTimeoutError(error.operation, error.timeoutMs, {
...context,
partialObservation: error.partialObservation,
});
if (error instanceof AnalysisAccessDeniedError)
return new AnalysisAccessDeniedError(
error.operation,
text(error.path),
error.systemCode,
{ cause: error },
context,
);
if (error instanceof AnalysisArtifactChangedError)
return new AnalysisArtifactChangedError(
error.operation,
text(error.path),
text(error.reason),
{ cause: error },
context,
);
if (error instanceof AnalysisInputError)
return new AnalysisInputError(
error.operation,
{ cause: error },
context,
error.issues.map((issue) => ({
...issue,
// Unknown-argument paths contain literal field names, including names
@@ -104,16 +139,18 @@ export const redactExplicitFailure = (
})),
);
if (error instanceof AnalysisOutputError)
return new AnalysisOutputError(error.operation, text(error.reason), {
cause: error,
});
return new AnalysisOutputError(
error.operation,
text(error.reason),
context,
);
if (error instanceof AnalysisCapabilityUnavailableError)
return new AnalysisCapabilityUnavailableError(
error.providerId,
error.operation,
text(error.reason),
{
cause: error,
...context,
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
@@ -126,19 +163,10 @@ export const redactExplicitFailure = (
text(error.reason),
error.reportedLimits === null ? null : diagnostics(error.reportedLimits),
{
cause: error,
...context,
...(error.remediationAction === undefined
? {}
: { remediationAction: text(error.remediationAction) }),
...(error.capturedOutput === undefined
? {}
: {
capturedOutput: {
stdout: text(error.capturedOutput.stdout),
stderr: text(error.capturedOutput.stderr),
truncated: error.capturedOutput.truncated,
},
}),
},
);
if (error instanceof ProviderCleanupError)
@@ -149,11 +177,6 @@ export const redactExplicitFailure = (
{ operation: error.operation, cause: error },
);
if (error instanceof ProviderAdapterError)
return new ProviderAdapterError(error.providerId, error.operation, {
cause: error,
...(error.diagnostics === undefined
? {}
: { diagnostics: diagnostics(error.diagnostics) }),
});
return new ProviderAdapterError(error.providerId, error.operation, context);
return error;
};
+173
View File
@@ -0,0 +1,173 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { digestSchema } from "../digests.js";
/**
* Caller intent for Flutter build identification. This family is pure
* parsing: it reads an APK's `lib/<abi>/libapp.so` and `libflutter.so`
* directly and runs no engine, tool, or device.
*/
export const flutterInputSchemas = {
identify_flutter_build: z.strictObject({
path: localPathStringSchema.describe("Local APK file to inspect"),
}),
inspect_dart_aot: z.strictObject({
path: localPathStringSchema.describe(
"Local APK file carrying a Flutter AOT payload",
),
abi: z
.string()
.min(2)
.max(16)
.regex(
/^[a-z0-9_\x2d]+$/u,
"ABI name as it appears under lib/, e.g. arm64-v8a",
)
.optional()
.describe(
"ABI to inspect; defaults to arm64-v8a, x86_64, x86, armeabi-v7a, then remaining ABIs alphabetically",
),
}),
} as const;
/** Supported Flutter-backed operations. */
export type FlutterOperation = keyof typeof flutterInputSchemas;
/** Validated Flutter requests carry their selected operation. */
export type FlutterRequest = {
[Name in FlutterOperation]: {
operation: Name;
input: z.infer<(typeof flutterInputSchemas)[Name]>;
};
}[FlutterOperation];
/** Validate operation and input together so their types remain correlated. */
export const flutterRequestSchema = z.discriminatedUnion("operation", [
z.strictObject({
operation: z.literal("identify_flutter_build"),
input: flutterInputSchemas.identify_flutter_build,
}),
z.strictObject({
operation: z.literal("inspect_dart_aot"),
input: flutterInputSchemas.inspect_dart_aot,
}),
]);
/** One hardware ABI's Flutter payload inside the APK. */
export const flutterResultSchemas = {
identify_flutter_build: z.strictObject({
target: z.strictObject({
path: localPathStringSchema,
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
}),
flutter_detected: z.boolean(),
abis: z.array(
z.strictObject({
abi: z.string().min(1),
libapp: z.strictObject({
present: z.boolean(),
bytes: z.number().int().nonnegative().nullable(),
sha256: digestSchema.nullable(),
/** Supported ELF header with table extents inside the library; table contents are not validated. */
elf_header_valid: z.boolean().nullable(),
/** Number of Dart snapshot sections found (vm + isolate). */
snapshot_hash_sources: z.number().int().nonnegative(),
/** Distinct hashes found; more than one means the sections disagree. */
snapshot_hash_candidates: z.array(
z.string().regex(/^[0-9a-f]{32}$/u),
),
/** The single hash when every snapshot section agrees. */
snapshot_hash: z
.string()
.regex(/^[0-9a-f]{32}$/u)
.nullable(),
}),
libflutter: z.strictObject({
present: z.boolean(),
bytes: z.number().int().nonnegative().nullable(),
sha256: digestSchema.nullable(),
build_id: z
.string()
.regex(/^[0-9a-f]{8,128}$/u)
.nullable()
.describe(
"The single GNU build ID when ELF note coverage is complete and unambiguous",
),
build_id_candidates: z
.array(z.string().regex(/^[0-9a-f]{8,128}$/u))
.max(64)
.describe(
"Distinct GNU build IDs observed in ELF-owned note ranges; conflicting IDs remain explicit",
),
dart_version: z
.string()
.nullable()
.describe(
"Labeled 'Dart VM version' string, when a build carries one",
),
toolchain_lines: z.array(z.string().min(1)),
/** Dart labels omitted by grammar or single-version projection bounds. */
dart_version_capped: z.boolean(),
/** Toolchain labels omitted by grammar or projection bounds. */
toolchain_capped: z.boolean(),
}),
}),
),
coverage: z.enum(["complete", "partial"]),
}),
inspect_dart_aot: z.strictObject({
target: z.strictObject({
path: localPathStringSchema,
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
}),
abi: z.string().min(1),
libapp: z.strictObject({
coverage: z
.enum(["complete", "partial"])
.describe(
"Coverage of ELF symbols, independent data headers, AOT kind, extents and agreeing hashes",
),
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
snapshot_hash: z
.string()
.regex(/^[0-9a-f]{32}$/u)
.nullable(),
/** Distinct hashes found; more than one means the sections disagree. */
snapshot_hash_candidates: z.array(z.string().regex(/^[0-9a-f]{32}$/u)),
/** Distinct exported data headers with a valid hash at the header's fixed offset. */
snapshot_hash_sources: z.number().int().nonnegative(),
/** Snapshot symbols read from the dynamic symbol table. */
sections: z.array(
z.strictObject({
name: z.string().min(1),
offset: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
magic_valid: z.boolean(),
kind: z.number().int().nonnegative().nullable(),
/** Raw declared snapshot length, excluding the four magic bytes. */
header_length: z.number().int().nonnegative().nullable(),
}),
),
}),
string_pool: z.strictObject({
coverage: z
.enum(["complete", "partial"])
.describe(
"Coverage of the bounded printable-run projection; independent of snapshot header validity",
),
/** Distinct package: source URIs, sorted, bounded. */
package_uris: z.array(z.string().min(1)),
package_uri_count_at_least: z.number().int().nonnegative(),
/** Distinct dart: SDK URIs, sorted, bounded. */
dart_uris: z.array(z.string().min(1)),
dart_uri_count_at_least: z.number().int().nonnegative(),
/** Identifier-like tokens, bounded; includes incidental matches. */
class_like_tokens: z.array(z.string().min(1)),
class_like_token_count_at_least: z.number().int().nonnegative(),
printable_run_count: z.number().int().nonnegative(),
}),
coverage: z.enum(["complete", "partial"]),
}),
} as const;
+78
View File
@@ -0,0 +1,78 @@
import type { RelationshipCoverage } from "./relationshipCoverage.js";
import type { FunctionDossier } from "./hopperValues.js";
import { uniqueSorted } from "./canonicalOrdering.js";
/** Combine caller and callee read outcomes without losing either explanation. */
export const combineFunctionRelationshipCoverage = (
callers: RelationshipCoverage | undefined,
callees: RelationshipCoverage | undefined,
): RelationshipCoverage => {
const reads = [
{ direction: "callers" as const, coverage: callers },
{ direction: "callees" as const, coverage: callees },
];
const diagnostics = uniqueSorted(
reads.flatMap(({ coverage }) =>
coverage !== undefined && "diagnostics" in coverage
? coverage.diagnostics
: [],
),
);
const details = diagnostics.length > 0 ? { diagnostics } : {};
const reasons = reads.flatMap(({ direction, coverage }) => {
const label = direction === "callers" ? "Callers" : "Callees";
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}`);
});
if (
reads.some(
({ coverage }) => coverage === undefined || coverage.status === "unknown",
)
)
return {
status: "unknown",
reason: uniqueSorted(reasons).join(" "),
...details,
};
if (reasons.length > 0)
return {
status: "partial",
limitations: uniqueSorted(reasons),
...details,
};
return { status: "complete", ...details };
};
/** 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(
...(dossier.unresolved_calls ?? []).map(
({ address, reason }) => `Unresolved call at ${address}: ${reason}`,
),
);
return uniqueSorted(limitations);
};
+116
View File
@@ -11,6 +11,7 @@ import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
import { jsonValueSchema } from "./jsonValue.js";
import { compareFunctions } from "./functionComparison.js";
import type { RelationshipCoverage } from "./relationshipCoverage.js";
const procedure = (address: string, name: string) => ({
address,
name,
@@ -96,6 +97,7 @@ const observe = (
digit: string,
value: ReturnType<typeof dossier>,
providerId = "rea-workflow",
relationshipCoverage: RelationshipCoverage | null = { status: "complete" },
): Evidence =>
createEvidence(
{
@@ -112,6 +114,7 @@ const observe = (
result: jsonValueSchema.parse(value),
confidence: "derived",
authority: "shipped-artifact",
...(relationshipCoverage === null ? {} : { relationshipCoverage }),
},
);
@@ -187,6 +190,100 @@ describe("function comparison normalized identity", () => {
});
});
describe("function call relationship coverage", () => {
const coverageCases: {
readonly label: string;
readonly coverage: RelationshipCoverage | null;
readonly limitation: string;
}[] = [
{
label: "missing",
coverage: null,
limitation: "Provider did not report relationship coverage.",
},
{
label: "partial",
coverage: {
status: "partial",
limitations: ["Call graph stopped at the read limit."],
},
limitation: "Call graph stopped at the read limit.",
},
];
it.each(coverageCases)(
"keeps equal empty calls unknown for $label coverage",
({ coverage, limitation }) => {
const left = observe("a", dossier("return 0;", "0x1000"));
const right = observe(
"b",
dossier("return 0;", "0x2000"),
"rea-workflow",
coverage,
);
const result = compareFunctions(left, right);
const calls = result.dimensions.find(
({ dimension }) => dimension === "calls",
);
expect(calls).toMatchObject({
status: "unknown",
conclusion_kind: "unresolved_branch",
left_count: 0,
right_count: 0,
limitations: [`Right: ${limitation}`],
});
expect(result.status).toBe("unknown");
},
);
it("retains complete observations with execution diagnostics as comparable", () => {
const coverage = {
status: "complete" as const,
diagnostics: ["Provider reported a non-call xref warning."],
};
const left = observe(
"c",
dossier("return 0;", "0x1000"),
"rea-workflow",
coverage,
);
const right = observe(
"d",
dossier("return 0;", "0x2000"),
"rea-workflow",
coverage,
);
expect(
compareFunctions(left, right).dimensions.find(
({ dimension }) => dimension === "calls",
),
).toMatchObject({ status: "unchanged", left_count: 0, right_count: 0 });
});
it("keeps unresolved call sites unknown despite complete resolved-set coverage", () => {
const left = observe("e", dossier("return 0;", "0x1000"));
const rightDossier = functionDossierSchema.parse({
...dossier("return 0;", "0x2000"),
unresolved_calls: [
{
address: "0x2010",
reason: "Indirect dispatch target could not be resolved.",
},
],
});
const right = observe("f", rightDossier);
expect(
compareFunctions(left, right).dimensions.find(
({ dimension }) => dimension === "calls",
),
).toMatchObject({
status: "unknown",
limitations: [
"Right: Unresolved call at 0x2010: Indirect dispatch target could not be resolved.",
],
});
});
});
describe("function collection collation ties", () => {
const composed = procedure("0x2000", "caf\u00e9");
const decomposed = procedure("0x3000", "cafe\u0301");
@@ -342,6 +439,7 @@ describe("function comparison ordering controls", () => {
result: jsonValueSchema.parse(result),
confidence: "derived",
authority: "shipped-artifact",
relationshipCoverage: { status: "complete" },
},
);
const left = controlled("0x1000", false);
@@ -525,7 +623,9 @@ describe("function comparison", () => {
limitations: [expect.stringContaining("did not expose reference kinds")],
});
});
});
describe("function comparison identity and malformed CFG", () => {
it("does not promote address-derived names through equal signatures", () => {
const autoDossier = (base: "0x1000" | "0x2000") =>
functionDossierSchema.parse({
@@ -546,6 +646,22 @@ describe("function comparison", () => {
comparison.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
expect(comparison.status).toBe("unknown");
const changedText = compareFunctions(
observe("b", autoDossier("0x1000")),
observe(
"c",
functionDossierSchema.parse({
...autoDossier("0x2000"),
pseudocode: "return 1;",
}),
),
);
expect(changedText.dimensions).toEqual(
expect.arrayContaining([
expect.objectContaining({ dimension: "pseudocode", status: "changed" }),
]),
);
expect(changedText.status).toBe("unknown");
});
it("rejects invalid CFG normalization and preserves newline differences", () => {
@@ -233,6 +233,18 @@ const compareCalls = (
): FunctionDimension => {
const leftValues = callProjection(left);
const rightValues = callProjection(right);
const coverageLimitations = [
...left.callCoverageLimitations.map((reason) => `Left: ${reason}`),
...right.callCoverageLimitations.map((reason) => `Right: ${reason}`),
];
if (coverageLimitations.length > 0)
return unresolvedDimension({
dimension: "calls",
links: context.links,
leftCount: leftValues.length,
rightCount: rightValues.length,
limitations: coverageLimitations,
});
if ([...leftValues, ...rightValues].some(({ name }) => isAutoName(name)))
return unresolvedDimension({
dimension: "calls",
+4 -8
View File
@@ -69,15 +69,11 @@ export const overallStatus = (
dimensions: readonly FunctionDimension[],
match: FunctionComparisonResult["function_match"]["status"],
): FunctionComparisonResult["status"] => {
if (
match === "ambiguous" ||
dimensions.some(({ status }) => status === "unknown")
)
return "unknown";
if (match === "mismatched") return "changed";
return dimensions.some(({ status }) => status === "changed")
? "changed"
: "unchanged";
if (match === "ambiguous") return "unknown";
if (dimensions.some(({ status }) => status === "changed")) return "changed";
if (dimensions.some(({ status }) => status === "unknown")) return "unknown";
return "unchanged";
};
export const summarize = (dimensions: readonly FunctionDimension[]) => ({
+5 -3
View File
@@ -4,7 +4,7 @@ import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const comparisonStatusSchema = z.enum(["unchanged", "changed", "unknown"]);
const dimensionNameSchema = z.enum([
export const functionComparisonDimensionNameSchema = z.enum([
"identity",
"pseudocode",
"assembly",
@@ -29,7 +29,7 @@ const textDeltaSchema = z.object({
});
const functionDimensionContextShape = {
dimension: dimensionNameSchema,
dimension: functionComparisonDimensionNameSchema,
left_count: z.number().int().min(0).nullable(),
right_count: z.number().int().min(0).nullable(),
evidence_links: z.array(evidenceIdSchema).min(2),
@@ -98,4 +98,6 @@ export type FunctionComparisonResult = z.infer<
typeof functionComparisonResultSchema
>;
export type FunctionDimension = z.infer<typeof functionDimensionSchema>;
export type DimensionName = z.infer<typeof dimensionNameSchema>;
export type DimensionName = z.infer<
typeof functionComparisonDimensionNameSchema
>;
+7
View File
@@ -1,6 +1,7 @@
import { parseEvidence, type Evidence } from "./evidence.js";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
import { functionDossierSchema, type FunctionDossier } from "./hopperValues.js";
import { functionCallCoverageLimitations } from "./functionCallCoverage.js";
/** Complete function observation parsed from one analyze_function Evidence record. */
export interface FunctionSnapshot {
@@ -8,6 +9,7 @@ export interface FunctionSnapshot {
readonly subject: NonNullable<Evidence["subject"]>;
readonly dossier: FunctionDossier;
readonly limitations: readonly string[];
readonly callCoverageLimitations: readonly string[];
}
/** Parse one complete analyze_function Evidence record for comparison workflows. */
@@ -20,6 +22,10 @@ export const parseFunctionEvidence = (input: unknown): FunctionSnapshot => {
if (evidence.subject === null)
throw new TypeError("Function comparison requires artifact-bound Evidence");
const dossier = functionDossierSchema.parse(evidence.normalized_result);
const callCoverageLimitations = functionCallCoverageLimitations(
evidence.relationship_coverage,
dossier,
);
return {
evidence,
subject: evidence.subject,
@@ -27,5 +33,6 @@ export const parseFunctionEvidence = (input: unknown): FunctionSnapshot => {
limitations: [
...new Set([...evidence.limitations, ...dossier.limitations]),
].sort((left, right) => compareUnicodeCodePoints(left, right)),
callCoverageLimitations,
};
};
+7 -3
View File
@@ -1,6 +1,9 @@
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
} from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
@@ -66,6 +69,7 @@ export const harmonyApplicationProjectionResultSchema = z.strictObject({
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
@@ -108,8 +112,8 @@ export const projectHarmonyApplication = (
classified.native_libraries,
);
const limitations = [
...(!inventory.complete
? ["Source inventory pages are incomplete; absence is unknown."]
...(!hasCompleteInventoryCoverage(inventory)
? ["Source inventory coverage is partial; absence is unknown."]
: []),
...(unavailable.length > 0
? [
+14
View File
@@ -8,6 +8,7 @@ import {
parseNames,
parseProcedures,
parseRelatedAddresses,
parseSegmentImageBase,
parseSegments,
} from "./hopperValues.js";
@@ -65,6 +66,19 @@ describe("Hopper boundary values", () => {
ok: true,
value: ["fixture"],
});
expect(
parseSegmentImageBase([
{ image_base: "0x100000" },
{ image_base: "0x100000" },
]),
).toBe("0x100000");
expect(
parseSegmentImageBase([
{ image_base: "0x100000" },
{ image_base: "0x200000" },
]),
).toBeUndefined();
expect(parseSegmentImageBase([{ name: "__TEXT" }])).toBeUndefined();
});
it.each([
+13
View File
@@ -59,6 +59,9 @@ const segmentSchema = z.object({
writable: z.boolean().nullable(),
executable: z.boolean().nullable(),
});
const segmentImageBaseSchema = z
.object({ image_base: z.string().min(1) })
.passthrough();
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
@@ -424,6 +427,16 @@ export const parseSegments = (
: invalid("segment list", parsed.error);
};
/** Return a provider-reported image base only when every segment agrees on it. */
export const parseSegmentImageBase = (value: JsonValue): string | undefined => {
const parsed = z
.array(segmentImageBaseSchema)
.safeParse(unwrapProperty(value, "segments"));
if (!parsed.success) return undefined;
const bases = new Set(parsed.data.map(({ image_base }) => image_base));
return bases.size === 1 ? parsed.data[0]?.image_base : undefined;
};
/** Parse direct or wrapped Hopper document names. */
export const parseDocuments = (
value: JsonValue,
@@ -9,6 +9,7 @@ import type {
ElectronUtilityProcessFinding,
ElectronWebPreference,
} from "./electronStaticAnalysisTypes.js";
import { contextBridgeExposureArguments } from "./javascriptContextBridgeExposure.js";
import {
boundedExpression,
collectContextBridgeMembers,
@@ -166,18 +167,19 @@ const inspectContextBridge = (
context: JavaScriptFindingContext,
): void => {
const path = electronCalleePath(node.callee, context);
const exposureMethod =
path?.length === 2 && path[0] === "contextBridge" ? path[1] : undefined;
const main = exposureMethod === "exposeInMainWorld";
const isolated = exposureMethod === "exposeInIsolatedWorld";
if (!main && !isolated) return;
const keyNode = argumentNode(node.arguments[isolated ? 1 : 0]);
const apiNode = argumentNode(node.arguments[isolated ? 2 : 1]);
const exposure =
path?.length === 2 && path[0] === "contextBridge"
? contextBridgeExposureArguments(path[1] ?? "", node.arguments)
: undefined;
if (exposure === undefined) return;
const keyNode = argumentNode(exposure.apiKey);
const apiNode = argumentNode(exposure.api);
const key = electronStaticValue(context.source, keyNode);
const api = collectContextBridgeMembers(apiNode);
const worldId = isolated
? electronStaticValue(context.source, argumentNode(node.arguments[0]))
: null;
const worldId =
exposure.worldId === null
? null
: electronStaticValue(context.source, argumentNode(exposure.worldId));
const unknown =
(key.status === "dynamic" ? 1 : 0) +
(worldId?.status === "dynamic" ? 1 : 0) +
@@ -191,7 +193,7 @@ const inspectContextBridge = (
: { api_key: null, api_key_expression: null };
const finding: ElectronContextBridgeFinding = {
...apiKey,
world: isolated ? "isolated" : "main",
world: exposure.world,
world_id: worldId,
api_status: api.status,
members: api.members,
@@ -201,7 +203,7 @@ const inspectContextBridge = (
};
addLocatedFinding(context, {
collection: context.accumulator.contextBridgeApis,
key: `context-bridge\0${isolated ? "isolated" : "main"}\0${finding.api_key ?? finding.api_key_expression ?? "[missing]"}`,
key: `context-bridge\0${exposure.world}\0${finding.api_key ?? finding.api_key_expression ?? "[missing]"}`,
node,
value: finding,
});
@@ -140,6 +140,60 @@ it("preserves an observed empty contextBridge API object", () => {
expect(result.parse_status).toBe("complete");
});
describe("wrapped contextBridge exposure methods", () => {
it("retains the original expression for a dynamic isolated world id", () => {
const result = analyzeJavaScriptStaticSource(
bundle(
`const worldId = selectWorld(); electron.contextBridge.exposeInIsolatedWorld(worldId, "isolatedApi", {ping: true});`,
),
);
expect(result.electron.context_bridge_apis).toContainEqual(
expect.objectContaining({
world: "isolated",
world_id: {
status: "dynamic",
value: null,
expression: "worldId",
},
api_key: "isolatedApi",
members: ["ping"],
resolution_basis: "wrapper-substitution",
}),
);
expect(result.parse_status).toBe("partial");
});
it("does not report a conditionally selected world as unconditional", () => {
const result = analyzeJavaScriptStaticSource(
bundle(
`if (useIsolated) electron.contextBridge.exposeInIsolatedWorld(1001, "isolatedApi", {ping: true});`,
),
);
expect(result.electron.context_bridge_apis).not.toContainEqual(
expect.objectContaining({
api_key: "isolatedApi",
resolution_basis: "wrapper-substitution",
}),
);
expect(result.parse_status).toBe("partial");
});
it("does not report conditionally resolved world ids as unconditional", () => {
const result = analyzeJavaScriptStaticSource(
bundle(
`const worldId = useFirstWorld ? 1001 : 1002; electron.contextBridge.exposeInIsolatedWorld(worldId, "isolatedApi", {ping: true});`,
),
);
expect(result.electron.context_bridge_apis).not.toContainEqual(
expect.objectContaining({
api_key: "isolatedApi",
resolution_basis: "wrapper-substitution",
}),
);
expect(result.parse_status).toBe("partial");
});
});
it("connects exposed closures to IPC sends and text clipboard calls", () => {
const result = analyzeJavaScriptStaticSource(
bundle(`
@@ -14,9 +14,17 @@ import type { JavaScriptAnalysisAccumulator } from "./javascriptStaticAnalysisSt
import type {
ElectronCallPath,
ElectronCallPathStep,
ElectronContextBridgeFinding,
ElectronIpcDescriptor,
ElectronIpcFinding,
ElectronStaticValue,
} from "./electronStaticAnalysisTypes.js";
import {
contextBridgeExposureArguments,
type JavaScriptContextBridgeExposureArguments,
} from "./javascriptContextBridgeExposure.js";
import { boundedExpression } from "./electronStaticAnalysisValues.js";
import { argumentNode } from "./javascriptStaticAnalysisHelpers.js";
import {
childNodes,
traverseJavaScriptAst,
@@ -114,6 +122,41 @@ export const collectElectronWrappedCallPaths = (
};
const hasConditions = (value: SymbolicValue): boolean =>
symbolicVariants(value).some((variant) => variant.conditions?.length);
const isolatedBridgeCall = (
node: t.CallExpression | t.OptionalCallExpression,
):
| { readonly env: SymbolicEnvironment; readonly callee: SymbolicValue }
| undefined => {
const env = resolver.environmentAt(node);
const callee = resolver.evaluate(node.callee, env);
return symbolicVariants(callee).some(
(callee) =>
callee.kind === "external" &&
identity.intactExport(callee.path) &&
callee.path.slice(1).join(".") ===
"contextBridge.exposeInIsolatedWorld",
)
? { env, callee }
: undefined;
};
const electronStaticSymbolicValue = (
value: SymbolicValue | undefined,
node: t.Node | undefined,
): ElectronStaticValue => {
const variants = value === undefined ? [] : symbolicVariants(value);
const variant = variants.length === 1 ? variants[0] : undefined;
if (variant?.kind === "literal" && variant.value !== undefined)
return {
status: "literal",
value: variant.value,
expression: null,
};
return {
status: "dynamic",
value: null,
expression: boundedExpression(source, node),
};
};
const emit = (
context: PathContext,
node: t.Node,
@@ -288,17 +331,34 @@ export const collectElectronWrappedCallPaths = (
};
const bridge = (
node: t.CallExpression | t.OptionalCallExpression,
args: readonly SymbolicValue[],
exposure: JavaScriptContextBridgeExposureArguments<SymbolicValue>,
context: PathContext,
guardedDispatch: boolean,
): void => {
const key = args[0];
const object = args[1];
const key = exposure.apiKey;
const object = exposure.api;
const worldValue =
exposure.worldId === null
? null
: (exposure.worldId ?? symbolicUnknown("missing world id"));
const worldContext =
worldValue === null ? context : metadataContext(context, worldValue);
if (!worldContext) return;
const worldId =
worldValue === null
? null
: electronStaticSymbolicValue(
worldValue,
exposure.worldIdIndex === null
? undefined
: argumentNode(node.arguments[exposure.worldIdIndex]),
);
if (worldId?.status === "dynamic") accumulator.unknownFindings += 1;
if (key?.kind !== "literal" || typeof key.value !== "string" || !object) {
accumulator.unknownFindings += 1;
return;
}
const keyContext = metadataContext(context, key);
const keyContext = metadataContext(worldContext, key);
if (!keyContext || !metadataContext(keyContext, object)) return;
const members = [...resolver.members(object)].sort();
const location = range(node);
@@ -306,9 +366,9 @@ export const collectElectronWrappedCallPaths = (
({ value }) =>
JSON.stringify(value.location) === JSON.stringify(location),
);
const finding = {
world: "main" as const,
world_id: null,
const finding: ElectronContextBridgeFinding = {
world: exposure.world,
world_id: worldId,
api_key: key.value,
api_key_expression: null,
api_status: "dynamic" as const,
@@ -320,10 +380,12 @@ export const collectElectronWrappedCallPaths = (
};
// This report shape has no predicate field, so a guarded world or object
// cannot be recorded as an unconditional exposure fact.
const guardedWorld = worldValue !== null && hasConditions(worldValue);
const guardedKey = hasConditions(key);
const guardedObject = hasConditions(object);
const guarded =
context.conditions.length > 0 ||
guardedWorld ||
guardedKey ||
guardedObject ||
guardedDispatch;
@@ -370,8 +432,9 @@ export const collectElectronWrappedCallPaths = (
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
context: PathContext,
evaluatedCallee?: SymbolicValue,
): void => {
const value = resolver.evaluate(node.callee, env);
const value = evaluatedCallee ?? resolver.evaluate(node.callee, env);
const args = resolver.arguments(node, env);
for (const callee of symbolicVariants(value)) {
const branchContext = metadataContext(context, callee);
@@ -394,7 +457,13 @@ export const collectElectronWrappedCallPaths = (
const endpoint = path.join(".");
if (identity.intactExport(path)) {
const descriptor = ipcDescriptor(path.slice(1));
if (descriptor)
const exposure =
path.length === 3 && path[1] === "contextBridge"
? contextBridgeExposureArguments(path[2] ?? "", args)
: undefined;
if (exposure)
bridge(node, exposure, branchContext, hasConditions(callee));
else if (descriptor)
ipc(
node,
descriptor,
@@ -403,10 +472,6 @@ export const collectElectronWrappedCallPaths = (
endpoint,
hasConditions(callee),
);
else if (
path.slice(1).join(".") === "contextBridge.exposeInMainWorld"
)
bridge(node, args, branchContext, hasConditions(callee));
else if (path[1] === "clipboard") emit(branchContext, node, endpoint);
} else if (
(path[0] === "navigator" && path[1] === "clipboard") ||
@@ -488,8 +553,12 @@ export const collectElectronWrappedCallPaths = (
enter: (node) => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return;
if (!t.isStringLiteral(node.arguments[0])) return;
const env = resolver.environmentAt(node);
const isolatedSeed = t.isStringLiteral(node.arguments[0])
? undefined
: isolatedBridgeCall(node);
if (!t.isStringLiteral(node.arguments[0]) && isolatedSeed === undefined)
return;
const env = isolatedSeed?.env ?? resolver.environmentAt(node);
let context: PathContext = {
entryNode: node,
entry: "",
@@ -536,7 +605,7 @@ export const collectElectronWrappedCallPaths = (
return;
}
}
call(node, env, context);
call(node, env, context, isolatedSeed?.callee);
},
});
if (remainingVisits < 0 || resolver.truncated) {
@@ -10,6 +10,10 @@ import {
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
/** Static CommonJS export names. */
export interface StaticExports {
@@ -29,13 +33,41 @@ export const fingerprintJavaScriptAst = (node: t.Node): string => {
};
/** Collect statically declared CommonJS/bundler export names from one factory. */
export const collectJavaScriptExports = (node: t.Node): StaticExports => {
export const collectJavaScriptExports = (
node: t.Node,
bindings?: JavaScriptSemanticAnalysisState,
): StaticExports => {
const exports = new Set<string>();
const factoryExports =
bindings !== undefined &&
t.isFunction(node) &&
t.isIdentifier(node.params[1])
? resolveSemanticBindingState(
bindings,
node.params[1],
node.params[1].name,
)?.bindingId
: undefined;
const isExportsAlias = (reference: t.Node | null): boolean => {
if (!t.isIdentifier(reference)) return false;
if (factoryExports === undefined) return reference.name === "exports";
return (
bindings !== undefined &&
resolveSemanticBindingState(bindings, reference, reference.name)
?.bindingId === factoryExports
);
};
traverseJavaScriptAst(node, {
enter: (current) => {
if (t.isAssignmentExpression(current))
collectAssignmentExports(current.left, current.right, exports);
if (t.isCallExpression(current)) collectCallExports(current, exports);
collectAssignmentExports(
current.left,
current.right,
exports,
isExportsAlias,
);
if (t.isCallExpression(current))
collectCallExports(current, exports, isExportsAlias);
return undefined;
},
});
@@ -72,17 +104,19 @@ const collectAssignmentExports = (
left: t.LVal | t.OptionalMemberExpression,
right: t.Expression,
output: Set<string>,
isExportsAlias: (root: t.Node | null) => boolean,
): void => {
const path = memberPath(left);
if (path === null) return;
const root = memberRoot(left);
const exportsAlias = isExportsAlias(root);
// Rebinding the CommonJS alias does not replace module.exports.
if (path.length === 1 && path[0] === "exports") return;
const exportOffset =
path[0] === "exports"
? 1
: path[0] === "module" && path[1] === "exports"
? 2
: null;
if (path.length === 1 && exportsAlias) return;
const exportOffset = exportsAlias
? 1
: path[0] === "module" && path[1] === "exports"
? 2
: null;
if (exportOffset === null) return;
if (path.length === exportOffset) {
if (t.isObjectExpression(right)) collectObjectKeys(right, output);
@@ -98,6 +132,7 @@ const collectAssignmentExports = (
const collectCallExports = (
call: t.CallExpression,
output: Set<string>,
isExportsAlias: (root: t.Node | null) => boolean,
): void => {
const callee = memberPath(call.callee);
if (callee === null) return;
@@ -107,13 +142,14 @@ const collectCallExports = (
callee[1] === "defineProperty";
const declarationCall = callee.length >= 2 && callee.at(-1) === "d";
if (!definePropertyCall && !declarationCall) return;
const target = memberPath(call.arguments[0]);
const targetNode = call.arguments[0];
const target = memberPath(targetNode);
const exportTarget =
target !== null &&
((target.length === 1 && target[0] === "exports") ||
(target.length === 2 &&
target[0] === "module" &&
target[1] === "exports"));
isExportsAlias(targetNode ?? null) ||
(target !== null &&
target.length === 2 &&
target[0] === "module" &&
target[1] === "exports");
if (!exportTarget) return;
if (definePropertyCall) {
const name = stringValue(call.arguments[1]);
@@ -125,6 +161,17 @@ const collectCallExports = (
collectObjectKeys(declarations, output);
};
const memberRoot = (node: t.Node | null | undefined): t.Node | null => {
let current = node;
while (
current !== null &&
current !== undefined &&
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
)
current = current.object;
return current ?? null;
};
const collectObjectKeys = (
object: t.ObjectExpression,
output: Set<string>,
@@ -0,0 +1,35 @@
/** One contextBridge exposure method and its API argument positions. */
export interface JavaScriptContextBridgeExposureArguments<Argument> {
readonly world: "main" | "isolated";
readonly worldId: Argument | null | undefined;
readonly worldIdIndex: number | null;
readonly apiKey: Argument | undefined;
readonly api: Argument | undefined;
}
/**
* Select the semantic arguments for a contextBridge exposure method.
* Callers retain authority over callee identity and interpretation of values.
*/
export const contextBridgeExposureArguments = <Argument>(
method: string,
arguments_: readonly Argument[],
): JavaScriptContextBridgeExposureArguments<Argument> | undefined => {
if (method === "exposeInMainWorld")
return {
world: "main",
worldId: null,
worldIdIndex: null,
apiKey: arguments_[0],
api: arguments_[1],
};
if (method === "exposeInIsolatedWorld")
return {
world: "isolated",
worldId: arguments_[0],
worldIdIndex: 0,
apiKey: arguments_[1],
api: arguments_[2],
};
return undefined;
};
@@ -52,13 +52,17 @@ export interface JavaScriptIntrinsicInvocation {
| undefined;
}
/** Index member and binding writes through caller-proven lexical identities. */
/**
* Index writes through possible lexical object identities. Resolve the complete
* object before appending the written key: self-reference properties can denote
* the same object, while replacing that property is a distinct write.
*/
export function* collectJavaScriptIdentityWritesSteps(
program: t.Program,
origin: (
root: t.Node,
kind: "binding" | "member" | "opaque-call",
) => readonly string[] | undefined,
) => readonly (readonly (string | null)[])[],
intrinsicInvocation: (
node: t.CallExpression | t.OptionalCallExpression,
) => JavaScriptIntrinsicInvocation | undefined,
@@ -84,8 +88,7 @@ export function* collectJavaScriptIdentityWritesSteps(
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
const invocation = intrinsicInvocation(node);
if (invocation?.kind === "opaque") {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
for (const scope of origin(node, "opaque-call")) retain(node, scope);
return;
}
const callee = invocation?.path;
@@ -114,20 +117,20 @@ export function* collectJavaScriptIdentityWritesSteps(
// A known mutator with an opaque argument list can overwrite any
// captured intrinsic. Do not turn an unexamined target into proof.
if (target === undefined || t.isSpreadElement(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
for (const scope of origin(node, "opaque-call"))
retain(node, scope);
}
if (t.isNode(target) && !t.isSpreadElement(target)) {
const { root, members } = electronMemberPath(target);
const exported = origin(root, "member");
if (exported !== undefined) {
const identities = origin(target, "member");
if (identities.length > 0) {
const key = keyedMutators.has(method ?? "")
? [staticString(arguments_?.[1]) ?? null]
: [];
retain(node, [...exported, ...members, ...key]);
for (const identity of identities)
retain(node, [...identity, ...key]);
} else if (!freshObject(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
for (const scope of origin(node, "opaque-call"))
retain(node, scope);
}
}
}
@@ -145,13 +148,19 @@ export function* collectJavaScriptIdentityWritesSteps(
if (target === undefined) return;
for (const leaf of semanticWriteTargets(target)) {
if (t.isIdentifier(leaf)) {
const exported = origin(leaf, "binding");
if (exported !== undefined) retain(node, exported);
for (const identity of origin(leaf, "binding"))
retain(node, identity);
continue;
}
const { root, members } = electronMemberPath(leaf);
const exported = origin(root, "member");
if (exported !== undefined) retain(node, [...exported, ...members]);
const member = unwrapJavaScriptExpression(leaf).node;
if (
!t.isMemberExpression(member) &&
!t.isOptionalMemberExpression(member)
)
continue;
const key = semanticStaticPropertyKey(member.property, member.computed);
for (const identity of origin(member.object, "member"))
retain(node, [...identity, key]);
}
},
});
@@ -6,13 +6,52 @@ import {
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
const arrayArguments = (array: t.Node | undefined) =>
t.isArrayExpression(array) &&
array.elements.every((element) => t.isExpression(element))
? array.elements.filter((element): element is t.Expression =>
/** Expand only literal array spreads whose positional arguments are all known. */
export const expandJavaScriptInvocationArguments = (
arguments_: readonly t.CallExpression["arguments"][number][],
): t.CallExpression["arguments"] => {
const expanded: t.CallExpression["arguments"] = [];
const pending = [...arguments_].reverse();
while (pending.length > 0) {
const argument = pending.pop();
if (argument === undefined) break;
const array = t.isSpreadElement(argument)
? unwrapJavaScriptExpression(argument.argument).node
: undefined;
if (
t.isArrayExpression(array) &&
array.elements.every(
(element) => t.isExpression(element) || t.isSpreadElement(element),
)
)
for (let index = array.elements.length - 1; index >= 0; index -= 1) {
const element = array.elements[index];
if (element !== null && element !== undefined) pending.push(element);
}
else expanded.push(argument);
}
return expanded;
};
const arrayArguments = (node: t.Node | undefined) => {
const array =
node === undefined ? undefined : unwrapJavaScriptExpression(node).node;
if (
!t.isArrayExpression(array) ||
array.elements.some((element) => element === null)
)
return undefined;
const expanded = expandJavaScriptInvocationArguments(
array.elements.filter(
(element): element is t.Expression | t.SpreadElement => element !== null,
),
);
return expanded.every((element) => t.isExpression(element))
? expanded.filter((element): element is t.Expression =>
t.isExpression(element),
)
: undefined;
};
const invocationArguments = (
method: "call" | "apply",
@@ -36,7 +75,8 @@ export const resolveJavaScriptIntrinsicInvocation = (
): JavaScriptIntrinsicInvocation | undefined => {
const visited = new Set<t.Node>();
let callee: t.Node = node.callee;
let arguments_: JavaScriptIntrinsicInvocation["arguments"] = node.arguments;
let arguments_: JavaScriptIntrinsicInvocation["arguments"] =
expandJavaScriptInvocationArguments(node.arguments);
let receiver: t.Node | undefined;
let explicitReceiver = false;
for (;;) {
@@ -19,7 +19,10 @@ import {
electronMemberPath,
type JavaScriptIntrinsicInvocation,
} from "./javascriptElectronMemberWrites.js";
import { resolveJavaScriptIntrinsicInvocation } from "./javascriptIntrinsicInvocation.js";
import {
expandJavaScriptInvocationArguments,
resolveJavaScriptIntrinsicInvocation,
} from "./javascriptIntrinsicInvocation.js";
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
import {
readExactJavaScriptLiteral,
@@ -74,6 +77,9 @@ interface InteropHelper {
/** Prove one inert namespace conversion without relaxing general assignment semantics. */
export const createSemanticModuleInterop = (
state: JavaScriptSemanticAnalysisState,
options?: {
readonly intrinsicPath: (node: t.Node) => readonly string[] | undefined;
},
) => {
const helpers = new Map<string, InteropHelper | null>();
const origins = new Map<string, InteropOrigin>();
@@ -96,55 +102,57 @@ export const createSemanticModuleInterop = (
return ["intrinsic"];
};
const intrinsicPath = (node: t.Node): readonly string[] | undefined => {
let current = node;
const visited = new Set<string>();
const pending: { id: string; suffixLength: number }[] = [];
let suffix: readonly string[] = [];
const finish = (
path: readonly string[] | undefined,
): readonly string[] | undefined => {
for (const binding of pending)
intrinsicBindings.set(
binding.id,
path === undefined
? null
: path.slice(0, path.length - binding.suffixLength),
);
return path;
};
for (;;) {
const { root, members } = electronMemberPath(current);
if (members.some((member) => member === null)) return finish(undefined);
suffix = [...(members as readonly string[]), ...suffix];
for (const global of ["Object", "Function", "Reflect"])
if (isUnshadowedGlobal(root, state, global))
return finish(["intrinsic", global, ...suffix]);
for (const global of ["globalThis", "global", "window", "self"])
if (isUnshadowedGlobal(root, state, global))
return finish(["intrinsic", ...suffix]);
if (!t.isIdentifier(root)) return finish(undefined);
const binding = resolveSemanticBindingState(state, root, root.name);
const cached =
binding === undefined
? undefined
: intrinsicBindings.get(binding.bindingId);
if (cached !== undefined)
return finish(cached === null ? undefined : [...cached, ...suffix]);
const initializer = semanticStableInitializer(binding, state);
if (
binding === undefined ||
initializer === undefined ||
initializer.projection.some((segment) => segment === null) ||
visited.has(binding.bindingId)
)
return finish(undefined);
visited.add(binding.bindingId);
pending.push({ id: binding.bindingId, suffixLength: suffix.length });
suffix = [...initializer.projection.map(String), ...suffix];
current = initializer.node;
}
};
const intrinsicPath =
options?.intrinsicPath ??
((node: t.Node): readonly string[] | undefined => {
let current = node;
const visited = new Set<string>();
const pending: { id: string; suffixLength: number }[] = [];
let suffix: readonly string[] = [];
const finish = (
path: readonly string[] | undefined,
): readonly string[] | undefined => {
for (const binding of pending)
intrinsicBindings.set(
binding.id,
path === undefined
? null
: path.slice(0, path.length - binding.suffixLength),
);
return path;
};
for (;;) {
const { root, members } = electronMemberPath(current);
if (members.some((member) => member === null)) return finish(undefined);
suffix = [...(members as readonly string[]), ...suffix];
for (const global of ["Object", "Function", "Reflect"])
if (isUnshadowedGlobal(root, state, global))
return finish(["intrinsic", global, ...suffix]);
for (const global of ["globalThis", "global", "window", "self"])
if (isUnshadowedGlobal(root, state, global))
return finish(["intrinsic", ...suffix]);
if (!t.isIdentifier(root)) return finish(undefined);
const binding = resolveSemanticBindingState(state, root, root.name);
const cached =
binding === undefined
? undefined
: intrinsicBindings.get(binding.bindingId);
if (cached !== undefined)
return finish(cached === null ? undefined : [...cached, ...suffix]);
const initializer = semanticStableInitializer(binding, state);
if (
binding === undefined ||
initializer === undefined ||
initializer.projection.some((segment) => segment === null) ||
visited.has(binding.bindingId)
)
return finish(undefined);
visited.add(binding.bindingId);
pending.push({ id: binding.bindingId, suffixLength: suffix.length });
suffix = [...initializer.projection.map(String), ...suffix];
current = initializer.node;
}
});
// A nominal alias path is sufficient for conservative mutation lookup, but
// helper proof also needs each read to follow initialization. An alias copy
@@ -263,7 +271,7 @@ export const createSemanticModuleInterop = (
const { root, members } = electronMemberPath(current.callee);
let bindTarget = root;
let bindingArguments: JavaScriptIntrinsicInvocation["arguments"] =
current.arguments;
expandJavaScriptInvocationArguments(current.arguments);
let captured = capturedIntrinsic(current.callee);
let terminal = captured?.path.at(-1) === "bind";
let path: readonly string[] | undefined = captured?.path.slice(0, -1);
@@ -6,6 +6,7 @@ import { javascriptRuntimeUnresolvedLocationSchema } from "./javascriptRuntimeOb
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { urlDeclaresQueryOrFragment } from "../urlComponents.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const nodeIdSchema = prefixedDigestSchema("jag_node");
@@ -53,8 +54,7 @@ const normalizeRuntimeUrlPrefix = (value: string): string | null => {
!["http:", "https:"].includes(url.protocol) ||
url.username !== "" ||
url.password !== "" ||
url.search !== "" ||
url.hash !== ""
urlDeclaresQueryOrFragment(url)
)
return null;
if (!url.pathname.endsWith("/")) url.pathname += "/";
@@ -0,0 +1,57 @@
import { expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
it.each([
{
name: "reconverging projections with different alias-cycle histories",
setup: `var x; const a = { foo: x, bar: globalThis }; x = a.bar;
const y = flag ? x : a.foo; y.URL = replacement;`,
specifier: null,
},
{
name: "growing self-reference projections with an ambient initializer",
setup: `let alias = globalThis; alias = alias.globalThis;
alias.URL = replacement;`,
specifier: null,
},
{
name: "distinct properties selecting both ambient identities",
setup: `const box = { left: globalThis, right: import.meta };
const selected = flag ? box.left : box.right; selected.URL = replacement;`,
specifier: null,
},
{
name: "cyclic containers with a reachable ambient property",
setup: `var alias; const box = { next: alias, target: import.meta };
alias = box; const selected = flag ? alias.target : alias.next.target;
selected.url = "file:///other/entry.mjs";`,
specifier: null,
},
{
name: "cycles containing no ambient identity",
setup: `var box; box = { next: box };
const selected = flag ? box : box.next; selected.URL = replacement;`,
specifier: "./worker.js",
},
{
name: "unrelated writes through widened self-reference projections",
setup: `let alias = globalThis; alias = alias.globalThis;
alias.unrelated = replacement;`,
specifier: "./worker.js",
},
{
name: "an exact empty projection into a shallow copy",
setup: `const copy = { ...globalThis };
const selected = flag ? copy : copy; selected.URL = replacement;`,
specifier: "./worker.js",
},
])("preserves $name", ({ setup, specifier }) => {
const source = `import { Worker } from "node:worker_threads";
${setup}
new Worker(new URL("./worker.js", import.meta.url));`;
const worker = analyzeJavaScriptStaticSource(source).references.find(
(reference) => reference.kind === "worker",
);
expect(worker?.specifier).toBe(specifier);
});
@@ -0,0 +1,301 @@
import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import {
collectJavaScriptIdentityWritesSteps,
electronMemberPath,
} from "./javascriptElectronMemberWrites.js";
import { createSemanticModuleInterop } from "./javascriptModuleInterop.js";
import {
isUnshadowedGlobal,
resolveSemanticBindingState,
semanticStableInitializer,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import { isImportMetaUrl } from "./javascriptStaticAnalysisHelpers.js";
const GLOBAL_OBJECT_NAMES = ["globalThis", "global", "window", "self"];
const globalObjectName = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | undefined =>
GLOBAL_OBJECT_NAMES.find((name) => isUnshadowedGlobal(node, state, name));
/** Global self references retain object identity, rather than adding a property. */
const canonicalAmbientPath = (
path: readonly (string | null)[],
): readonly (string | null)[] => {
if (path[0] !== "global") return path;
let firstProperty = 1;
while (GLOBAL_OBJECT_NAMES.includes(path[firstProperty] ?? ""))
firstProperty += 1;
return ["global", ...path.slice(firstProperty)];
};
type AmbientPath = readonly (string | null)[];
/** Undefined means a cyclic or conflicting projection can select any depth. */
type AmbientProjection = AmbientPath | undefined;
/**
* Follow local object identities without equating shallow copies with their
* sources. Write lookup retains every visible initializer: reassigning an alias
* later cannot erase a possible earlier mutation. Intrinsic reads stay strict.
*/
const createAmbientPathResolver = (
state: JavaScriptSemanticAnalysisState,
possibleWrites: boolean,
) => {
const cached = new WeakMap<t.Node, readonly AmbientPath[]>();
return (node: t.Node): readonly AmbientPath[] => {
const prior = cached.get(node);
if (prior !== undefined) return prior;
const result = new Map<string, AmbientPath>();
const pending: { node: t.Node; suffix: AmbientProjection }[] = [
{ node, suffix: [] },
];
// Join projections at their producing expression, rather than enumerating
// alias histories. Each key can only widen to a wildcard, and conflicting
// depths widen to unknown, so diamonds and cycles have finite state.
const expanded = new WeakMap<t.Node, AmbientProjection>();
const retain = (path: AmbientPath) => {
let canonical = canonicalAmbientPath(path);
for (;;) {
result.set(JSON.stringify(canonical), canonical);
// An unknown key may select a global self reference as well as a
// distinct property. Retain both possible object identities for writes.
if (
!possibleWrites ||
canonical[0] !== "global" ||
canonical[1] !== null
)
break;
canonical = canonicalAmbientPath(["global", ...canonical.slice(2)]);
}
};
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
const { root, members } = electronMemberPath(current.node);
let suffix: AmbientProjection =
current.suffix === undefined
? undefined
: [...members, ...current.suffix];
if (expanded.has(root)) {
const previous = expanded.get(root);
if (previous === undefined) continue;
if (suffix !== undefined && previous.length === suffix.length) {
const joined: AmbientPath = previous.map((key, index) =>
key === suffix?.[index] ? key : null,
);
if (joined.every((key, index) => key === previous[index])) continue;
suffix = joined;
} else suffix = undefined;
if (!possibleWrites) {
cached.set(node, []);
return [];
}
}
expanded.set(root, suffix);
// A widened projection is a possible write, never proof of an intrinsic.
if (suffix === undefined && !possibleWrites) continue;
const continueWith = (node: t.Node, path: AmbientProjection = suffix) =>
pending.push({ node, suffix: path });
if (
t.isMetaProperty(root) &&
root.meta.name === "import" &&
root.property.name === "meta"
) {
retain(["import-meta", ...(suffix ?? [])]);
continue;
}
if (t.isIdentifier(root)) {
if (globalObjectName(root, state) !== undefined) {
retain(["global", ...(suffix ?? [])]);
continue;
}
if (isUnshadowedGlobal(root, state, root.name)) {
retain(["global", root.name, ...(suffix ?? [])]);
continue;
}
const binding = resolveSemanticBindingState(state, root, root.name);
if (binding === undefined) continue;
const stable = semanticStableInitializer(binding, state);
const initializers = possibleWrites
? binding.initializers
: stable === undefined
? []
: [stable];
for (const initializer of initializers)
pending.push({
node: initializer.node,
suffix:
suffix === undefined
? undefined
: [
...initializer.projection.map((key) =>
key === null ? null : String(key),
),
...suffix,
],
});
continue;
}
if (possibleWrites && t.isConditionalExpression(root)) {
continueWith(root.consequent);
continueWith(root.alternate);
continue;
}
if (possibleWrites && t.isLogicalExpression(root)) {
continueWith(root.left);
continueWith(root.right);
continue;
}
const key = suffix?.[0];
if (suffix !== undefined && key === undefined) continue;
if (t.isObjectExpression(root)) {
if (possibleWrites) {
for (const property of root.properties) {
if (t.isSpreadElement(property)) continueWith(property.argument);
else if (
t.isObjectProperty(property) &&
t.isExpression(property.value)
) {
const ownKey = semanticStaticPropertyKey(
property.key,
property.computed,
);
if (
suffix === undefined ||
key === null ||
ownKey === null ||
ownKey === key
)
continueWith(property.value, suffix?.slice(1));
}
}
} else if (
suffix !== undefined &&
key !== null &&
root.properties.every(
(property) =>
t.isObjectProperty(property) &&
semanticStaticPropertyKey(property.key, property.computed) !==
null,
)
) {
const property = root.properties.findLast(
(property) =>
t.isObjectProperty(property) &&
semanticStaticPropertyKey(property.key, property.computed) ===
key,
);
if (t.isObjectProperty(property) && t.isExpression(property.value))
continueWith(property.value, suffix.slice(1));
}
} else if (t.isArrayExpression(root)) {
if (suffix === undefined) {
for (const element of root.elements)
if (t.isSpreadElement(element)) continueWith(element.argument);
else if (t.isExpression(element)) continueWith(element);
} else if (!root.elements.some(t.isSpreadElement)) {
const index = Number(key);
if (key === null && possibleWrites) {
for (const element of root.elements)
if (t.isExpression(element))
continueWith(element, suffix.slice(1));
} else if (
key !== null &&
Number.isInteger(index) &&
index >= 0 &&
String(index) === key
) {
const element = root.elements[index];
if (t.isExpression(element)) continueWith(element, suffix.slice(1));
}
}
}
}
const paths = [...result.values()];
cached.set(node, paths);
return paths;
};
};
/**
* Index source-local writes through ambient identities and stable aliases.
* The shared invocation owner resolves intrinsic aliases, bind/call/apply and
* literal argument spreads. Runtime reachability and arbitrary call effects
* remain unevaluated; a visible possible write is sufficient.
*/
export function* indexJavaScriptAmbientWritesSteps(
program: t.Program,
state: JavaScriptSemanticAnalysisState,
): Generator<void> {
const ambientReads = createAmbientPathResolver(state, false);
const ambientWrites = createAmbientPathResolver(state, true);
const interop = createSemanticModuleInterop(state, {
intrinsicPath: (node) => {
const [path] = ambientReads(node);
return path?.[0] === "global" && path.every((key) => key !== null)
? ["intrinsic", ...(path.slice(1) as readonly string[])]
: undefined;
},
});
yield* collectJavaScriptIdentityWritesSteps(
program,
(root, kind) => {
if (kind === "opaque-call") return [];
// Reassigning a local alias changes the binding, not the referenced object.
if (kind === "binding")
return t.isIdentifier(root) &&
isUnshadowedGlobal(root, state, root.name)
? [["global", root.name]]
: [];
return ambientWrites(root);
},
interop.intrinsicInvocation,
interop.staticString,
interop.isFreshObject,
(_node, path) => {
state.ambientWrites.retain(path);
},
);
}
/**
* Recognize an ambient name or direct global-object property without a visible
* source-local overwrite. This is a syntax-local identity fact, not proof that
* the runtime's globals have never been patched by other code.
*/
export const isUnmodifiedGlobalReference = (
callee: t.Node,
state: JavaScriptSemanticAnalysisState,
name: string,
): boolean => {
const node = unwrapJavaScriptExpression(callee).node;
if (state.ambientWrites.covers(["global", name])) return false;
if (isUnshadowedGlobal(node, state, name)) return true;
if (
!t.isMemberExpression(node) ||
semanticStaticPropertyKey(node.property, node.computed) !== name
)
return false;
const root = unwrapJavaScriptExpression(node.object).node;
const namespace = globalObjectName(root, state);
return (
namespace !== undefined &&
!state.ambientWrites.covers(["global", namespace])
);
};
/** A module URL base is known only while its property has no visible write. */
export const isUnmodifiedImportMetaUrl = (
node: t.Node | undefined,
state: JavaScriptSemanticAnalysisState,
): boolean =>
isImportMetaUrl(node) && !state.ambientWrites.covers(["import-meta", "url"]);
@@ -52,6 +52,36 @@ describe("TypeScript import-equals links", () => {
});
describe("CommonJS dependency links", () => {
it("retains an import-equals binding and its module origin", () => {
const ir = analyzeJavaScriptSemantics(`
import typed = require("dependency");
import type TypeOnly = require("type-only");
namespace Local { export class Marker {} }
import Alias = Local.Marker;
void typed;
`);
expect(topLevelBinding(ir, "typed")).toMatchObject({
kind: "import",
mutable: false,
provenance: {
origins: [{ specifier: "dependency", importedPath: [] }],
},
});
expect(
ir.moduleLinks.filter(({ specifier }) => specifier !== null),
).toEqual([
expect.objectContaining({
kind: "require",
specifier: "dependency",
importedName: null,
localName: "typed",
}),
]);
expect(ir.references.filter(({ name }) => name === "typed")).toHaveLength(
1,
);
});
it.each([
'require("dependency");',
'void require("dependency");',
@@ -148,7 +178,9 @@ describe("CommonJS dependency links", () => {
]);
expect(
ir.bindings.find(({ name }) => name === "bound")?.provenance.origins,
).toEqual([{ specifier: "bound", importedPath: [] }]);
).toEqual([
{ specifier: "bound", importedPath: [], resolutionMode: "require" },
]);
});
it.each([
@@ -179,6 +211,7 @@ it("preserves unshadowed require origins through aliases and assignments", () =>
expect(origin(topLevelBinding(ir, name))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
resolutionMode: "require",
});
expect(topLevelBinding(ir, "assigned").provenance).toMatchObject({
status: "ambiguous",
@@ -2,42 +2,128 @@ import { expect, it, vi } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import { onlyBinding } from "./javascriptSemanticAnalysis.fixture.js";
import type { JavaScriptSemanticIr } from "./javascriptSemanticIr.js";
/** Count AST ancestry lookups made while analyzing one source. */
const ancestryReads = (
source: string,
inspect: (ir: JavaScriptSemanticIr) => void,
): number => {
const original = WeakMap.prototype.get;
let reads = 0;
const get = vi.spyOn(WeakMap.prototype, "get").mockImplementation(function (
this: WeakMap<object, unknown>,
key,
) {
const value: unknown = original.call(this, key);
if (
typeof value === "object" &&
value !== null &&
"type" in value &&
typeof value.type === "string"
)
reads++;
return value;
});
try {
inspect(analyzeJavaScriptSemantics(source));
return reads;
} finally {
get.mockRestore();
}
};
it("bounds ancestry reads for repeated deep lexical references", () => {
const ancestryReads = (depth: number): number => {
const original = WeakMap.prototype.get;
let reads = 0;
const get = vi.spyOn(WeakMap.prototype, "get").mockImplementation(function (
this: WeakMap<object, unknown>,
key,
) {
const value: unknown = original.call(this, key);
if (
typeof value === "object" &&
value !== null &&
"type" in value &&
typeof value.type === "string"
)
reads++;
return value;
});
try {
const ir = analyzeJavaScriptSemantics(
`const a=1; module.exports.value=${"a+(".repeat(depth)}a${")".repeat(depth)};`,
);
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, "a").value).toEqual({
status: "literal",
value: 1,
});
return reads;
} finally {
get.mockRestore();
}
};
const reads = (depth: number): number =>
ancestryReads(
`const a=1; module.exports.value=${"a+(".repeat(depth)}a${")".repeat(depth)};`,
(ir) => {
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, "a").value).toEqual({
status: "literal",
value: 1,
});
},
);
const smaller = ancestryReads(80);
const larger = ancestryReads(160);
const smaller = reads(80);
const larger = reads(160);
expect(smaller).toBeGreaterThan(0);
expect(larger).toBeLessThan(3 * smaller);
});
it.each([
[
"object",
(index: number) => `var s${String(index + 1)}={x:s${String(index)}};`,
],
[
"array",
(index: number) => `var s${String(index + 1)}=[s${String(index)}];`,
],
[
"sequence-assigned object",
(index: number) =>
`var s${String(index + 1)}; 0, s${String(index + 1)}={x:s${String(index)}};`,
],
])(
"keeps the expression depth budget across a chain of %s wrappers",
(_, wrap) => {
// Reusing each wrapper's value for the next would nest without limit.
const nesting = (length: number): number => {
const ir = analyzeJavaScriptSemantics(
`var s0={};${Array.from({ length: length - 1 }, (unused, index) => wrap(index)).join("")}`,
);
let value = onlyBinding(ir, `s${String(length - 1)}`).value;
let depth = 0;
while (value.status === "object" || value.status === "array") {
const [slot] =
value.status === "object" ? value.properties : value.items;
if (slot === undefined) return depth;
value = slot.value;
depth++;
}
expect(value).toMatchObject({ resourceLimit: "expression-depth" });
expect(ir.coverage.status).toBe("partial");
return depth;
};
expect(nesting(40)).toBe(39);
const bounded = nesting(300);
expect(bounded).toBeLessThan(256);
expect(nesting(600)).toBe(bounded);
},
);
it.each([
["an object", "{ value: 1 }", "object"],
["a self-referential namespace", "s0 || {}", "ambiguous"],
["an unknown parameter", "seed", "unknown"],
])(
"bounds nested closures that alias %s from the enclosing scope",
(_, root, status) => {
// Each closure reads its parent's local once live and once at its own
// capture point; re-deriving the parent each time doubles work per level.
const reads = (depth: number): number =>
ancestryReads(
`function f0(seed){ var s0=${root};${Array.from(
{ length: depth - 1 },
(unused, index) =>
` function f${String(index + 1)}(){ var s${String(index + 1)}=s${String(index)};`,
).join("")}${"}".repeat(depth)}`,
(ir) => {
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, `s${String(depth - 1)}`).value).toEqual(
onlyBinding(ir, "s1").value,
);
expect(onlyBinding(ir, "s1").value.status).toBe(status);
},
);
const smaller = reads(8);
const larger = reads(16);
expect(smaller).toBeGreaterThan(0);
// Doubling per level would multiply the reads by 256.
expect(larger).toBeLessThan(8 * smaller);
},
);
@@ -38,10 +38,12 @@ describe("JavaScript semantic analysis: structure 1", () => {
expect(origin(topLevelBinding(ir, "bus"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
resolutionMode: "require",
});
expect(origin(topLevelBinding(ir, "forwarded"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
resolutionMode: "require",
});
expect(topLevelBinding(ir, "assigned").provenance).toMatchObject({
status: "ambiguous",
@@ -66,6 +68,7 @@ describe("JavaScript semantic analysis: structure 1", () => {
expect(origin(innerBus)).toEqual({
specifier: "./local-bus.js",
importedPath: [],
resolutionMode: "require",
});
const shadow = onlyBinding(ir, "ipcRenderer");
expect(shadow.provenance).toEqual({
@@ -42,6 +42,7 @@ import {
} from "./javascriptSemanticTraversal.js";
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { collectSemanticMemberMutationsSteps } from "./javascriptSemanticMemberMutations.js";
import { indexJavaScriptAmbientWritesSteps } from "./javascriptSemanticAmbientWrites.js";
import {
collectSemanticReturns,
resolveSemanticModuleCallables,
@@ -99,6 +100,7 @@ interface AddBindingInput {
readonly definitionNode: t.Node;
readonly initializer: t.Node | null;
readonly directOrigin?: JavaScriptModuleOrigin;
readonly runtimeImport?: boolean;
readonly projection?: readonly (string | number | null)[];
}
@@ -128,14 +130,18 @@ export function* indexJavaScriptBindingsSteps(
): Generator<void, JavaScriptSemanticAnalysisState> {
const state = createState(program);
yield* collectDefinitionsSteps(program, state);
yield* indexJavaScriptAmbientWritesSteps(program, state);
return state;
}
/** Recover semantics from an already parsed JavaScript artifact. */
export const analyzeParsedJavaScriptSemantics = (
file: ParsedJavaScriptSource,
staticImportResolutionMode: "import" | "require" = "import",
): JavaScriptSemanticIr =>
completeSemanticSteps(analyzeParsedJavaScriptSemanticsSteps(file));
completeSemanticSteps(
analyzeParsedJavaScriptSemanticsSteps(file, staticImportResolutionMode),
);
/**
* Recover semantics from a parsed artifact with a yield between analysis
@@ -145,8 +151,9 @@ export const analyzeParsedJavaScriptSemantics = (
*/
export function* analyzeParsedJavaScriptSemanticsSteps(
file: ParsedJavaScriptSource,
staticImportResolutionMode: "import" | "require" = "import",
): Generator<void, JavaScriptSemanticIr> {
const state = createState(file.program);
const state = createState(file.program, staticImportResolutionMode);
yield* collectDefinitionsSteps(file.program, state);
yield* collectSemanticMemberMutationsSteps(file.program, state);
yield* traverseJavaScriptAstSteps(file.program, {
@@ -159,7 +166,11 @@ export function* analyzeParsedJavaScriptSemanticsSteps(
yield;
const callables = collectSemanticReturns(state, parserPartial);
yield;
const moduleLinks = resolveSemanticModuleCallables(state, callables);
const moduleLinks = resolveSemanticModuleCallables(
state,
callables,
bindings,
);
const derived = yield* collectJavaScriptDerivedSemanticsSteps(
file.program,
state,
@@ -428,15 +439,18 @@ export function* indexJavaScriptElectronIdentitySteps(
};
yield* collectJavaScriptIdentityWritesSteps(
program,
(root, kind) => {
if (kind === "opaque-call") return interop.opaqueMutationPath(root);
(node, kind) => {
if (kind === "opaque-call") return [interop.opaqueMutationPath(node)];
const { root, members } = electronMemberPath(node);
const exported = kind === "binding" ? undefined : rootExport(root);
return exported === undefined
? (interop.intrinsicPath(root) ??
const path =
exported === undefined
? (interop.intrinsicPath(root) ??
(kind === "member"
? interop.boundIntrinsic(root)?.path
: undefined))
: ["electron", ...exported];
: ["electron", ...exported];
return path === undefined ? [] : [[...path, ...members]];
},
interop.intrinsicInvocation,
interop.staticString,
@@ -517,7 +531,10 @@ const bindingOrigin = (
: { ...origin, importedPath: [...origin.importedPath, ...projection] };
};
const createState = (program: t.Program): JavaScriptSemanticAnalysisState => {
const createState = (
program: t.Program,
staticImportResolutionMode: "import" | "require" = "import",
): JavaScriptSemanticAnalysisState => {
const root: JavaScriptSemanticScopeState = {
scopeId: semanticScopeId("program", program),
parentScopeId: null,
@@ -527,6 +544,7 @@ const createState = (program: t.Program): JavaScriptSemanticAnalysisState => {
bindings: new Map(),
};
return {
staticImportResolutionMode,
parentsByNode: new WeakMap(),
scopes: [root],
scopesById: new Map([[root.scopeId, root]]),
@@ -538,6 +556,7 @@ const createState = (program: t.Program): JavaScriptSemanticAnalysisState => {
linkedRequireCalls: new WeakSet(),
moduleLinkBindings: new WeakMap(),
conditionalInitializers: new WeakSet(),
ambientWrites: new SemanticPropertyPathCoverage(),
};
};
@@ -803,7 +822,7 @@ const bindImportEquals = (
mutable: false,
definitionNode: node.id,
initializer: null,
directOrigin: { specifier, importedPath: [] },
directOrigin: { specifier, importedPath: [], resolutionMode: "require" },
});
};
@@ -992,6 +1011,12 @@ const bindImports = (
definitionNode: specifier.local,
initializer: null,
directOrigin: { specifier: node.source.value, importedPath },
runtimeImport:
node.importKind !== "type" &&
node.importKind !== "typeof" &&
(!t.isImportSpecifier(specifier) ||
(specifier.importKind !== "type" &&
specifier.importKind !== "typeof")),
});
}
};
@@ -1168,6 +1193,7 @@ const addBinding = (input: AddBindingInput): void => {
definitionNode,
initializer,
directOrigin,
runtimeImport,
projection = [],
} = input;
let binding = scope.bindings.get(name);
@@ -1181,7 +1207,14 @@ const addBinding = (input: AddBindingInput): void => {
binding.definitions.push({ kind, location: range(definitionNode) });
if (initializer !== null)
binding.initializers.push({ node: initializer, projection });
if (directOrigin !== undefined) binding.directOrigins.push(directOrigin);
if (directOrigin !== undefined)
binding.directOrigins.push(
directOrigin.resolutionMode === undefined &&
state.staticImportResolutionMode === "require"
? { ...directOrigin, resolutionMode: "require" }
: directOrigin,
);
binding.runtimeImport ||= runtimeImport === true;
};
const createBinding = (
@@ -1201,6 +1234,7 @@ const createBinding = (
initializers: [],
referenceInitializers: [],
directOrigins: [],
runtimeImport: false,
});
const addAssignment = (
@@ -0,0 +1,81 @@
/** An immutable persistent binary trie over one state's binding identities. */
export type SemanticDependencyProof =
| true
| {
readonly zero: SemanticDependencyProof;
readonly one: SemanticDependencyProof;
}
| undefined;
/**
* Identity layout belongs to the indexed state, not to a query or its effects.
* Every proof has the same height. Union shares unchanged branches, so aliases
* add a path rather than copying their dependency's transitive membership set.
*/
export class SemanticDependencyProofs {
private readonly indices = new Map<string, number>();
private readonly singletons = new Map<string, SemanticDependencyProof>();
private readonly height: number;
constructor(bindings: Iterable<string>) {
for (const binding of bindings)
this.indices.set(binding, this.indices.size);
this.height = Math.ceil(Math.log2(Math.max(1, this.indices.size)));
}
binding(binding: string): SemanticDependencyProof {
const prior = this.singletons.get(binding);
if (prior !== undefined) return prior;
const index = this.index(binding);
let proof: SemanticDependencyProof = true;
for (let bit = 0; bit < this.height; bit++) {
const one = Math.floor(index / 2 ** bit) % 2 === 1;
proof = Object.freeze({
zero: one ? undefined : proof,
one: one ? proof : undefined,
});
}
this.singletons.set(binding, proof);
return proof;
}
union(
first: SemanticDependencyProof,
second: SemanticDependencyProof,
): SemanticDependencyProof {
if (first === second || second === undefined) return first;
if (first === undefined) return second;
if (first === true || second === true) return true;
const zero = this.union(first.zero, second.zero);
const one = this.union(first.one, second.one);
if (zero === first.zero && one === first.one) return first;
if (zero === second.zero && one === second.one) return second;
return Object.freeze({ zero, one });
}
intersects(
proof: SemanticDependencyProof,
active: ReadonlyMap<string, number>,
): boolean {
for (const binding of active.keys())
if (this.has(proof, binding)) return true;
return false;
}
has(proof: SemanticDependencyProof, binding: string): boolean {
const index = this.index(binding);
for (let bit = this.height - 1; bit >= 0; bit--) {
if (proof === undefined) return false;
if (proof === true) return true;
proof = Math.floor(index / 2 ** bit) % 2 === 1 ? proof.one : proof.zero;
}
return proof === true;
}
private index(binding: string): number {
const index = this.indices.get(binding);
if (index === undefined)
throw new TypeError(`Unindexed semantic dependency: ${binding}`);
return index;
}
}
@@ -7,6 +7,7 @@ import type {
/** One exact module origin followed through imports, requires, or aliases. */
export interface JavaScriptModuleOrigin {
readonly resolutionMode?: "import" | "require";
readonly specifier: string;
readonly importedPath: readonly string[];
}
@@ -392,8 +393,10 @@ export interface JavaScriptSemanticFrontier {
/** Static import/export relationship retained for cross-file composition. */
export interface JavaScriptSemanticModuleLink {
readonly resolutionMode?: "import" | "require";
readonly kind:
| "import"
| "type-import"
| "require"
| "export"
| "re-export"
@@ -6,7 +6,7 @@ import {
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import {
clearSemanticPrimitiveBindingValues,
clearSemanticValueCaches,
evaluateSemanticBinding,
evaluateSemanticExpression,
} from "./javascriptSemanticValues.js";
@@ -256,7 +256,7 @@ export function* collectSemanticMemberMutationsSteps(
if (effect === "escape")
binding.escapedPaths.push({ path, node: mutation });
else binding.mutatedPaths.push(path);
clearSemanticPrimitiveBindingValues(state);
clearSemanticValueCaches(state);
for (const initializer of origins.initializers)
pending.push({
node: initializer.node,
@@ -548,7 +548,7 @@ export function* collectSemanticMemberMutationsSteps(
}
// Gathering effects can evaluate a primitive projection before its object
// escapes. Final values must use the completed mutation state.
clearSemanticPrimitiveBindingValues(state);
clearSemanticValueCaches(state);
}
interface ReferencedValue {
@@ -54,6 +54,7 @@ describe("parameter references copied into function body bindings", () => {
initializers: [entry, assigned],
referenceInitializers: [],
directOrigins: [],
runtimeImport: false,
};
const origins = semanticMutationInitializers(binding, mutation, parents);
expect(origins.initializers.includes(entry)).toBe(retained);
@@ -669,19 +669,26 @@ export const semanticReferenceRole = (
return "read";
};
const isDeclarationIdentifier = (node: t.Identifier, parent: t.Node): boolean =>
(t.isVariableDeclarator(parent) && patternContains(parent.id, node)) ||
((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&
parent.id === node) ||
(t.isFunction(parent) &&
parent.params.some((value) => patternContains(value, node))) ||
((t.isClassDeclaration(parent) || t.isClassExpression(parent)) &&
parent.id === node) ||
(t.isImportSpecifier(parent) &&
(parent.local === node || parent.imported === node)) ||
(t.isImportDefaultSpecifier(parent) && parent.local === node) ||
(t.isImportNamespaceSpecifier(parent) && parent.local === node) ||
(t.isCatchClause(parent) && parent.param === node);
const isDeclarationIdentifier = (
node: t.Identifier,
parent: t.Node,
): boolean => {
if (t.isTSImportEqualsDeclaration(parent)) return parent.id === node;
return (
(t.isVariableDeclarator(parent) && patternContains(parent.id, node)) ||
((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&
parent.id === node) ||
(t.isFunction(parent) &&
parent.params.some((value) => patternContains(value, node))) ||
((t.isClassDeclaration(parent) || t.isClassExpression(parent)) &&
parent.id === node) ||
(t.isImportSpecifier(parent) &&
(parent.local === node || parent.imported === node)) ||
(t.isImportDefaultSpecifier(parent) && parent.local === node) ||
(t.isImportNamespaceSpecifier(parent) && parent.local === node) ||
(t.isCatchClause(parent) && parent.param === node)
);
};
const isNonReferenceKey = (node: t.Identifier, parent: t.Node): boolean =>
((t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) &&
@@ -48,7 +48,11 @@ export const uniqueSemanticOrigins = (
);
const semanticOriginKey = (origin: JavaScriptModuleOrigin): string =>
JSON.stringify([origin.specifier, origin.importedPath]);
JSON.stringify([
origin.specifier,
origin.importedPath,
origin.resolutionMode ?? "import",
]);
/** Canonically distinguish primitive values across type boundaries. */
export const semanticPrimitiveKey = (
@@ -54,7 +54,11 @@ export const semanticRequireOrigin = (
return specifier === undefined
? undefined
: {
origin: { specifier, importedPath: members.reverse() },
origin: {
specifier,
importedPath: members.reverse(),
resolutionMode: "require",
},
call: current,
};
};
@@ -6,6 +6,7 @@ import {
} from "./javascriptSemanticSlots.js";
import type {
JavaScriptSemanticBinding,
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
JavaScriptSemanticReturnSite,
@@ -89,12 +90,16 @@ const semanticReturnSiteId = (
String(location.end.column),
].join(":");
/** Link exports to callables only when lexical resolution is unique and exact. */
/** Finalize exported bindings only when lexical resolution is unique and exact. */
export const resolveSemanticModuleCallables = (
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
bindings: readonly JavaScriptSemanticBinding[],
): JavaScriptSemanticModuleLink[] => {
const callableIds = new Set(callables.map(({ callableId }) => callableId));
const provenanceByBinding = new Map(
bindings.map(({ bindingId, provenance }) => [bindingId, provenance]),
);
return state.moduleLinks.map((link) => {
// Named exports follow their lexical binding, including every assignment.
// A declaration's ID or a callable's display name cannot prove that link.
@@ -107,8 +112,19 @@ export const resolveSemanticModuleCallables = (
binding === undefined
? []
: callableIdsForBinding(binding, state, callableIds, new Set());
const provenance =
binding === undefined || link.specifier !== null
? undefined
: provenanceByBinding.get(binding.bindingId);
const resolutionMode =
provenance?.status === "module"
? provenance.origins[0].resolutionMode
: undefined;
return {
...link,
...(resolutionMode === "import" || resolutionMode === "require"
? { resolutionMode }
: {}),
callableId: resolved.length === 1 ? (resolved[0] ?? null) : null,
};
});
@@ -1,6 +1,9 @@
import * as t from "@babel/types";
import type { JavaScriptSemanticPropertyPath } from "./javascriptSemanticPropertyPaths.js";
import type {
JavaScriptSemanticPropertyPath,
SemanticPropertyPathCoverage,
} from "./javascriptSemanticPropertyPaths.js";
import type {
JavaScriptModuleOrigin,
@@ -43,6 +46,8 @@ export interface JavaScriptSemanticBindingState {
readonly initializers: JavaScriptSemanticInitializer[];
readonly referenceInitializers: JavaScriptSemanticReferenceInitializer[];
readonly directOrigins: JavaScriptModuleOrigin[];
/** An ECMAScript import that exists at runtime, excluding type-only and import-equals syntax. */
runtimeImport: boolean;
}
/** Mutable lexical-scope state used only during AST recovery. */
@@ -57,6 +62,8 @@ export interface JavaScriptSemanticScopeState {
/** Shared state for semantic collection and evaluation. */
export interface JavaScriptSemanticAnalysisState {
/** Effective loader for static imports in this source artifact. */
readonly staticImportResolutionMode: "import" | "require";
readonly parentsByNode: WeakMap<t.Node, t.Node>;
readonly scopes: JavaScriptSemanticScopeState[];
readonly scopesById: Map<string, JavaScriptSemanticScopeState>;
@@ -73,6 +80,8 @@ export interface JavaScriptSemanticAnalysisState {
JavaScriptSemanticBindingState
>;
readonly conditionalInitializers: WeakSet<t.Node>;
/** Source-local writes, tagged by global-object or import.meta identity. */
readonly ambientWrites: SemanticPropertyPathCoverage;
}
/**
@@ -0,0 +1,227 @@
import { expect, it, vi } from "vitest";
import {
analyzeJavaScriptSemantics,
indexJavaScriptBindingsSteps,
} from "./javascriptSemanticAnalysis.js";
import { SemanticDependencyProofs } from "./javascriptSemanticDependencies.js";
import type { JavaScriptSemanticValue } from "./javascriptSemanticValueTypes.js";
import {
clearSemanticValueCaches,
evaluateSemanticBinding,
evaluateSemanticProvenance,
} from "./javascriptSemanticValues.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
const property = (
value: JavaScriptSemanticValue,
name: string,
): JavaScriptSemanticValue => {
if (value.status !== "object")
throw new Error(`Expected object at ${name}, got ${value.status}`);
const result = value.properties.find((entry) => entry.name === name)?.value;
if (result === undefined) throw new Error(`Missing ${name}`);
return result;
};
it.each([false, true])(
"recomputes a shared cyclic value under a different active ancestor (prewarmed: %s)",
(prewarmed) => {
const parsed = parseJavaScriptSource(
`
const a = { shared: common, own: "a" };
const b = { shared: common, own: "b" };
const common = { a, b };
const result = { first: a, second: b };
`,
"cycles.js",
);
if (parsed === null) throw new Error("Expected parsed source");
const steps = indexJavaScriptBindingsSteps(parsed.program);
let step = steps.next();
while (step.done !== true) step = steps.next();
const state = step.value;
const binding = [...state.bindingsById.values()].find(
(entry) => entry.name === "result",
);
if (binding === undefined) throw new Error("Missing result binding");
if (prewarmed)
for (const entry of state.bindingsById.values())
if (entry.name === "a" || entry.name === "b")
evaluateSemanticBinding(entry, state);
const value = evaluateSemanticBinding(binding, state);
const firstCommon = property(property(value, "first"), "shared");
const secondCommon = property(property(value, "second"), "shared");
expect(property(firstCommon, "a").status).toBe("cycle");
expect(property(property(firstCommon, "b"), "own")).toEqual({
status: "literal",
value: "b",
});
expect(property(secondCommon, "b").status).toBe("cycle");
expect(property(property(secondCommon, "a"), "own")).toEqual({
status: "literal",
value: "a",
});
},
);
it("invalidates retained alias values at the producing mutation boundary", () => {
const parsed = parseJavaScriptSource(
"const target = { value: 1 }; const alias = target; const root = { alias };",
"mutation.js",
);
if (parsed === null) throw new Error("Expected parsed source");
const steps = indexJavaScriptBindingsSteps(parsed.program);
let step = steps.next();
while (step.done !== true) step = steps.next();
const state = step.value;
const target = [...state.bindingsById.values()].find(
({ name }) => name === "target",
);
const root = [...state.bindingsById.values()].find(
({ name }) => name === "root",
);
if (target === undefined || root === undefined)
throw new Error("Missing binding");
expect(
property(property(evaluateSemanticBinding(root, state), "alias"), "value"),
).toEqual({ status: "literal", value: 1 });
target.mutatedPaths.push(["value"]);
clearSemanticValueCaches(state);
expect(
property(property(evaluateSemanticBinding(root, state), "alias"), "value")
.status,
).toBe("unknown");
});
const balancedOr = (names: string[]): string => {
if (names.length === 1) return names[0]!;
const middle = Math.floor(names.length / 2);
return `(${balancedOr(names.slice(0, middle))} || ${balancedOr(names.slice(middle))})`;
};
it("shares dependency proofs across a shallow wide reconvergent graph", () => {
const measure = (width: number) => {
const imports = Array.from({ length: width }, (_, index) => `l${index}`);
const aliases = Array.from({ length: width }, (_, index) => `a${index}`);
const source = `${imports.map((name) => `import * as ${name} from "fs";`).join("\n")}
const shared = ${balancedOr(imports)};
function consumer() {
${aliases.map((name) => `const ${name} = shared;`).join("\n")}
const root = ${balancedOr(aliases)};
}`;
const parsed = parseJavaScriptSource(source, "wide.js");
if (parsed === null) throw new Error("Expected parsed source");
const steps = indexJavaScriptBindingsSteps(parsed.program);
let step = steps.next();
while (step.done !== true) step = steps.next();
const state = step.value;
const rootBinding = [...state.bindingsById.values()].find(
({ name }) => name === "root",
);
if (rootBinding === undefined) throw new Error("Missing root binding");
// One root query simultaneously retains every alias memo in this family.
// Separate per-binding provenance queries have baseline repeated traversal;
// they must not be confused with this cache's retained closure expansion.
// Count representation construction and union work, not elapsed time/heap.
// Binding-ID additions also discriminate the superseded flattened Sets.
let bindingMemberships = 0;
let proofBranches = 0;
let unionCalls = 0;
const add = Set.prototype.add;
const freeze = Object.freeze;
const union = SemanticDependencyProofs.prototype.union;
const addSpy = vi.spyOn(Set.prototype, "add").mockImplementation(function (
this: Set<unknown>,
value: unknown,
) {
if (typeof value === "string" && value.includes("binding:"))
bindingMemberships++;
return add.call(this, value);
});
const freezeSpy = vi.spyOn(Object, "freeze").mockImplementation((value) => {
if (
typeof value === "object" &&
value !== null &&
Object.hasOwn(value, "zero") &&
Object.hasOwn(value, "one") &&
Object.keys(value).length === 2
)
proofBranches++;
return freeze(value);
});
const unionSpy = vi
.spyOn(SemanticDependencyProofs.prototype, "union")
.mockImplementation(function (
this: SemanticDependencyProofs,
first,
second,
) {
unionCalls++;
return union.call(this, first, second);
});
try {
expect(evaluateSemanticBinding(rootBinding, state).status).toBe(
"ambiguous",
);
expect(evaluateSemanticProvenance(rootBinding, state).origins).toEqual([
{ specifier: "fs", importedPath: [] },
]);
} finally {
unionSpy.mockRestore();
freezeSpy.mockRestore();
addSpy.mockRestore();
}
const result = analyzeJavaScriptSemantics(source);
expect(result.coverage).toEqual({ status: "complete", omittedCount: 0 });
for (const name of [...imports, ...aliases, "shared", "root"])
expect(
result.bindings.filter((entry) => entry.name === name),
).toHaveLength(1);
const root = result.bindings.find((entry) => entry.name === "root");
expect(root?.value.status).toBe("ambiguous");
expect(root?.provenance.origins).toEqual([
{ specifier: "fs", importedPath: [] },
]);
return {
storage: bindingMemberships + proofBranches,
work: bindingMemberships + unionCalls,
};
};
// Balanced depths remain small; doubling both independent widths must not
// quadruple proof construction/work while all meaningful aliases survive.
const small = measure(32);
const large = measure(64);
expect(small.storage).toBeGreaterThan(0);
expect(small.work).toBeGreaterThan(0);
expect(large.storage).toBeLessThan(small.storage * 3);
expect(large.work).toBeLessThan(small.work * 3);
});
it("uses immutable exact identity proofs and shares unchanged union branches", () => {
const proofs = new SemanticDependencyProofs(["a", "b", "c", "d", "e"]);
const a = proofs.binding("a");
const b = proofs.binding("b");
const c = proofs.binding("c");
const ab = proofs.union(a, b);
const abc = proofs.union(ab, c);
expect(proofs.union(abc, ab)).toBe(abc);
expect(proofs.binding("a")).toBe(a);
expect(Object.isFrozen(abc)).toBe(true);
expect(["a", "b", "c", "d", "e"].map((id) => proofs.has(abc, id))).toEqual([
true,
true,
true,
false,
false,
]);
expect(proofs.has(undefined, "a")).toBe(false);
expect(proofs.intersects(abc, new Map([["d", 0]]))).toBe(false);
expect(proofs.intersects(abc, new Map([["c", 0]]))).toBe(true);
const single = new SemanticDependencyProofs(["only"]);
expect(single.has(single.binding("only"), "only")).toBe(true);
expect(single.has(undefined, "only")).toBe(false);
expect(() => proofs.binding("unindexed")).toThrow(
"Unindexed semantic dependency",
);
});
+257 -31
View File
@@ -1,5 +1,10 @@
import * as t from "@babel/types";
import {
SemanticDependencyProofs,
type SemanticDependencyProof,
} from "./javascriptSemanticDependencies.js";
import {
semanticCapturePosition,
semanticEscapeFollowsCapture,
@@ -51,14 +56,74 @@ import {
semanticResourceLimitReason,
} from "./javascriptSemanticResourceLimits.js";
interface MemoizedEvaluation<T> {
readonly value: T;
readonly dependencies: SemanticDependencyProof;
}
/** Provenance lives for one query; live values belong to the effects-aware state. */
interface EvaluationMemo {
readonly provenance: Map<
string,
Map<number, MemoizedEvaluation<JavaScriptBindingProvenance>>
>;
readonly dependencyFrames: { proof: SemanticDependencyProof }[];
readonly dependencies: SemanticDependencyProofs;
}
// Indexing owns stable binding identities; effects invalidate values, not this
// identity-only layout. No query result or dependency closure is retained here.
const dependencyProofsByState = new WeakMap<
JavaScriptSemanticAnalysisState,
SemanticDependencyProofs
>();
const createEvaluationMemo = (
state: JavaScriptSemanticAnalysisState,
): EvaluationMemo => {
let dependencies = dependencyProofsByState.get(state);
if (dependencies === undefined) {
dependencies = new SemanticDependencyProofs(state.bindingsById.keys());
dependencyProofsByState.set(state, dependencies);
}
return { provenance: new Map(), dependencyFrames: [], dependencies };
};
interface EvaluationContext {
readonly state: JavaScriptSemanticAnalysisState;
readonly bindings: Set<string>;
/** Bindings under evaluation, by their position on the active stack. */
readonly bindings: Map<string, number>;
readonly expressionDepth: number;
readonly capturePoint?: t.Node;
readonly primitiveBindingValues: Map<string, JavaScriptSemanticValue>;
readonly dependence: EvaluationDependence;
readonly memo: EvaluationMemo;
}
/**
* How far up the active stack the value being evaluated depends on its
* caller. An alias cycle depends on the position of its head; the expression
* depth budget depends on every caller. A binding whose value depends only on
* positions pushed after its own evaluates to that value from any caller
* with at least as much of the depth budget left.
*/
interface EvaluationDependence {
lowest: number;
}
const CALLER_INDEPENDENT = Number.POSITIVE_INFINITY;
const EVERY_CALLER = -1;
/** A value no caller changes, and the deepest evaluation known to yield it. */
interface CallerIndependentBindingValue extends MemoizedEvaluation<JavaScriptSemanticValue> {
readonly expressionDepth: number;
}
const callerIndependentBindingValuesByState = new WeakMap<
JavaScriptSemanticAnalysisState,
Map<string, CallerIndependentBindingValue>
>();
const primitiveBindingValuesByState = new WeakMap<
JavaScriptSemanticAnalysisState,
Map<string, JavaScriptSemanticValue>
@@ -74,13 +139,24 @@ const capturedBindingValuesByState = new WeakMap<
WeakMap<t.Node, Map<string, JavaScriptSemanticValue>>
>();
/** Discard primitive projections evaluated before mutation collection finished. */
export const clearSemanticPrimitiveBindingValues = (
/** Discard every state-owned value derived before the effects boundary changed. */
export const clearSemanticValueCaches = (
state: JavaScriptSemanticAnalysisState,
): void => {
primitiveBindingValuesByState.delete(state);
capturedBindingValuesByState.delete(state);
primitiveExpressionValuesByState.delete(state);
callerIndependentBindingValuesByState.delete(state);
};
const callerIndependentBindingValuesFor = (
state: JavaScriptSemanticAnalysisState,
): Map<string, CallerIndependentBindingValue> => {
const existing = callerIndependentBindingValuesByState.get(state);
if (existing !== undefined) return existing;
const values = new Map<string, CallerIndependentBindingValue>();
callerIndependentBindingValuesByState.set(state, values);
return values;
};
const primitiveBindingValuesFor = (
@@ -109,9 +185,11 @@ export const evaluateSemanticBinding = (
): JavaScriptSemanticValue =>
evaluateBinding(binding, {
state,
bindings: new Set(),
bindings: new Map(),
expressionDepth: 0,
primitiveBindingValues: primitiveBindingValuesFor(state),
dependence: { lowest: CALLER_INDEPENDENT },
memo: createEvaluationMemo(state),
});
/** Evaluate an inert expression, optionally at an earlier reference capture. */
@@ -122,9 +200,11 @@ export const evaluateSemanticExpression = (
): JavaScriptSemanticValue => {
const context: EvaluationContext = {
state,
bindings: new Set(),
bindings: new Map(),
expressionDepth: 0,
primitiveBindingValues: primitiveBindingValuesFor(state),
dependence: { lowest: CALLER_INDEPENDENT },
memo: createEvaluationMemo(state),
};
return evaluateExpression(
node,
@@ -141,17 +221,69 @@ export const evaluateSemanticProvenance = (
): JavaScriptBindingProvenance =>
provenanceForBinding(binding, {
state,
bindings: new Set(),
bindings: new Map(),
expressionDepth: 0,
primitiveBindingValues: primitiveBindingValuesFor(state),
dependence: { lowest: CALLER_INDEPENDENT },
memo: createEvaluationMemo(state),
});
const readMemoizedEvaluation = <T>(
entry: MemoizedEvaluation<T> | undefined,
context: EvaluationContext,
): T | undefined => {
if (
entry === undefined ||
context.memo.dependencies.intersects(entry.dependencies, context.bindings)
)
return undefined;
retainDependencyProof(entry.dependencies, context);
return entry.value;
};
const retainDependencyProof = (
proof: SemanticDependencyProof,
context: EvaluationContext,
): void => {
const parent = context.memo.dependencyFrames.at(-1);
if (parent !== undefined)
parent.proof = context.memo.dependencies.union(parent.proof, proof);
};
const recordBindingDependency = (
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
): void =>
retainDependencyProof(
context.memo.dependencies.binding(binding.bindingId),
context,
);
const collectEvaluationDependencies = <T>(
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
evaluate: () => T,
): MemoizedEvaluation<T> => {
const frame = { proof: context.memo.dependencies.binding(binding.bindingId) };
context.memo.dependencyFrames.push(frame);
try {
return { value: evaluate(), dependencies: frame.proof };
} finally {
context.memo.dependencyFrames.pop();
retainDependencyProof(frame.proof, context);
}
};
const evaluateBinding = (
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
): JavaScriptSemanticValue => {
if (context.bindings.has(binding.bindingId))
recordBindingDependency(binding, context);
const cycleHead = context.bindings.get(binding.bindingId);
if (cycleHead !== undefined) {
context.dependence.lowest = Math.min(context.dependence.lowest, cycleHead);
return { status: "cycle", reason: `Alias cycle at ${binding.name}.` };
}
if (
context.capturePoint !== undefined &&
!semanticBindingPrecedesCapture(
@@ -168,6 +300,22 @@ const evaluateBinding = (
}
const cached = context.primitiveBindingValues.get(binding.bindingId);
if (cached !== undefined) return cached;
// Each closure that aliases an outer binding evaluates it both live and at
// its capture point, so re-deriving it doubles the work at every level of
// nesting. A deeper reader derives it again: the retained value would carry
// more nesting than the remaining depth budget allows it to observe.
const independent =
context.capturePoint === undefined
? callerIndependentBindingValuesFor(context.state)
: undefined;
const retained = independent?.get(binding.bindingId);
if (
retained !== undefined &&
context.expressionDepth <= retained.expressionDepth
) {
const reusable = readMemoizedEvaluation(retained, context);
if (reusable !== undefined) return reusable;
}
if (binding.initializers.length === 0)
return {
status: "unknown",
@@ -196,26 +344,44 @@ const evaluateBinding = (
const initializer = binding.initializers[0];
if (initializer === undefined)
return { status: "unknown", reason: "Missing binding initializer." };
context.bindings.add(binding.bindingId);
const position = context.bindings.size;
const callerDependence = context.dependence.lowest;
context.dependence.lowest = CALLER_INDEPENDENT;
context.bindings.set(binding.bindingId, position);
let value: JavaScriptSemanticValue;
let callerIndependent = false;
let evaluated: MemoizedEvaluation<JavaScriptSemanticValue>;
try {
const nested = nestedContext(context);
value = projectValue(
evaluateExpression(initializer.node, nested),
initializer.projection,
);
if (!isPrimitive(value)) {
const captureContext = primitiveCaptureContext(initializer.node, nested);
if (captureContext !== undefined) {
const captured = projectValue(
evaluateExpression(initializer.node, captureContext),
initializer.projection,
evaluated = collectEvaluationDependencies(binding, context, () => {
const nested = nestedContext(context);
let value = projectValue(
evaluateExpression(initializer.node, nested),
initializer.projection,
);
if (!isPrimitive(value)) {
const captureContext = primitiveCaptureContext(
initializer.node,
nested,
);
if (isPrimitive(captured)) value = captured;
if (captureContext !== undefined) {
const captured = projectValue(
evaluateExpression(initializer.node, captureContext),
initializer.projection,
);
if (isPrimitive(captured)) value = captured;
}
}
}
return value;
});
value = evaluated.value;
// A cycle among bindings this one reads is part of its value. A cycle
// through this binding is cut elsewhere when a caller holds another member.
callerIndependent = context.dependence.lowest > position;
} finally {
context.bindings.delete(binding.bindingId);
context.dependence.lowest = callerIndependent
? callerDependence
: Math.min(callerDependence, context.dependence.lowest);
}
let projected = invalidateSemanticMutationPaths(value, binding.mutatedPaths);
for (const escape of binding.escapedPaths) {
@@ -233,6 +399,17 @@ const evaluateBinding = (
continue;
projected = invalidateSemanticEscapedPath(projected, escape.path);
}
if (
callerIndependent &&
independent !== undefined &&
(retained === undefined ||
retained.expressionDepth < context.expressionDepth)
)
independent.set(binding.bindingId, {
value: projected,
dependencies: evaluated.dependencies,
expressionDepth: context.expressionDepth,
});
// Point-local memoization also bounds failed speculative captures. Only a
// primitive result is allowed back into ordinary value evaluation.
if (
@@ -251,15 +428,19 @@ const evaluateExpression = (
node: t.Node,
context: EvaluationContext,
): JavaScriptSemanticValue => {
if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT)
if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT) {
context.dependence.lowest = EVERY_CALLER;
return semanticResourceLimitUnknown("expression-depth");
}
const unwrapped = unwrapJavaScriptExpression(node);
if (unwrapped.depth > 0) {
if (
context.expressionDepth + unwrapped.depth >
SEMANTIC_EXPRESSION_DEPTH_LIMIT
)
) {
context.dependence.lowest = EVERY_CALLER;
return semanticResourceLimitUnknown("expression-depth");
}
return evaluateExpression(unwrapped.node, {
...context,
expressionDepth: context.expressionDepth + unwrapped.depth,
@@ -567,6 +748,50 @@ const projectValue = (
const provenanceForBinding = (
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
): JavaScriptBindingProvenance => {
recordBindingDependency(binding, context);
const cycleHead = context.bindings.get(binding.bindingId);
if (cycleHead !== undefined) {
context.dependence.lowest = Math.min(context.dependence.lowest, cycleHead);
return semanticUnresolvedProvenance(
"cycle",
`Alias cycle at ${binding.name}.`,
);
}
let depths = context.memo.provenance.get(binding.bindingId);
const prior = readMemoizedEvaluation(
depths?.get(context.expressionDepth),
context,
);
if (prior !== undefined) return prior;
const position = context.bindings.size;
const callerDependence = context.dependence.lowest;
context.dependence.lowest = CALLER_INDEPENDENT;
let result: MemoizedEvaluation<JavaScriptBindingProvenance>;
let callerIndependent = false;
try {
result = collectEvaluationDependencies(binding, context, () =>
provenanceForBindingUncached(binding, context),
);
callerIndependent = context.dependence.lowest > position;
} finally {
context.dependence.lowest = callerIndependent
? callerDependence
: Math.min(callerDependence, context.dependence.lowest);
}
if (callerIndependent) {
if (depths === undefined) {
depths = new Map();
context.memo.provenance.set(binding.bindingId, depths);
}
depths.set(context.expressionDepth, result);
}
return result.value;
};
const provenanceForBindingUncached = (
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
): JavaScriptBindingProvenance => {
const provenance = provenanceForBindingValue(binding, context);
const assigned = binding.definitions.some(
@@ -592,11 +817,6 @@ const provenanceForBindingValue = (
binding: JavaScriptSemanticBindingState,
context: EvaluationContext,
): JavaScriptBindingProvenance => {
if (context.bindings.has(binding.bindingId))
return semanticUnresolvedProvenance(
"cycle",
`Alias cycle at ${binding.name}.`,
);
if (binding.directOrigins.length > 0)
return semanticOriginsProvenance(binding.directOrigins);
if (binding.initializers.length === 0) return semanticLocalProvenance();
@@ -616,7 +836,7 @@ const provenanceForBindingValue = (
"unknown",
"Dynamic provenance projection.",
);
context.bindings.add(binding.bindingId);
context.bindings.set(binding.bindingId, context.bindings.size);
let resolved: JavaScriptBindingProvenance;
try {
resolved = provenanceForExpression(
@@ -643,21 +863,25 @@ const provenanceForExpression = (
node: t.Node,
context: EvaluationContext,
): JavaScriptBindingProvenance => {
if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT)
if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT) {
context.dependence.lowest = EVERY_CALLER;
return semanticUnresolvedProvenance(
"unknown",
semanticResourceLimitReason("expression-depth"),
);
}
const unwrapped = unwrapJavaScriptExpression(node);
if (unwrapped.depth > 0) {
if (
context.expressionDepth + unwrapped.depth >
SEMANTIC_EXPRESSION_DEPTH_LIMIT
)
) {
context.dependence.lowest = EVERY_CALLER;
return semanticUnresolvedProvenance(
"unknown",
semanticResourceLimitReason("expression-depth"),
);
}
return provenanceForExpression(unwrapped.node, {
...context,
expressionDepth: context.expressionDepth + unwrapped.depth,
@@ -763,6 +987,8 @@ const nestedContext = (context: EvaluationContext): EvaluationContext => ({
: { capturePoint: context.capturePoint }),
expressionDepth: context.expressionDepth + 1,
bindings: context.bindings,
dependence: context.dependence,
memo: context.memo,
});
const isPrimitive = (value: JavaScriptSemanticValue): boolean =>
@@ -1,4 +1,4 @@
import { parse, type ParserPlugin } from "@babel/parser";
import { parse, type ParserOptions, type ParserPlugin } from "@babel/parser";
/** Babel AST produced by REA's inert JavaScript parser boundary. */
export type ParsedJavaScriptSource = ReturnType<typeof parse>;
@@ -37,6 +37,67 @@ export const parserPluginsForPath = (sourcePath?: string): ParserPlugin[] => {
: ["decorators-legacy", typescript];
};
/** `.mjs` and `.mts` are modules by extension; other paths leave the mode to syntax. */
export const isExplicitModuleSourcePath = (path?: string): boolean =>
/\.m[jt]s$/iu.test(path ?? "");
export interface RecoveredJavaScriptParse {
readonly file: ParsedJavaScriptSource;
/** Errors that apply only if a source of unknown mode is an ES module. */
readonly moduleOnlyErrors: readonly string[];
}
/**
* Parse a module or script with recovery. Babel tries module mode first and
* keeps its strict-mode errors after falling back to a script, so a script
* with errors is parsed again as a script. Strict errors that only the module
* parse reports stay visible because the source may still be a module.
*/
export const parseRecoveredJavaScript = (
source: string,
sourcePath: string | undefined,
options: Omit<ParserOptions, "sourceType" | "errorRecovery">,
): RecoveredJavaScriptParse => {
// `.cjs` is CommonJS by extension, so module-only errors cannot apply.
if (/\.cjs$/iu.test(sourcePath ?? ""))
return {
file: parse(source, {
...options,
sourceType: "script",
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
if (isExplicitModuleSourcePath(sourcePath))
return {
file: parse(source, {
...options,
sourceType: "module",
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
const file = parse(source, {
...options,
sourceType: "unambiguous",
errorRecovery: true,
});
if (file.program.sourceType !== "script" || file.errors.length === 0)
return { file, moduleOnlyErrors: [] };
const script = parse(source, {
...options,
sourceType: "script",
errorRecovery: true,
});
const scriptErrors = new Set(script.errors.map((error) => error.message));
return {
file: script,
moduleOnlyErrors: file.errors
.map((error) => error.message)
.filter((message) => !scriptErrors.has(message)),
};
};
/** Parse JavaScript or TypeScript once without attaching comments to AST nodes. */
export const parseJavaScriptSource = (
source: string,
@@ -52,6 +52,7 @@ import {
} from "./javascriptSourceParser.js";
import { createJavaScriptRpcScan } from "./javascriptRpcEndpoints.js";
import { semanticImportEqualsSpecifier } from "./javascriptSemanticProjection.js";
/** Parse one JavaScript artifact and recover static structure only. */
export const analyzeJavaScriptStaticSource = (
@@ -232,13 +233,18 @@ const inspectNode = (
inspectElectronStaticNode(node, findings);
if (t.isCallExpression(node)) {
inspectBundlerBootstrap(source, node, accumulator, bindings);
inspectBundlerRegistration(source, node, accumulator);
inspectEsbuildWrapper(source, node, accumulator);
inspectCall(source, node, findings);
inspectBundlerRegistration(source, node, accumulator, bindings);
inspectEsbuildWrapper(source, node, accumulator, bindings);
inspectCall(source, node, findings, bindings);
} else if (t.isOptionalCallExpression(node)) {
inspectCall(source, node, findings);
} else if (t.isNewExpression(node)) inspectCall(source, node, findings);
if (
inspectCall(source, node, findings, bindings);
} else if (t.isNewExpression(node))
inspectCall(source, node, findings, bindings);
if (t.isTSImportEqualsDeclaration(node)) {
const specifier = semanticImportEqualsSpecifier(node);
if (specifier !== null)
addReference(findings, { node, kind: "require", specifier });
} else if (
(t.isImportDeclaration(node) || t.isExportAllDeclaration(node)) &&
node.source !== undefined
)
@@ -37,6 +37,7 @@ export const inspectBundlerRegistration = (
source: string,
call: t.CallExpression,
accumulator: AnalysisAccumulator,
bindings: JavaScriptSemanticAnalysisState,
): void => {
const runtime = chunkRuntime(call);
const entry = call.arguments[0];
@@ -45,7 +46,10 @@ export const inspectBundlerRegistration = (
const table = entry.elements[1];
const runtimeValue = runtimeMetadata(entry.elements[2]);
if (!t.isArrayExpression(chunkIds) || !t.isObjectExpression(table)) return;
const recovered = recoverBundlerModules(source, table, runtime, accumulator);
const recovered = recoverBundlerModules(source, table, accumulator, {
runtime,
bindings,
});
const chunkKeys = staticArrayValues(chunkIds);
accumulator.unknownFindings += chunkKeys.unknown;
accumulator.unknownFindings +=
@@ -98,8 +102,8 @@ export const inspectBundlerBootstrap = (
const recovered = recoverBundlerModules(
source,
bootstrap.table,
runtime,
accumulator,
{ runtime, bindings },
);
const entries: string[] = [];
let unknownEntries = 0;
@@ -148,6 +152,7 @@ export const inspectEsbuildWrapper = (
source: string,
call: t.CallExpression,
accumulator: AnalysisAccumulator,
bindings: JavaScriptSemanticAnalysisState,
): void => {
const name = calleeName(call.callee);
const wrapperKind =
@@ -159,7 +164,10 @@ export const inspectEsbuildWrapper = (
const table = call.arguments[0];
if (wrapperKind === null || !t.isObjectExpression(table)) return;
const runtime = `esbuild-${wrapperKind}`;
const recovered = recoverBundlerModules(source, table, runtime, accumulator);
const recovered = recoverBundlerModules(source, table, accumulator, {
runtime,
bindings,
});
if (recovered.modules.length === 0) return;
accumulator.unknownFindings += recovered.unknownAsyncChunkKeys;
const registration: JavaScriptBundlerRegistration = {
@@ -191,11 +199,16 @@ interface RecoveredBundlerModules {
readonly unknownAsyncChunkKeys: number;
}
interface BundlerRecoveryContext {
readonly runtime: string;
readonly bindings: JavaScriptSemanticAnalysisState;
}
const recoverBundlerModules = (
source: string,
table: t.ObjectExpression,
runtime: string,
accumulator: AnalysisAccumulator,
context: BundlerRecoveryContext,
): RecoveredBundlerModules => {
const modules: JavaScriptBundlerModule[] = [];
const asyncChunkKeys: string[] = [];
@@ -204,8 +217,8 @@ const recoverBundlerModules = (
const recovered = recoverBundlerModule(
source,
property,
runtime,
accumulator,
context,
);
if (recovered === null) continue;
modules.push(recovered.module);
@@ -222,20 +235,21 @@ const recoverBundlerModules = (
const recoverBundlerModule = (
source: string,
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
runtime: string,
accumulator: AnalysisAccumulator,
context: BundlerRecoveryContext,
): {
readonly module: JavaScriptBundlerModule;
readonly asyncChunkKeys: readonly string[];
readonly unknownAsyncChunkKeys: number;
} | null => {
const { runtime, bindings } = context;
const factory = moduleFactory(property);
if (factory === undefined) return null;
const key = modulePropertyName(property);
if (key.startsWith("[computed@") || key.startsWith("[unknown@"))
accumulator.unknownFindings += 1;
const fingerprint = fingerprintJavaScriptAst(factory);
const exportsValue = collectJavaScriptExports(factory);
const exportsValue = collectJavaScriptExports(factory, bindings);
const requireName = factoryRequireName(factory);
const asyncChunks = collectBundlerAsyncChunkKeys(factory, requireName);
if (typeof factory.start === "number" && typeof factory.end === "number") {
@@ -1,5 +1,6 @@
import * as t from "@babel/types";
import { htmlUrlText, stripQueryAndFragment } from "../artifactPathSyntax.js";
import { sanitizeEndpointCandidate } from "../browserObservation.js";
import {
addFindingOnce,
@@ -7,6 +8,7 @@ import {
} from "./javascriptStaticAnalysisFindings.js";
import {
STATIC_ROUTE_CALL_NAMES,
argumentNode,
argumentValue,
calleeName,
endpointArgument as endpointArgumentHelper,
@@ -19,13 +21,24 @@ import {
storageKind,
stringValue,
} from "./javascriptStaticAnalysisHelpers.js";
import { semanticStaticPropertyName } from "./javascriptAstValues.js";
import {
semanticStaticPropertyName,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import type {
JavaScriptAnalysisAccumulator as AnalysisAccumulator,
JavaScriptEndpointInput as EndpointInput,
JavaScriptFindingContext as FindingContext,
JavaScriptReferenceInput as ReferenceInput,
} from "./javascriptStaticAnalysisState.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import {
isUnmodifiedGlobalReference,
isUnmodifiedImportMetaUrl,
} from "./javascriptSemanticAmbientWrites.js";
type JavaScriptCallLike =
| t.CallExpression
@@ -37,6 +50,7 @@ export const inspectCall = (
source: string,
node: JavaScriptCallLike,
context: FindingContext,
bindings: JavaScriptSemanticAnalysisState,
): void => {
const { accumulator } = context;
const name = calleeName(node.callee);
@@ -59,8 +73,27 @@ export const inspectCall = (
});
for (const specifier of vitePreloadDependencySpecifiers(source, node, name))
addReference(context, { node, kind: "dynamic-import", specifier });
if (name === "Worker" || name.endsWith(".Worker"))
addReference(context, { node, kind: "worker", specifier: first });
const worker = t.isNewExpression(node) ? node : undefined;
const workerConstructor =
worker === undefined
? undefined
: workerConstructorKind(worker.callee, bindings);
if (
workerConstructor !== undefined ||
name === "Worker" ||
name.endsWith(".Worker")
)
addReference(context, {
node,
kind: "worker",
// Node string paths use the process cwd or filesystem root, neither of
// which is established by the analyzed source's artifact location.
specifier:
(workerConstructor === "node" ? undefined : first) ??
(workerConstructor === undefined || worker === undefined
? undefined
: workerUrlSpecifier(worker, bindings)),
});
if (name.endsWith("serviceWorker.register"))
addReference(context, { node, kind: "service-worker", specifier: first });
inspectEndpointCall(node, name, first, context);
@@ -97,6 +130,69 @@ export const inspectCall = (
});
};
const workerUrlSpecifier = (
worker: t.NewExpression,
bindings: JavaScriptSemanticAnalysisState,
): string | undefined => {
const argumentExpression = argumentNode(worker.arguments[0]);
if (argumentExpression === undefined) return undefined;
const node = unwrapJavaScriptExpression(argumentExpression).node;
if (!t.isNewExpression(node)) return undefined;
const callee = unwrapJavaScriptExpression(node.callee).node;
if (
!isUnmodifiedGlobalReference(callee, bindings, "URL") ||
!isUnmodifiedImportMetaUrl(argumentNode(node.arguments[1]), bindings)
)
return undefined;
const specifier = stringValue(node.arguments[0]);
if (specifier === undefined) return undefined;
const pathname = stripQueryAndFragment(specifier);
// The module URL's scheme and filesystem/origin root are unavailable. Only
// relative pathnames can establish a location within the artifact; retain
// rooted paths and paths requiring URL text normalization as expressions.
// Malformed percent escapes survive HTTP URL parsing but cannot be converted
// from a file URL to a Node Worker path. Without the base scheme, keep that
// ambiguity unknown; query and fragment bytes do not affect pathname lookup.
return pathname.length > 0 &&
!pathname.startsWith("/") &&
!/%(?![0-9a-f]{2})/iu.test(pathname) &&
stripQueryAndFragment(htmlUrlText(specifier)) === pathname
? specifier
: undefined;
};
const workerConstructorKind = (
callee: t.Node,
bindings: JavaScriptSemanticAnalysisState,
): "browser" | "node" | undefined => {
const node = unwrapJavaScriptExpression(callee).node;
const member =
t.isMemberExpression(node) &&
semanticStaticPropertyName(node.property, node.computed) === "Worker";
const root = unwrapJavaScriptExpression(member ? node.object : node).node;
if (!t.isIdentifier(root)) return undefined;
const browserGlobal = member
? ["globalThis", "window", "self"].includes(root.name)
: root.name === "Worker";
if (browserGlobal && isUnmodifiedGlobalReference(node, bindings, "Worker"))
return "browser";
const binding = resolveSemanticBindingState(bindings, root, root.name);
const [origin] = binding?.directOrigins ?? [];
// Named ESM exports and module namespace exports are read-only. Default
// imports and CommonJS objects can replace Worker, so their identity is unknown.
return binding?.runtimeImport === true &&
binding.definitions.length === 1 &&
binding.directOrigins.length === 1 &&
origin !== undefined &&
(origin.specifier === "worker_threads" ||
origin.specifier === "node:worker_threads") &&
(member
? origin.importedPath.length === 0
: origin.importedPath.length === 1 && origin.importedPath[0] === "Worker")
? "node"
: undefined;
};
// Element factories such as jsx("audio", props) and createElement("video",
// props) carry the HTML media `preload` hint ("none", "metadata", "auto"),
// which never names an Electron preload script.
@@ -342,16 +342,23 @@ const isDirectoryIdentity = (node: t.Node | undefined): boolean => {
);
};
const isFileIdentity = (node: t.Node | undefined): boolean => {
if (t.isIdentifier(node, { name: "__filename" })) return true;
/** Whether the expression denotes the current module's URL. */
export const isImportMetaUrl = (node: t.Node | undefined): boolean => {
if (node === undefined) return false;
if (
t.isMemberExpression(node) &&
t.isMetaProperty(node.object) &&
node.object.meta.name === "import" &&
node.object.property.name === "meta" &&
semanticStaticPropertyName(node.property, node.computed) === "url"
)
const expression = unwrapJavaScriptExpression(node).node;
if (!t.isMemberExpression(expression)) return false;
const object = unwrapJavaScriptExpression(expression.object).node;
return (
t.isMetaProperty(object) &&
object.meta.name === "import" &&
object.property.name === "meta" &&
semanticStaticPropertyName(expression.property, expression.computed) ===
"url"
);
};
const isFileIdentity = (node: t.Node | undefined): boolean => {
if (t.isIdentifier(node, { name: "__filename" }) || isImportMetaUrl(node))
return true;
if (!t.isCallExpression(node)) return false;
const name = calleeName(node.callee);
@@ -50,6 +50,18 @@ it("does not infer a bootstrap from a function table without a matching loader",
expect(analysis.bundler_registrations).toEqual([]);
});
it("does not treat a same-named shadow as the factory exports parameter", () => {
const analysis =
analyzeJavaScriptStaticSource(`globalThis.webpackChunkApp.push([[1], {
first(module, e, require) {
{ const e = {}; require.d(e, { shadowed: () => 1 }); e.other = 2; }
}
}]);`);
expect(analysis.bundler_registrations[0]?.modules).toMatchObject([
{ module_key: "first", exports: [] },
]);
});
it("does not confuse a shadowed dispatch table with the outer module table", () => {
const analysis = analyzeJavaScriptStaticSource(`(() => {
const modules = { 17(module) { module.exports = require("electron"); } };
@@ -3,7 +3,10 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import type { ParsedInventorySet } from "./artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
type ParsedInventorySet,
} from "./artifactInventoryEvidence.js";
import { evidenceSchema } from "./evidence.js";
import { digestSchema } from "./digests.js";
import { prefixedDigestSchema } from "./digests.js";
@@ -49,10 +52,11 @@ export const projectionCoverage = (
budgetComplete: boolean,
): {
status: "complete-within-inventory" | "partial";
/** True when all manifest graph-member counts are present, independent of source coverage. */
inventory_complete: boolean;
} => ({
status:
inventory.complete && budgetComplete
hasCompleteInventoryCoverage(inventory) && budgetComplete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
+5 -9
View File
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
import { z } from "zod";
import { decodeCanonicalBase64 } from "../webScreenshot.js";
import { readPngHeaderDimensions } from "../pngHeader.js";
const scope = {
pid: z.number().int().positive(),
@@ -95,11 +96,8 @@ const nativeUiScreenshotSchema = z
code: "custom",
message: "PNG screenshot digest mismatch",
});
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
) {
const dimensions = readPngHeaderDimensions(bytes);
if (dimensions === undefined) {
context.addIssue({
code: "custom",
message: "Screenshot bytes are not a PNG image",
@@ -107,8 +105,8 @@ const nativeUiScreenshotSchema = z
return;
}
if (
bytes.readUInt32BE(16) !== screenshot.width ||
bytes.readUInt32BE(20) !== screenshot.height
dimensions.width !== screenshot.width ||
dimensions.height !== screenshot.height
)
context.addIssue({
code: "custom",
@@ -116,8 +114,6 @@ const nativeUiScreenshotSchema = z
});
});
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
export const nativeUiSnapshotSchema = z.strictObject({
window: z.strictObject({
pid: z.number().int().positive(),
+11
View File
@@ -358,3 +358,14 @@ export type InspectRecordedCrashInput = z.output<
typeof inspectRecordedCrashInputSchema
>;
export type RecordedCrash = z.output<typeof recordedCrashSchema>;
/** Validated basic core evidence retained when requested debugger enrichment fails. */
export type RecordedCrashPartialObservation = Omit<
RecordedCrash,
"debugger"
> & {
readonly debugger: {
readonly status: "unavailable";
readonly requested: true;
};
};
+2 -2
View File
@@ -1,6 +1,6 @@
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
import type { HeaderArchitecture } from "./binaryTargetTypes.js";
export type PeArchitecture = Exclude<BinaryArchitecture, "mips">;
export type PeArchitecture = HeaderArchitecture;
/** A decoded COFF machine and whether it carried a ReadyToRun OS override. */
export interface PeMachine {
+35
View File
@@ -0,0 +1,35 @@
import { expect, it } from "vitest";
import { readPngHeaderDimensions } from "./pngHeader.js";
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
it("reads encoded dimensions without changing screenshot bytes", () => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(257, 16);
bytes.writeUInt32BE(129, 20);
const original = Buffer.from(bytes);
expect(readPngHeaderDimensions(bytes)).toEqual({ width: 257, height: 129 });
expect(bytes.equals(original)).toBe(true);
});
it.each([12, 13, 14, 15])("rejects ASCII-folded IHDR byte at %s", (offset) => {
const bytes = Buffer.from(png);
bytes[offset] = (bytes[offset] ?? 0) | 0x80;
expect(bytes.subarray(12, 16).toString("ascii")).toBe("IHDR");
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
expect(readPngHeaderDimensions(png.subarray(0, 23))).toBeUndefined();
const badSignature = Buffer.from(png);
badSignature[0] = 0;
expect(readPngHeaderDimensions(badSignature)).toBeUndefined();
for (const offset of [16, 20]) {
const zero = Buffer.from(png);
zero.writeUInt32BE(0, offset);
expect(readPngHeaderDimensions(zero)).toBeUndefined();
}
});
+17
View File
@@ -0,0 +1,17 @@
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const IHDR_TYPE = Buffer.from("IHDR");
/** Read screenshot dimensions from a byte-faithful PNG header, not a full image decode. */
export const readPngHeaderDimensions = (
bytes: Buffer,
): { readonly width: number; readonly height: number } | undefined => {
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
)
return undefined;
const width = bytes.readUInt32BE(16);
const height = bytes.readUInt32BE(20);
return width === 0 || height === 0 ? undefined : { width, height };
};
+113
View File
@@ -98,6 +98,119 @@ it("preserves OpenStep dictionary and array autodetection", () => {
});
});
/** The single-member chain of a nested dictionary, down to its deepest value. */
const deepestValue = (value: unknown): unknown => {
let cursor = value;
while (
cursor !== null &&
typeof cursor === "object" &&
!Array.isArray(cursor) &&
"k" in cursor
) {
cursor = (cursor as Record<string, unknown>).k;
}
return cursor;
};
/** The single-member chain of a nested array, down to its deepest value. */
const deepestEntry = (value: unknown): unknown => {
let cursor = value;
while (Array.isArray(cursor) && cursor.length === 1) cursor = cursor[0];
return cursor;
};
const nestedDictionaries = (depth: number) =>
plist(
"<dict><key>k</key>".repeat(depth) +
"<string>x</string>" +
"</dict>".repeat(depth),
);
const nestedArrays = (depth: number) =>
plist(
"<array>".repeat(depth) + "<string>x</string>" + "</array>".repeat(depth),
);
it("rejects XML nesting beyond the projection limit with the limit diagnostic", () => {
// `plist` and the prototype-key traversal recurse once per level, so the
// depth check must report the same bounded-resource error as the projection
// instead of letting those recursive passes exhaust the call stack.
const limit = new RangeError("Plist exceeds 128 nesting levels");
expect(() => parseXmlPropertyList(nestedDictionaries(129))).toThrow(limit);
expect(() => parseXmlPropertyList(nestedArrays(129))).toThrow(limit);
expect(() => parseXmlPropertyList(nestedDictionaries(3000))).toThrow(limit);
expect(() => parseXmlPropertyList(nestedArrays(4000))).toThrow(limit);
});
it("decodes XML property lists exactly at the projection nesting limit", () => {
expect(
deepestValue(parseXmlPropertyList(nestedDictionaries(128)).value),
).toBe("x");
expect(deepestEntry(parseXmlPropertyList(nestedArrays(128)).value)).toBe("x");
expect(
parseXmlPropertyList(
plist("<array>".repeat(128) + "<array/>" + "</array>".repeat(128)),
).value,
).toBeDefined();
});
it("does not count markup inside comments, CDATA, or the doctype as nesting", () => {
const text = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd" [<!ENTITY deep "<dict/>">]>
<plist version="1.0"><dict>
<key>a</key><string><![CDATA[<dict><array><dict>]]></string>
<!-- <dict><key>k</key> -->
<key>b</key><array><!-- <array> --><string>x</string></array>
</dict></plist>`;
expect(parseXmlPropertyList(text)).toEqual({
value: { a: "<dict><array><dict>", b: ["x"] },
omittedPrototypeKeys: 0,
});
});
it.each(['"', "'"])(
"counts containers with quoted XML delimiters using %s attributes",
(quote) => {
const opening = `<dict note=${quote}/>${quote}><key>k</key>`;
const text = plist(
opening.repeat(3000) + "<string>x</string>" + "</dict>".repeat(3000),
);
expect(() => parseXmlPropertyList(text)).toThrow(
new RangeError("Plist exceeds 128 nesting levels"),
);
expect(
parseXmlPropertyList(
plist(
"<array>" + `<dict note=${quote}>${quote}/>`.repeat(130) + "</array>",
),
).value,
).toEqual(Array.from({ length: 130 }, () => ({})));
},
);
it("ignores complete DOCTYPE internal subsets when checking value depth", () => {
const text = `<!DOCTYPE plist [
<!ENTITY first "unused">
<!-- <dict><array> -->
<!ENTITY second "${"<dict>".repeat(130)}">
]><plist><string>x</string></plist>`;
expect(parseXmlPropertyList(text)).toEqual({
value: "x",
omittedPrototypeKeys: 0,
});
});
it("bounds nested plist wrappers before recursive decoding", () => {
const text =
"<plist>".repeat(3000) + "<string>x</string>" + "</plist>".repeat(3000);
expect(() => parseXmlPropertyList(text)).toThrow(
new RangeError("Plist exceeds 128 nesting levels"),
);
expect(
parseXmlPropertyList(plist("<plist><string>x</string></plist>")).value,
).toEqual(["x"]);
});
it.each(["\n", "\r\n", "\r", "\u0085", "\u2028", "\u2029"])(
"preserves unrelated source values around %j line endings",
(newline) => {
+60 -7
View File
@@ -1,6 +1,13 @@
import { DOMParser, normalizeLineEndings } from "@xmldom/xmldom";
import {
DOMParser,
normalizeLineEndings,
type Document,
type Node,
} from "@xmldom/xmldom";
import { parse } from "plist";
import { MAX_PLIST_DEPTH } from "./apple/plistValue.js";
/** The dictionary key REA results cannot carry: validation strips it. */
const PROTOTYPE_KEY = "__proto__";
@@ -88,18 +95,64 @@ export const parseXmlPropertyList = (
// by app Info.plist resolution. Only XML needs the key-element substitution.
const first = text.trimStart()[0];
if (first === "{" || first === "(") return omitPrototypeKeys(parse(text));
// Normalize only the literal line endings the pinned decoder normalizes.
// Preserve character references in the source: serializing a DOM would turn
// e.g. an encoded carriage return into a literal newline on the second parse.
const normalized = normalizeLineEndings(text);
// The pinned XML parser is iterative. Reuse its document for the depth
// preflight and key lookup so quoted attributes and declarations have the
// same meaning at both boundaries, before plist's recursive value decode.
const document = new DOMParser().parseFromString(normalized, "text/xml");
assertXmlPlistDepthWithinLimit(document);
const { substituted, placeholder } = substitutePrototypeKeys(
normalizeLineEndings(text),
normalized,
document,
);
return withoutKey(parse(substituted), placeholder);
};
/** Elements whose children the pinned plist value decoder visits recursively. */
const PLIST_CONTAINER_ELEMENTS = new Set(["plist", "dict", "array"]);
/**
* Reject XML plists nested deeper than the projection supports before any
* recursive value pass runs. `plist` and the prototype-key traversal recurse once
* per nesting level, so a deeply nested document exhausts the call stack
* before the projection limit can report the resource bound. The failure
* matches `projectPlistValue` so callers classify it as a limit failure.
*
* Depth counts values the way the projection does: the root value is level 0
* and every container member is one level deeper. A dictionary key names a
* member instead of nesting one, and a self-closing element is the value at
* its own level. The outer plist envelope is unwrapped by the decoder;
* nested plist elements decode as arrays and must count toward the bound.
*/
const assertXmlPlistDepthWithinLimit = (document: Document): void => {
const root = document.documentElement;
if (root === null) return;
const pending: Array<{ node: Node; depth: number }> = [
{ node: root, depth: -1 },
];
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined) break;
const { node, depth } = entry;
// Schedule only the next sibling, keeping traversal storage proportional
// to depth rather than the number of members in a wide container.
if (node.nextSibling !== null)
pending.push({ node: node.nextSibling, depth });
if (node.nodeType !== node.ELEMENT_NODE) continue;
if (node.nodeName !== "key" && depth > MAX_PLIST_DEPTH)
throw new RangeError(
`Plist exceeds ${String(MAX_PLIST_DEPTH)} nesting levels`,
);
if (PLIST_CONTAINER_ELEMENTS.has(node.nodeName) && node.firstChild !== null)
pending.push({ node: node.firstChild, depth: depth + 1 });
}
};
/** Locate keys with the same XML parser and first-child semantics as plist. */
const substitutePrototypeKeys = (text: string) => {
// Normalize only the literal line endings the pinned decoder normalizes.
// Preserve character references in the source: serializing a DOM would turn
// e.g. an encoded carriage return into a literal newline on the second parse.
const document = new DOMParser().parseFromString(text, "text/xml");
const substitutePrototypeKeys = (text: string, document: Document) => {
const keys = Array.from(document.getElementsByTagName("key"));
const decodedKeys = new Set(keys.map((key) => key.firstChild?.nodeValue));
let placeholder = "__rea_prototype_key__";

Some files were not shown because too many files have changed in this diff Show More