fix(artifacts): preserve integrity evidence across workflows and integrate main

This commit is contained in:
morluto
2026-10-08 23:16:16 +08:00
781 changed files with 55034 additions and 14106 deletions
+29
View File
@@ -0,0 +1,29 @@
import { expect, it } from "vitest";
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
it.each(["EACCES", "EPERM"] as const)(
"projects %s as host access denial with correction guidance and a valid public schema",
(systemCode) => {
const error = new AnalysisAccessDeniedError(
"inspect_web_network_capture",
"/selected/capture.har",
systemCode,
{ cause: new Error("internal detail") },
);
const projected = projectAnalysisError(error);
expect(analysisErrorProjectionSchema.parse(projected)).toMatchObject({
code: "access_denied",
category: "unavailable",
retryable: false,
details: {
path: "/selected/capture.har",
system_code: systemCode,
boundary: "filesystem-read",
},
});
expect(projected.remediation.action).toContain("read access");
expect(JSON.stringify(projected)).not.toContain("internal detail");
},
);
+32
View File
@@ -2,10 +2,14 @@
const ANALYSIS_ERROR_TAGS = [
"AnalysisProtocolError",
"AnalysisInputError",
"AnalysisAccessDeniedError",
"AnalysisArtifactChangedError",
"AnalysisOutputError",
"AnalysisCapabilityUnavailableError",
"AnalysisUnsupportedTargetError",
"AnalysisCancelledError",
"AnalysisTimeoutError",
"AnalysisResourceConstraintError",
"ProviderSelectionError",
"ProviderAdapterError",
"BrowserObservationError",
@@ -28,11 +32,39 @@ const ANALYSIS_ERROR_TAGS = [
/** Stable tag for an expected analysis failure. */
export type AnalysisErrorTag = (typeof ANALYSIS_ERROR_TAGS)[number];
/** Retained command output associated with a typed failure; truncation stays explicit. */
export interface AnalysisCapturedOutput {
readonly stdout: string;
readonly stderr: string;
readonly truncated: boolean;
}
/** Optional provider-neutral context that must survive typed error projection. */
export interface AnalysisErrorOptions extends ErrorOptions {
readonly capturedOutput?: AnalysisCapturedOutput;
}
/** Base class for expected analysis, provider, and session failures. */
export abstract class AnalysisError extends Error {
readonly capturedOutput: AnalysisCapturedOutput | undefined;
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
this.capturedOutput =
options?.capturedOutput === undefined
? undefined
: { ...options.capturedOutput };
}
abstract readonly _tag: AnalysisErrorTag;
readonly userMessage: string | undefined = undefined;
readonly userCategory: "cancelled" | undefined = undefined;
readonly cleanupIncomplete: boolean = false;
readonly cleanupResources: readonly string[] = [];
readonly executionFailure: string | undefined = undefined;
readonly partialObservation: PartialProcessCaptureObservation | undefined =
undefined;
readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined;
}
import type {
PartialProcessCaptureObservation,
ProcessCaptureCleanupReport,
} from "./process/processCapture.js";
+71 -6
View File
@@ -1,5 +1,36 @@
import type { JsonValue } from "./jsonValue.js";
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** A readable supplied artifact lies outside this operation's supported target formats. */
export class AnalysisUnsupportedTargetError extends AnalysisError {
readonly _tag = "AnalysisUnsupportedTargetError";
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: AnalysisErrorOptions,
) {
super(`Unsupported target for ${operation} at ${path}: ${reason}`, options);
}
}
/** Provider reported a resource failure, distinct from malformed input or unsupported coverage. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
constructor(
readonly operation: string,
readonly resource: "memory" | "cpu" | "file-size",
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
options?: AnalysisErrorOptions,
) {
super(`Resource constraint during ${operation}: ${reason}`, options);
}
}
/** Provider-neutral invalid analysis input or output at an application boundary. */
export class AnalysisProtocolError extends AnalysisError {
@@ -12,7 +43,7 @@ export class AnalysisInputError extends AnalysisError {
constructor(
readonly operation: string,
options?: ErrorOptions,
options?: AnalysisErrorOptions,
readonly issues: readonly AnalysisInputIssue[] = [],
) {
super(`Invalid analysis input for ${operation}`, options);
@@ -43,7 +74,7 @@ export class AnalysisOutputError extends AnalysisError {
constructor(
readonly operation: string,
readonly reason: string,
options?: ErrorOptions,
options?: AnalysisErrorOptions,
) {
super(`Invalid analysis output for ${operation}: ${reason}`, options);
}
@@ -58,7 +89,7 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError {
readonly providerId: string,
readonly operation: string,
readonly reason: string,
options?: ErrorOptions & { readonly userMessage?: string },
options?: AnalysisErrorOptions & { readonly userMessage?: string },
) {
super(
`Provider ${providerId} cannot execute ${operation}: ${reason}`,
@@ -72,8 +103,11 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError {
export class AnalysisCancelledError extends AnalysisError {
readonly _tag = "AnalysisCancelledError";
constructor(readonly operation: string) {
super(`Analysis operation was cancelled: ${operation}`);
constructor(
readonly operation: string,
options?: AnalysisErrorOptions,
) {
super(`Analysis operation was cancelled: ${operation}`, options);
}
}
@@ -84,9 +118,40 @@ export class AnalysisTimeoutError extends AnalysisError {
constructor(
readonly operation: string,
readonly timeoutMs: number,
options?: AnalysisErrorOptions,
) {
super(
`Analysis operation timed out after ${String(timeoutMs)}ms: ${operation}`,
options,
);
}
}
/** Host filesystem permissions denied the selected read; this is not malformed caller input. */
export class AnalysisAccessDeniedError extends AnalysisError {
readonly _tag = "AnalysisAccessDeniedError";
constructor(
readonly operation: string,
readonly path: string,
readonly systemCode: "EACCES" | "EPERM",
options?: ErrorOptions,
) {
super(
`Host filesystem read access denied (${systemCode}) for ${path} during ${operation}`,
options,
);
}
}
/** Selected artifact acquisition observed a change, so no stable identity can be reported. */
export class AnalysisArtifactChangedError extends AnalysisError {
readonly _tag = "AnalysisArtifactChangedError";
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: ErrorOptions,
) {
super(`Selected artifact changed during acquisition: ${reason}`, options);
}
}
+42 -4
View File
@@ -1,4 +1,10 @@
import { AnalysisInputError } from "./analysisErrorCore.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
AnalysisUnsupportedTargetError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import {
BinaryTargetError,
@@ -28,6 +34,14 @@ import { type AnalysisErrorProjection } from "./analysisErrorProjection.js";
export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
if (error instanceof AnalysisUnsupportedTargetError)
return "Select a target supported by this operation or choose an operation supporting the reported target format.";
if (error instanceof AnalysisResourceConstraintError)
return 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.providerState === "busy"
? "Check binary_session.analysis_activity, wait for the active Hopper request to finish, then retry."
@@ -47,6 +61,10 @@ export const analysisErrorRemediationAction = (
error.constraint === "directory_requires_file"
)
return "For a JavaScript/Electron application directory, call analyze_javascript_application with input_path or run `rea analyze <directory>`. For binary analysis, select its executable file.";
if (error instanceof AnalysisAccessDeniedError)
return "Check the current process's read access to the selected path. Retry with a readable local file.";
if (error instanceof AnalysisArtifactChangedError)
return "Wait until the selected file is stable, then retry this operation.";
if (error instanceof AnalysisInputError)
return "Correct the listed arguments and retry.";
if (error instanceof UnknownRegistryError && error.reason === "not-found")
@@ -107,18 +125,28 @@ const STATIC_ERROR_CATEGORIES: Readonly<
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
> = {
AnalysisInputError: "invalid_input",
AnalysisAccessDeniedError: "unavailable",
AnalysisArtifactChangedError: "integrity_mismatch",
AnalysisCapabilityUnavailableError: "unsupported_provider",
AnalysisUnsupportedTargetError: "unsupported_target",
ProviderSelectionError: "unsupported_provider",
EvidenceIntegrityError: "integrity_mismatch",
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
AnalysisTimeoutError: "timeout",
AnalysisResourceConstraintError: "resource_constraint",
HopperTimeoutError: "timeout",
NoBinaryOpenError: "unavailable",
BinaryTargetError: "unavailable",
};
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof AnalysisUnsupportedTargetError) return error.message;
if (error instanceof AnalysisResourceConstraintError) return error.reason;
if (error instanceof AnalysisAccessDeniedError)
return "Host filesystem permissions denied read access to the selected path.";
if (error instanceof AnalysisArtifactChangedError)
return "The selected artifact changed during acquisition; no stable snapshot was decoded.";
if (error instanceof AnalysisInputError)
return "Analysis input is invalid. Check the arguments and try again.";
const hopperMessage = hopperErrorUserMessage(error);
@@ -138,8 +166,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
: `Evidence ${error.evidenceId} does not match the requested reference (${error.reason}). Check the expected and actual identity in the diagnostic details.`;
if (error instanceof EvidenceIntegrityError)
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
if (error instanceof EvidenceFileError)
return evidenceFileMessage(error.reason);
if (error instanceof EvidenceFileError) return evidenceFileMessage(error);
if (error instanceof UnknownRegistryError && error.reason === "not-found")
return "The requested residual unknown does not exist in this session. Check the unknown_id and try again.";
if (error instanceof UnknownRegistryError)
@@ -243,7 +270,14 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
return "Artifact could not be read or written. Check file access and try again.";
};
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
const evidenceFileMessage = ({
operation,
reason,
}: EvidenceFileError): string => {
if (reason === "missing")
return operation === "read"
? "Evidence file does not exist at the selected path. Check the path and try again."
: "Evidence output directory does not exist. Choose an existing directory and try again.";
if (reason === "not-file")
return "Evidence path does not point to a regular file. Choose a file and try again.";
if (reason === "exists")
@@ -256,10 +290,14 @@ const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
const KNOWN_ERROR_TAGS = {
AnalysisProtocolError: true,
AnalysisInputError: true,
AnalysisAccessDeniedError: true,
AnalysisArtifactChangedError: true,
AnalysisOutputError: true,
AnalysisCapabilityUnavailableError: true,
AnalysisUnsupportedTargetError: true,
AnalysisCancelledError: true,
AnalysisTimeoutError: true,
AnalysisResourceConstraintError: true,
ProviderSelectionError: true,
ProviderAdapterError: true,
BrowserObservationError: true,
+111
View File
@@ -1,8 +1,12 @@
import { describe, expect, it } from "vitest";
import {
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import { BinaryTargetError } from "./configurationErrors.js";
@@ -16,6 +20,113 @@ import {
import { ProviderAdapterError } from "./providerAdapterError.js";
import { UnknownRegistryError } from "./unknownRegistryError.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { ProviderSelectionError } from "./providerSelectionError.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
const retainedOutput = {
stdout: "selected output\u0000",
stderr: "upstream warning",
truncated: true,
};
it("distinguishes unsupported target formats from unavailable provider capabilities", () => {
const projected = projectAnalysisError(
new AnalysisUnsupportedTargetError(
"inspect_evm_interface",
"/selected/runtime.hex",
"EOF-style EF00 container is unsupported.",
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "unsupported_target",
category: "unsupported_target",
retryable: false,
details: {
operation: "inspect_evm_interface",
path: "/selected/runtime.hex",
reason: "EOF-style EF00 container is unsupported.",
captured_output: retainedOutput,
},
});
expect(projected.message).toContain("EF00");
expect(projected.remediation.action).toContain("target format");
expect(projected.remediation.action).not.toContain("doctor");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
["cpu", null],
["cpu", { cpu_seconds: 1 }],
["file-size", null],
["file-size", { file_size_bytes: 1024 }],
] as const)(
"projects reported %s constraints with observed or unknown limits: %j",
(resource, limits) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_binary_layout",
resource,
resource === "memory"
? "Memory allocation failed; exact cause unknown."
: "Observed SIGXCPU; exact signal cause unknown.",
limits,
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "resource_constraint",
category: "resource_constraint",
retryable: false,
details: {
resource,
reported_limits: limits,
captured_output: retainedOutput,
},
});
expect(projected.remediation.action).toContain(
resource === "cpu"
? "CPU"
: resource === "file-size"
? "file-size"
: "memory",
);
expect(projected.remediation.action).not.toContain("doctor");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
new AnalysisInputError("inspect", { capturedOutput: retainedOutput }),
new AnalysisOutputError("inspect", "invalid reply", {
capturedOutput: retainedOutput,
}),
new AnalysisCapabilityUnavailableError(
"provider",
"inspect",
"unsupported profile",
{ capturedOutput: retainedOutput },
),
new AnalysisCancelledError("inspect", { capturedOutput: retainedOutput }),
new AnalysisTimeoutError("inspect", 30, { capturedOutput: retainedOutput }),
new ProviderSelectionError({
operation: "inspect",
reason: "provider_unavailable",
requestedProviderId: "provider",
candidateIds: [],
capturedOutput: retainedOutput,
}),
])(
"retains captured output without changing the typed primary failure: $._tag",
(failure) => {
expect(projectAnalysisError(failure).details?.captured_output).toEqual(
retainedOutput,
);
},
);
describe("analysis error projection: provider failures", () => {
it("projects the primary browser failure alongside incomplete cleanup", () => {
+71 -3
View File
@@ -1,4 +1,4 @@
import type { JsonValue } from "./jsonValue.js";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import {
analysisErrorCategory,
@@ -7,11 +7,15 @@ import {
assertKnownAnalysisErrorTag,
} from "./analysisErrorPresentation.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import { BinaryTargetError } from "./configurationErrors.js";
@@ -37,7 +41,11 @@ export const projectAnalysisError = (
): AnalysisErrorProjection => {
assertKnownAnalysisErrorTag(error._tag);
const code = errorCode(error);
const details = errorDetails(error);
const primaryDetails = errorDetails(error);
const details =
error.capturedOutput === undefined
? primaryDetails
: { ...primaryDetails, captured_output: { ...error.capturedOutput } };
return {
code,
category: analysisErrorCategory(error),
@@ -130,10 +138,14 @@ const STATIC_ERROR_CODES = {
AnalysisOutputError: "unreadable_output",
HopperProtocolError: "unreadable_output",
AnalysisInputError: "invalid_request",
AnalysisAccessDeniedError: "access_denied",
AnalysisArtifactChangedError: "artifact_changed",
AnalysisCapabilityUnavailableError: "capability_unavailable",
AnalysisUnsupportedTargetError: "unsupported_target",
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
AnalysisTimeoutError: "provider_timeout",
AnalysisResourceConstraintError: "resource_constraint",
HopperTimeoutError: "provider_timeout",
HopperProcessError: "provider_unavailable",
HopperStartError: "provider_unavailable",
@@ -177,6 +189,33 @@ const errorDetails = (
const requestErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisUnsupportedTargetError)
return {
operation: error.operation,
path: error.path,
reason: error.reason,
};
if (error instanceof AnalysisResourceConstraintError)
return {
operation: error.operation,
resource: error.resource,
reason: error.reason,
reported_limits: error.reportedLimits,
};
if (error instanceof AnalysisArtifactChangedError)
return {
operation: error.operation,
path: error.path,
reason: error.reason,
boundary: "stable-artifact-read",
};
if (error instanceof AnalysisAccessDeniedError)
return {
operation: error.operation,
path: error.path,
system_code: error.systemCode,
boundary: "filesystem-read",
};
if (error instanceof AnalysisOutputError)
return { operation: error.operation, reason: error.reason };
if (error instanceof AnalysisInputError && error.issues.length > 0)
@@ -220,7 +259,11 @@ const artifactStateErrorDetails = (
};
if (error instanceof UnknownRegistryError) return { reason: error.reason };
if (error instanceof EvidenceFileError)
return { operation: error.operation, reason: error.reason };
return {
operation: error.operation,
reason: error.reason,
...(error.path === undefined ? {} : { path: error.path }),
};
return undefined;
};
@@ -336,12 +379,30 @@ const lifecycleErrorDetails = (
return {
cleanup: "incomplete",
resources: [...error.cleanupResources],
...(error.cleanupReport === undefined
? {}
: { cleanup_report: jsonValueSchema.parse(error.cleanupReport) }),
...(error.executionFailure === undefined
? {}
: { execution_failure: error.executionFailure }),
...(error.partialObservation === undefined
? {}
: {
partial_observation: jsonValueSchema.parse(
error.partialObservation,
),
}),
};
if (
error._tag === "ProcessCaptureError" &&
error.userCategory === "cancelled"
)
return { operation: "process_capture", cleanup: "complete" };
if (
error._tag === "ProcessCaptureError" &&
error.executionFailure !== undefined
)
return { execution_failure: error.executionFailure };
if (error instanceof BinaryTargetError)
return {
path: error.path,
@@ -354,6 +415,7 @@ const lifecycleErrorDetails = (
};
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
"artifact_changed",
"invalid_request",
"provider_timeout",
"cancelled",
@@ -366,10 +428,14 @@ export interface AnalysisErrorProjection extends Readonly<
> {
readonly code:
| "invalid_request"
| "access_denied"
| "artifact_changed"
| "unreadable_output"
| "capability_unavailable"
| "unsupported_target"
| "provider_unavailable"
| "provider_timeout"
| "resource_constraint"
| "cancelled"
| "artifact_integrity_mismatch"
| "artifact_operation_failed"
@@ -384,10 +450,12 @@ export interface AnalysisErrorProjection extends Readonly<
readonly category:
| "invalid_input"
| "unsupported_provider"
| "unsupported_target"
| "integrity_mismatch"
| "truncated"
| "cancelled"
| "timeout"
| "resource_constraint"
| "unavailable"
| "execution_failure";
readonly message: string;
+51 -26
View File
@@ -17,6 +17,55 @@ import {
import { createEvidence } from "./evidence.js";
import { createEvidenceBundle } from "./evidenceBundle.js";
const snapshotWithHistoricalEvidence = () => {
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const parameters = { procedure: "main" };
const makeEvidence = (result: string) =>
createEvidence(ANALYSIS_SNAPSHOT_TARGET, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "analyze_function",
parameters,
result: { summary: result },
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
});
const current = makeEvidence("cached");
const entry = {
query_id: analysisQueryId(target, binding, "analyze_function", parameters),
operation: "analyze_function",
parameters,
execution: {
result: { summary: "cached" },
raw_result: null,
provider: binding.provider,
limitations: [],
locations: [],
subject: {
path: ANALYSIS_SNAPSHOT_TARGET.path,
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
format: ANALYSIS_SNAPSHOT_TARGET.format,
architecture: ANALYSIS_SNAPSHOT_TARGET.architecture ?? null,
},
},
};
return {
current,
snapshot: {
target,
binding,
entries: [entry],
evidence_bundle: createEvidenceBundle([
makeEvidence("older"),
current,
createEvidence(ANALYSIS_SNAPSHOT_TARGET, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "legacy_query",
parameters: {},
result: { summary: "legacy" },
}),
]),
} satisfies AnalysisSnapshot,
};
};
describe("analysis snapshot contract", () => {
it("preserves DOS MZ target and subject formats with the x86 family", () => {
const target = {
@@ -91,31 +140,7 @@ describe("analysis snapshot contract", () => {
describe("analysis snapshot Evidence binding", () => {
it("finds only Evidence committed to the exact binding and profile", () => {
const evidence = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
ANALYSIS_SNAPSHOT_PROVIDER,
{
operation: "analyze_function",
parameters: { procedure: "main" },
result: { summary: "cached" },
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
},
);
const legacy = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
ANALYSIS_SNAPSHOT_PROVIDER,
{
operation: "legacy_query",
parameters: {},
result: { summary: "legacy" },
},
);
const snapshot: AnalysisSnapshot = {
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
entries: [],
evidence_bundle: createEvidenceBundle([evidence, legacy]),
};
const { current, snapshot } = snapshotWithHistoricalEvidence();
expect(
snapshotEvidenceForQuery(snapshot, {
target: ANALYSIS_SNAPSHOT_TARGET,
@@ -125,7 +150,7 @@ describe("analysis snapshot Evidence binding", () => {
provider: ANALYSIS_SNAPSHOT_PROVIDER,
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
}),
).toEqual(evidence);
).toEqual(current);
expect(
snapshotEvidenceForQuery(snapshot, {
target: ANALYSIS_SNAPSHOT_TARGET,
+250 -2
View File
@@ -101,17 +101,33 @@ const entrySchema = z.object({
subject: subjectSchema.nullable(),
}),
});
const workflowEntrySchema = z.object({
query_id: prefixedDigestSchema("query"),
operation: z.string().min(1),
parameters: jsonObjectSchema,
execution: z.object({
result: jsonValueSchema,
raw_result: jsonValueSchema.nullable(),
provider: committedProviderSchema,
analysis_profile: analysisProfileSchema,
limitations: z.array(z.string()),
locations: z.array(evidenceLocationSchema),
subject: subjectSchema.nullable(),
}),
});
/** Provider- and profile-exact cache of successful immutable analysis calls. */
export const analysisSnapshotSchema = z.object({
target: targetSchema,
binding: bindingSchema,
entries: z.array(entrySchema),
workflow_entries: z.array(workflowEntrySchema).optional(),
evidence_bundle: evidenceBundleSchema,
});
export type AnalysisSnapshot = z.infer<typeof analysisSnapshotSchema>;
export type AnalysisSnapshotEntry = z.infer<typeof entrySchema>;
export type AnalysisSnapshotWorkflowEntry = z.infer<typeof workflowEntrySchema>;
export type AnalysisSnapshotTarget = z.infer<typeof targetSchema>;
export type AnalysisSnapshotBinding = z.infer<typeof bindingSchema>;
@@ -208,6 +224,19 @@ export const snapshotEvidenceForQuery = (
if (!snapshotMatchesBinding(snapshot, target, bindingProfile))
return undefined;
const encodedParameters = canonicalJson(parameters);
const queryId = analysisQueryId(
snapshot.target,
snapshot.binding,
operation,
parameters,
);
const entry = snapshot.entries.find(
(candidate) => candidate.query_id === queryId,
);
const workflowEntry = snapshot.workflow_entries?.find(
(candidate) => candidate.query_id === queryId,
);
if (entry === undefined && workflowEntry === undefined) return undefined;
return snapshot.evidence_bundle.records.find(
(record) =>
record.subject?.digest.sha256 === target.sha256 &&
@@ -217,10 +246,77 @@ export const snapshotEvidenceForQuery = (
record.provider.version === provider.version &&
"analysis_profile" in record &&
analysisProfilesEqual(record.analysis_profile, evidenceProfile) &&
canonicalJson(record.parameters) === encodedParameters,
canonicalJson(record.parameters) === encodedParameters &&
((entry !== undefined && evidenceMatchesEntry(record, entry, snapshot)) ||
(workflowEntry !== undefined &&
evidenceMatchesWorkflowEntry(record, workflowEntry, snapshot))),
);
};
/** Create one exact replay record for a derived application workflow result. */
export const createAnalysisSnapshotWorkflowEntry = (input: {
readonly target: AnalysisSnapshotTarget;
readonly binding: AnalysisSnapshotBinding;
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly execution: SnapshotExecution & {
readonly analysisProfile: AnalysisProfileCommitment;
};
}): AnalysisSnapshotWorkflowEntry => {
const { target, binding, operation, parameters, execution } = input;
if (
execution.provider.id !== execution.analysisProfile.provider.id ||
execution.provider.name !== execution.analysisProfile.provider.name ||
execution.provider.version !== execution.analysisProfile.provider.version
)
throw new TypeError(
"Workflow snapshot execution provider does not match its profile",
);
return {
query_id: analysisQueryId(target, binding, operation, parameters),
operation,
parameters: jsonObjectSchema.parse(parameters),
execution: {
result: execution.result,
raw_result: execution.rawResult,
provider: execution.analysisProfile.provider,
analysis_profile: execution.analysisProfile,
limitations: [...execution.limitations],
locations: [...execution.locations],
subject:
execution.subject === null
? null
: {
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
},
};
};
const evidenceMatchesEntry = (
evidence: Evidence,
entry: AnalysisSnapshotEntry,
snapshot: Pick<AnalysisSnapshot, "target" | "binding">,
): boolean =>
isCorrespondingEvidence(evidence, snapshot) &&
canonicalJson({
query: evidenceQueryKey(evidence),
normalized_result: evidence.normalized_result,
raw_result: evidence.raw_result,
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
local_path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
}) === entryEvidenceKey(entry, snapshot.binding);
/** Compute the stable lookup key for one provider/profile-specific query. */
export const analysisQueryId = (
target: AnalysisSnapshotTarget,
@@ -286,7 +382,9 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
);
const ids = new Set<string>();
const boundEntries: AnalysisSnapshotEntry[] = [];
const boundWorkflowEntries: AnalysisSnapshotWorkflowEntry[] = [];
const index = createEvidenceIndex(parsed);
const workflowIndex = createWorkflowEvidenceIndex(parsed);
for (const entry of parsed.entries) {
if (
entry.execution.provider.id !== parsed.binding.provider.id ||
@@ -316,12 +414,60 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
}
boundEntries.push(entry);
}
for (const entry of parsed.workflow_entries ?? []) {
if (
entry.execution.provider.id !==
entry.execution.analysis_profile.provider.id ||
entry.execution.provider.name !==
entry.execution.analysis_profile.provider.name ||
entry.execution.provider.version !==
entry.execution.analysis_profile.provider.version
)
throw new TypeError(
"Analysis snapshot workflow entry provider does not match its profile",
);
const expected = analysisQueryId(
parsed.target,
parsed.binding,
entry.operation,
entry.parameters,
);
if (entry.query_id !== expected)
throw new TypeError(
"Analysis snapshot workflow query identifier does not match",
);
if (ids.has(entry.query_id))
throw new TypeError("Analysis snapshot contains duplicate queries");
ids.add(entry.query_id);
if (!workflowEntryHasMatchingEvidence(entry, workflowIndex)) {
if (workflowEntryHasCorrespondingEvidence(entry, workflowIndex))
throw new TypeError(
`Analysis snapshot workflow entry ${entry.operation} differs from its Evidence record`,
);
continue;
}
boundWorkflowEntries.push(entry);
}
const sorted = [...parsed.entries].sort((left, right) =>
left.query_id.localeCompare(right.query_id),
);
if (JSON.stringify(parsed.entries) !== JSON.stringify(sorted))
throw new TypeError("Analysis snapshot entries are not canonical");
return { ...parsed, entries: boundEntries };
const sortedWorkflows = [...(parsed.workflow_entries ?? [])].sort(
(left, right) => left.query_id.localeCompare(right.query_id),
);
if (
parsed.workflow_entries !== undefined &&
JSON.stringify(parsed.workflow_entries) !== JSON.stringify(sortedWorkflows)
)
throw new TypeError("Analysis snapshot workflow entries are not canonical");
return {
...parsed,
entries: boundEntries,
...(parsed.workflow_entries === undefined
? {}
: { workflow_entries: boundWorkflowEntries }),
};
};
/** Check that a cached provider execution is represented by bundled Evidence. */
@@ -429,6 +575,108 @@ const entryEvidenceKey = (
},
});
const workflowEntryQueryKey = (entry: AnalysisSnapshotWorkflowEntry): string =>
canonicalJson({
operation: entry.operation,
parameters: entry.parameters,
provider: entry.execution.provider,
analysis_profile: entry.execution.analysis_profile,
});
const workflowEntryEvidenceKey = (
entry: AnalysisSnapshotWorkflowEntry,
): string =>
canonicalJson({
query: workflowEntryQueryKey(entry),
normalized_result: entry.execution.result,
raw_result: entry.execution.raw_result,
limitations: entry.execution.limitations,
locations: entry.execution.locations,
subject:
entry.execution.subject === null
? null
: {
local_path: entry.execution.subject.path,
sha256: entry.execution.subject.sha256,
format: entry.execution.subject.format,
architecture: entry.execution.subject.architecture,
},
});
const isWorkflowEvidence = (
evidence: Evidence,
snapshot: Pick<AnalysisSnapshot, "target">,
entry: AnalysisSnapshotWorkflowEntry,
): boolean =>
evidence.predicate_type === "rea.analysis" &&
evidence.confidence === "derived" &&
evidence.authority === "shipped-artifact" &&
evidence.subject?.digest.sha256 === snapshot.target.sha256 &&
"analysis_profile" in evidence &&
analysisProfilesEqual(
evidence.analysis_profile,
entry.execution.analysis_profile,
) &&
evidence.provider.id === entry.execution.provider.id &&
evidence.provider.name === entry.execution.provider.name &&
evidence.provider.version === entry.execution.provider.version;
const createWorkflowEvidenceIndex = (
snapshot: Pick<AnalysisSnapshot, "target" | "evidence_bundle">,
): EvidenceIndex => {
const matching = new Set<string>();
const corresponding = new Set<string>();
for (const evidence of snapshot.evidence_bundle.records) {
if (
evidence.predicate_type !== "rea.analysis" ||
evidence.confidence !== "derived" ||
evidence.authority !== "shipped-artifact" ||
evidence.subject?.digest.sha256 !== snapshot.target.sha256 ||
!("analysis_profile" in evidence)
)
continue;
corresponding.add(evidenceQueryKey(evidence));
matching.add(canonicalJson(evidenceContentProjection(evidence)));
}
return { matching, corresponding };
};
const workflowEntryHasMatchingEvidence = (
entry: AnalysisSnapshotWorkflowEntry,
index: EvidenceIndex,
): boolean => index.matching.has(workflowEntryEvidenceKey(entry));
const workflowEntryHasCorrespondingEvidence = (
entry: AnalysisSnapshotWorkflowEntry,
index: EvidenceIndex,
): boolean => index.corresponding.has(workflowEntryQueryKey(entry));
const evidenceMatchesWorkflowEntry = (
evidence: Evidence,
entry: AnalysisSnapshotWorkflowEntry,
snapshot: Pick<AnalysisSnapshot, "target">,
): boolean =>
isWorkflowEvidence(evidence, snapshot, entry) &&
canonicalJson(evidenceContentProjection(evidence)) ===
workflowEntryEvidenceKey(entry);
const evidenceContentProjection = (evidence: Evidence) => ({
query: evidenceQueryKey(evidence),
normalized_result: evidence.normalized_result,
raw_result: evidence.raw_result,
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
local_path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
});
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
+9 -2
View File
@@ -118,6 +118,7 @@ export const projectAndroidApplication = (
? ["Source inventory pages are incomplete; 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.",
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
];
const withoutId = {
@@ -176,11 +177,17 @@ const runtimeFamilies = (all: readonly Component[]) => {
const families = new Set<
AndroidApplicationProjectionResult["runtime_families"][number]
>();
if (all.some(({ path, format }) => format === "dex" || path.endsWith(".dex")))
if (
all.some(
({ path, format }) =>
format === "dex" || path.toLowerCase().endsWith(".dex"),
)
)
families.add("dalvik-art");
if (
all.some(
({ path, format }) => format === "jvm-class" || path.endsWith(".class"),
({ path, format }) =>
format === "jvm-class" || path.toLowerCase().endsWith(".class"),
)
)
families.add("java-kotlin");
+110
View File
@@ -0,0 +1,110 @@
import type {
DylibTreeEntry,
DylibTreeView,
MachoSlice,
} from "./dylibResolution.js";
const MAX_SYMLINK_HOPS = 32;
export type PathLookup =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "absent" | "escapes" | "not-file" };
/**
* Resolve a root-relative path one segment at a time, as `open` would:
* symlinks are followed inside the root, `..` applies to the real parent,
* and any escape above the root or through an absolute link stops.
*/
export const resolveTreePath = async (
view: DylibTreeView,
input: string,
): Promise<PathLookup> => {
const pending = segmentsOf(input);
const resolved: string[] = [];
let last: DylibTreeEntry | undefined;
let hops = 0;
while (pending.length > 0) {
const segment = pending.shift() ?? "";
if (segment === "..") {
if (resolved.length === 0) return { kind: "escapes" };
resolved.pop();
last = { kind: "directory" };
continue;
}
const path = [...resolved, segment].join("/");
const entry = await view.entry(path);
if (entry === undefined) return { kind: "absent" };
if (entry.kind === "symlink") {
hops += 1;
if (hops > MAX_SYMLINK_HOPS) return { kind: "absent" };
if (entry.target.startsWith("/")) return { kind: "escapes" };
pending.unshift(...segmentsOf(entry.target));
continue;
}
if (entry.kind === "file" && pending.length > 0) return { kind: "absent" };
resolved.push(segment);
last = entry;
}
return last?.kind === "file"
? { kind: "file", path: resolved.join("/") }
: { kind: "not-file" };
};
const segmentsOf = (path: string): string[] =>
path.split("/").filter((segment) => segment !== "" && segment !== ".");
export const directoryOf = (path: string): string => {
const index = path.lastIndexOf("/");
return index < 0 ? "" : path.slice(0, index);
};
export const joinPath = (directory: string, rest: string): string =>
directory === "" ? rest : rest === "" ? directory : `${directory}/${rest}`;
export type Expansion =
| { readonly scope: "target"; readonly path: string }
| { readonly scope: "outside"; readonly path: string }
| { readonly scope: "undetermined"; readonly path: string };
/** Expand one dyld path prefix relative to its owning image. */
export const expandPrefix = (
raw: string,
context: {
readonly ownerDirectory: string;
readonly executable: string | null;
},
): Expansion => {
const variable = /^@(executable_path|loader_path)(?:\/(.*))?$/u.exec(raw);
if (variable !== null) {
const rest = variable[2] ?? "";
if (variable[1] === "loader_path")
return { scope: "target", path: joinPath(context.ownerDirectory, rest) };
return context.executable === null
? { scope: "undetermined", path: raw }
: {
scope: "target",
path: joinPath(directoryOf(context.executable), rest),
};
}
if (raw.startsWith("/")) return { scope: "outside", path: raw };
return { scope: "undetermined", path: raw };
};
/**
* Slices a process may load, best first, following dyld's graded
* architectures: an x86_64h process also accepts generic x86_64.
*/
const COMPATIBLE_ARCHITECTURES: Readonly<Record<string, readonly string[]>> = {
x86_64h: ["x86_64h", "x86_64"],
};
export const compatibleSlice = (
slices: readonly MachoSlice[],
process: string,
): MachoSlice | undefined => {
for (const architecture of COMPATIBLE_ARCHITECTURES[process] ?? [process]) {
const slice = slices.find((item) => item.architecture === architecture);
if (slice !== undefined) return slice;
}
return undefined;
};
+605
View File
@@ -0,0 +1,605 @@
import { describe, expect, it } from "vitest";
import {
traceDylibLoading,
type DylibTreeEntry,
type DylibTreeView,
type MachoDependency,
type MachoImageFacts,
type MachoSlice,
} from "./dylibResolution.js";
const slice = (overrides: Partial<MachoSlice> = {}): MachoSlice => ({
architecture: "arm64",
file_type: "dylib",
install_name: null,
dependencies: [],
rpaths: [],
dyld_environment: [],
code_signature_present: true,
...overrides,
});
const dependency = (
installName: string,
overrides: Partial<MachoDependency> = {},
): MachoDependency => ({
command: "LC_LOAD_DYLIB",
encoding: "dylib_command",
install_name: installName,
weak: false,
upward: false,
reexport: false,
delayed_init: false,
current_version: "1.0.0",
compatibility_version: "1.0.0",
...overrides,
});
const parsed = (...slices: MachoSlice[]): MachoImageFacts => ({
status: "parsed",
slices,
});
const executable = (overrides: Partial<MachoSlice> = {}): MachoImageFacts =>
parsed(slice({ file_type: "execute", ...overrides }));
/** In-memory tree: files are images (or "data"), symlinks map to targets. */
const memoryView = (
files: Readonly<Record<string, MachoImageFacts | "data">>,
symlinks: Readonly<Record<string, string>> = {},
): DylibTreeView => {
const entries = new Map<string, DylibTreeEntry>();
const addParents = (path: string): void => {
const segments = path.split("/");
for (let length = 1; length < segments.length; length++)
entries.set(segments.slice(0, length).join("/"), { kind: "directory" });
};
for (const path of Object.keys(files)) {
addParents(path);
entries.set(path, { kind: "file" });
}
for (const [path, target] of Object.entries(symlinks)) {
addParents(path);
entries.set(path, { kind: "symlink", target });
}
return {
entry: (path) => Promise.resolve(entries.get(path)),
image: (path) => {
const facts = files[path];
return Promise.resolve(
facts === undefined || facts === "data"
? { status: "not-mach-o" as const }
: facts,
);
},
};
};
const MAIN = "Contents/MacOS/App";
const edgeFor = (
trace: Awaited<ReturnType<typeof traceDylibLoading>>,
loader: string,
installName: string,
) => {
const edge = trace.edges.find(
(candidate) =>
candidate.loader === loader && candidate.install_name === installName,
);
if (edge === undefined)
throw new Error(`missing ${loader} -> ${installName}`);
return edge;
};
describe("dyld path expansion", () => {
it("searches the loading image's rpaths before its loaders'", async () => {
const core = "Contents/Frameworks/Core.framework/Versions/A/Core";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [dependency("@rpath/Core.framework/Versions/A/Core")],
}),
[core]: parsed(
slice({
rpaths: ["@loader_path/Libraries"],
dependencies: [dependency("@rpath/libchain.dylib")],
}),
),
"Contents/Frameworks/libchain.dylib": parsed(slice()),
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib":
parsed(slice()),
}),
{ roots: [MAIN] },
);
const chain = edgeFor(trace, core, "@rpath/libchain.dylib");
expect(chain.via).toEqual([MAIN, core]);
expect(chain.candidates).toEqual([
expect.objectContaining({
source: "rpath",
rpath: "@loader_path/Libraries",
rpath_owner: core,
outcome: "resolved",
}),
]);
expect(chain.resolution).toEqual({
status: "resolved",
image:
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib",
});
});
it("expands @loader_path in an rpath relative to the image that owns it", async () => {
const plugin = "Contents/PlugIns/Tool.bundle/Contents/MacOS/Tool";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@loader_path/../Shared"],
dependencies: [
dependency(
`@executable_path/../PlugIns/Tool.bundle/Contents/MacOS/Tool`,
),
],
}),
[plugin]: parsed(
slice({
file_type: "bundle",
dependencies: [dependency("@rpath/libshared.dylib")],
}),
),
"Contents/Shared/libshared.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, plugin, "@rpath/libshared.dylib").candidates).toEqual(
[
expect.objectContaining({
path: "Contents/MacOS/../Shared/libshared.dylib",
rpath_owner: MAIN,
outcome: "resolved",
resolved_path: "Contents/Shared/libshared.dylib",
}),
],
);
});
it("gives each executable root its own @executable_path", async () => {
const service = "Contents/XPCServices/Fetch.xpc/Contents/MacOS/Fetch";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("@executable_path/libhere.dylib")],
}),
[service]: executable({
dependencies: [dependency("@executable_path/libhere.dylib")],
}),
"Contents/MacOS/libhere.dylib": parsed(slice()),
}),
{ roots: [MAIN, service] },
);
expect(
edgeFor(trace, MAIN, "@executable_path/libhere.dylib").resolution.status,
).toBe("resolved");
expect(
edgeFor(trace, service, "@executable_path/libhere.dylib"),
).toMatchObject({
candidates: [
{
path: "Contents/XPCServices/Fetch.xpc/Contents/MacOS/libhere.dylib",
outcome: "absent",
},
],
resolution: { status: "unresolved", image: null },
});
});
it("follows Versions/Current inside the root and stops at escaping links", async () => {
const trace = await traceDylibLoading(
memoryView(
{
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/Core.framework/Core"),
dependency("@rpath/Escape.framework/Escape"),
dependency("@executable_path/../../../outside.dylib"),
],
}),
"Contents/Frameworks/Core.framework/Versions/A/Core": parsed(slice()),
},
{
"Contents/Frameworks/Core.framework/Versions/Current": "A",
"Contents/Frameworks/Core.framework/Core": "Versions/Current/Core",
"Contents/Frameworks/Escape.framework":
"/Library/Frameworks/Escape.framework",
},
),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, MAIN, "@rpath/Core.framework/Core").resolution,
).toEqual({
status: "resolved",
image: "Contents/Frameworks/Core.framework/Versions/A/Core",
});
for (const name of [
"@rpath/Escape.framework/Escape",
"@executable_path/../../../outside.dylib",
])
expect(edgeFor(trace, MAIN, name)).toMatchObject({
candidates: [{ outcome: "escapes-target" }],
resolution: { status: "undetermined", image: null },
});
});
});
describe("dyld resolution outcomes", () => {
it("keeps paths outside the root undetermined and in-root fallbacks conditional", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/usr/lib/swift", "@executable_path/../Frameworks"],
dependencies: [
dependency("/usr/lib/libSystem.B.dylib"),
dependency("@rpath/libswiftCore.dylib"),
dependency("libleaf.dylib"),
],
}),
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, MAIN, "/usr/lib/libSystem.B.dylib")).toMatchObject({
candidates: [
{ outcome: "outside-target", path: "/usr/lib/libSystem.B.dylib" },
],
resolution: { status: "undetermined", image: null },
});
expect(edgeFor(trace, MAIN, "@rpath/libswiftCore.dylib")).toMatchObject({
candidates: [
{
outcome: "outside-target",
path: "/usr/lib/swift/libswiftCore.dylib",
},
{ outcome: "resolved" },
],
resolution: {
status: "conditional",
image: "Contents/Frameworks/libswiftCore.dylib",
},
});
expect(edgeFor(trace, MAIN, "libleaf.dylib").resolution.status).toBe(
"undetermined",
);
});
it("derives unresolved and earlier-candidate findings separately for weak loads", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: [
"@executable_path/../Overrides",
"@executable_path/../Frameworks",
],
dependencies: [
dependency("@rpath/libfound.dylib"),
dependency("@rpath/libgone.dylib", {
command: "LC_LOAD_WEAK_DYLIB",
weak: true,
}),
dependency("@rpath/libmissing.dylib"),
],
dyld_environment: ["DYLD_LIBRARY_PATH=/tmp"],
}),
"Contents/Frameworks/libfound.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(
trace.findings.map(({ kind, edge_index: index }) => [kind, index]),
).toEqual([
["earlier-rpath-candidate-absent", 0],
["weak-load-unresolved", 1],
["required-load-unresolved", 2],
["dyld-environment-present", null],
]);
expect(trace.findings[0]?.explanation).toContain(
"Contents/MacOS/../Overrides/libfound.dylib",
);
});
it("reports non-Mach-O, malformed and wrong-architecture candidates", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: [
"@executable_path/a",
"@executable_path/b",
"@executable_path/c",
],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/a/lib.dylib": "data",
"Contents/MacOS/b/lib.dylib": {
status: "malformed",
reason: "load command 0 has invalid cmdsize 0",
},
"Contents/MacOS/c/lib.dylib": parsed(slice({ architecture: "x86_64" })),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, MAIN, "@rpath/lib.dylib").candidates.map(
({ outcome }) => outcome,
),
).toEqual(["not-mach-o", "malformed", "architecture-missing"]);
expect(trace.coverage).toEqual({
status: "partial",
unparsed_images: ["Contents/MacOS/b/lib.dylib"],
roots_without_architecture: [],
});
expect(trace.images.map(({ path }) => path)).toEqual([
MAIN,
"Contents/MacOS/b/lib.dylib",
"Contents/MacOS/c/lib.dylib",
]);
});
});
describe("dyld load order", () => {
it("loads each image once per process and reuses matching install names", async () => {
const a = "Contents/Frameworks/libA.dylib";
const b = "Contents/Frameworks/libB.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/libA.dylib"),
dependency("@rpath/libB.dylib"),
],
}),
[a]: parsed(
slice({
install_name: "@rpath/libA.dylib",
dependencies: [
dependency("@rpath/libB.dylib"),
dependency("@rpath/libA.dylib"),
],
}),
),
[b]: parsed(
slice({
install_name: "@rpath/libB.dylib",
dependencies: [dependency("@rpath/libA.dylib")],
}),
),
}),
{ roots: [MAIN] },
);
expect(
trace.edges.map(
({ loader, install_name: name }) =>
`${loader.split("/").at(-1)}>${name}`,
),
).toEqual([
"App>@rpath/libA.dylib",
"App>@rpath/libB.dylib",
"libA.dylib>@rpath/libB.dylib",
"libA.dylib>@rpath/libA.dylib",
"libB.dylib>@rpath/libA.dylib",
]);
expect(edgeFor(trace, b, "@rpath/libA.dylib").candidates).toEqual([
expect.objectContaining({ source: "already-loaded", resolved_path: a }),
]);
expect(edgeFor(trace, a, "@rpath/libA.dylib").install_name_matches).toBe(
true,
);
});
it("leaves @executable_path undetermined for a library root and filters architectures", async () => {
const library = "Contents/Frameworks/libroot.dylib";
const trace = await traceDylibLoading(
memoryView({
[library]: parsed(
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
),
[MAIN]: executable(),
}),
{ roots: [library, MAIN], architecture: "x86_64" },
);
expect(trace.roots).toEqual([]);
expect(trace.coverage.roots_without_architecture).toEqual([library, MAIN]);
const arm = await traceDylibLoading(
memoryView({
[library]: parsed(
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
),
}),
{ roots: [library] },
);
expect(arm.edges[0]?.candidates).toEqual([
expect.objectContaining({
source: "executable_path",
outcome: "undetermined",
}),
]);
});
it("stops when cancelled", async () => {
const controller = new AbortController();
controller.abort();
await expect(
traceDylibLoading(memoryView({ [MAIN]: executable() }), {
roots: [MAIN],
signal: controller.signal,
}),
).rejects.toThrow();
});
});
describe("dyld slice compatibility and coverage", () => {
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
const files = {
[MAIN]: parsed(
slice({
architecture: "x86_64h",
file_type: "execute",
dependencies: [dependency("@executable_path/libgeneric.dylib")],
}),
slice({
architecture: "arm64e",
file_type: "execute",
dependencies: [dependency("@executable_path/libgeneric.dylib")],
}),
),
"Contents/MacOS/libgeneric.dylib": parsed(
slice({ architecture: "x86_64" }),
slice({ architecture: "arm64" }),
),
};
const trace = await traceDylibLoading(memoryView(files), { roots: [MAIN] });
expect(
trace.edges.map(({ architecture, candidates, resolution }) => [
architecture,
candidates[0]?.outcome,
resolution.status,
]),
).toEqual([
["x86_64h", "resolved", "resolved"],
["arm64e", "architecture-missing", "unresolved"],
]);
});
it("keeps unsupported candidates undeterminable rather than malformed", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("@executable_path/libbig.dylib")],
}),
"Contents/MacOS/libbig.dylib": {
status: "unsupported",
reason: "big-endian Mach-O images are not supported",
},
}),
{ roots: [MAIN] },
);
expect(trace.edges[0]).toMatchObject({
candidates: [{ outcome: "unsupported" }],
resolution: { status: "undetermined", image: null },
});
expect(
trace.images.find(({ path }) => path.endsWith("libbig.dylib")),
).toMatchObject({
parse_status: "unsupported",
});
});
it("reports unclassified Mach-O files as partial coverage", async () => {
const broken = "Contents/Helpers/broken";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable(),
[broken]: {
status: "malformed",
reason: "load command 0 has invalid cmdsize 0",
},
}),
{ roots: [MAIN], unclassified: [broken] },
);
expect(trace.coverage).toEqual({
status: "partial",
unparsed_images: [broken],
roots_without_architecture: [],
});
expect(trace.images.find(({ path }) => path === broken)?.reason).toBe(
"load command 0 has invalid cmdsize 0",
);
});
});
describe("lazily loaded dependencies", () => {
it("resolves lazy loads without traversing them or reporting launch failure", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/liblazy.dylib", {
command: "LC_LAZY_LOAD_DYLIB",
}),
dependency("@rpath/libmissing.dylib", {
command: "LC_LAZY_LOAD_DYLIB",
}),
],
}),
"Contents/Frameworks/liblazy.dylib": parsed(
slice({ dependencies: [dependency("@rpath/libdeep.dylib")] }),
),
}),
{ roots: [MAIN] },
);
expect(trace.edges.map(({ loader }) => loader)).toEqual([MAIN, MAIN]);
expect(trace.edges[0]?.resolution.status).toBe("resolved");
expect(trace.findings.map(({ kind }) => kind)).toEqual([
"lazy-load-unresolved",
]);
});
});
describe("conditional loads", () => {
it("carries a conditional fallback's uncertainty to its dependents and reuses", async () => {
const VENDOR = "Contents/Frameworks/libvendor.dylib";
const OTHER = "Contents/Frameworks/libother.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/opt/vendor/lib", "@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/libvendor.dylib"),
dependency("@executable_path/../Frameworks/libother.dylib"),
],
}),
[VENDOR]: parsed(
slice({
install_name: "@rpath/libvendor.dylib",
dependencies: [
dependency("@loader_path/libgone.dylib"),
dependency("@loader_path/libweak.dylib", { weak: true }),
dependency("@loader_path/liblazy.dylib", {
command: "LC_LAZY_LOAD_DYLIB",
}),
],
}),
),
[OTHER]: parsed(
slice({ dependencies: [dependency("@rpath/libvendor.dylib")] }),
),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, MAIN, "@rpath/libvendor.dylib")).toMatchObject({
resolution: { status: "conditional", image: VENDOR },
loader_conditional: false,
});
expect(edgeFor(trace, VENDOR, "@loader_path/libgone.dylib")).toMatchObject({
resolution: { status: "unresolved" },
loader_conditional: true,
});
expect(edgeFor(trace, OTHER, "@rpath/libvendor.dylib")).toMatchObject({
candidates: [{ source: "already-loaded" }],
resolution: { status: "conditional", image: VENDOR },
loader_conditional: false,
});
// Required, weak and lazy findings below the fallback are all qualified.
for (const kind of [
"required-load-unresolved",
"weak-load-unresolved",
"lazy-load-unresolved",
])
expect(
trace.findings.find((finding) => finding.kind === kind)?.explanation,
).toContain(`${VENDOR} loads only conditionally; if it loads,`);
});
});
+514
View File
@@ -0,0 +1,514 @@
import { z } from "zod";
import {
compatibleSlice,
directoryOf,
expandPrefix,
joinPath,
resolveTreePath,
type Expansion,
} from "./dyldPaths.js";
import { digestSchema } from "../digests.js";
import {
DYLIB_RESOLUTION_LIMITATIONS,
deriveFindings,
} from "./dylibResolutionFindings.js";
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
const ROOT_RELATIVE_PATH =
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
/** Caller selection of process roots and one CPU slice. */
export const dylibResolutionInputSchema = z.strictObject({
roots: z.array(rootRelativePathSchema).min(1).optional(),
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
});
const dependencyCommandSchema = z.enum([
"LC_LOAD_DYLIB",
"LC_LOAD_WEAK_DYLIB",
"LC_REEXPORT_DYLIB",
"LC_LAZY_LOAD_DYLIB",
"LC_LOAD_UPWARD_DYLIB",
]);
const dependencySchema = z.strictObject({
command: dependencyCommandSchema,
encoding: z.enum(["dylib_command", "dylib_use_command"]),
install_name: z.string(),
weak: z.boolean(),
upward: z.boolean(),
reexport: z.boolean(),
delayed_init: z.boolean(),
current_version: z.string(),
compatibility_version: z.string(),
});
/** Observed dylib-loading facts of one Mach-O slice. */
export const machoSliceSchema = z.strictObject({
architecture: z.string().min(1),
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
install_name: z.string().nullable(),
dependencies: z.array(dependencySchema),
rpaths: z.array(z.string()),
dyld_environment: z.array(z.string()),
code_signature_present: z.boolean(),
});
export type MachoDependency = z.infer<typeof dependencySchema>;
export type MachoSlice = z.infer<typeof machoSliceSchema>;
/** Header parse of one file; malformed and unsupported images keep their reason. */
export type MachoImageFacts =
| { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
| {
readonly status: "malformed" | "unsupported";
readonly reason: string;
}
| { readonly status: "not-mach-o" };
/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
export type DylibTreeEntry =
| { readonly kind: "file" | "directory" }
| { readonly kind: "symlink"; readonly target: string };
/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
export interface DylibTreeView {
entry(path: string): Promise<DylibTreeEntry | undefined>;
image(path: string): Promise<MachoImageFacts>;
}
const candidateSchema = z.strictObject({
path: z.string(),
source: z.enum([
"literal",
"executable_path",
"loader_path",
"rpath",
"already-loaded",
]),
rpath: z.string().nullable(),
rpath_owner: z.string().nullable(),
outcome: z.enum([
"resolved",
"absent",
"not-mach-o",
"malformed",
"unsupported",
"architecture-missing",
"outside-target",
"escapes-target",
"undetermined",
]),
resolved_path: z.string().nullable(),
});
const edgeSchema = z.strictObject({
root: z.string(),
architecture: z.string(),
loader: z.string(),
via: z.array(z.string()),
...dependencySchema.shape,
candidates: z.array(candidateSchema),
resolution: z.strictObject({
status: z.enum(["resolved", "conditional", "unresolved", "undetermined"]),
image: z.string().nullable(),
}),
install_name_matches: z.boolean().nullable(),
/**
* The loader was reached through a conditional edge, so it might not load;
* this edge describes what happens only if it does.
*/
loader_conditional: z.boolean(),
});
const findingSchema = z.strictObject({
kind: z.enum([
"required-load-unresolved",
"weak-load-unresolved",
"lazy-load-unresolved",
"earlier-rpath-candidate-absent",
"dyld-environment-present",
]),
edge_index: z.number().int().nonnegative().nullable(),
image: z.string().nullable(),
basis: z.literal("derived"),
explanation: z.string().min(1),
});
const imageSchema = z.strictObject({
path: z.string(),
sha256: digestSchema,
parse_status: z.enum(["parsed", "malformed", "unsupported"]),
reason: z.string().nullable(),
slices: z.array(machoSliceSchema.omit({ dependencies: true })),
});
/** Static dyld load-path resolution for every selected process root. */
export const dylibResolutionResultSchema = z.strictObject({
root_path: z.string(),
target_sha256: digestSchema,
roots: z.array(
z.strictObject({ image: z.string(), architecture: z.string() }),
),
images: z.array(imageSchema),
edges: z.array(edgeSchema),
findings: z.array(findingSchema),
coverage: z.strictObject({
status: z.enum(["complete", "partial"]),
unparsed_images: z.array(z.string()),
roots_without_architecture: z.array(z.string()),
}),
limitations: z.array(z.string().min(1)),
});
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
type Candidate = z.infer<typeof candidateSchema>;
export type DylibEdge = z.infer<typeof edgeSchema>;
export type DylibFinding = z.infer<typeof findingSchema>;
type Edge = DylibEdge;
/** Result before the adapter adds file digests and the analyzed root. */
export type DylibTrace = Omit<
DylibResolutionResult,
"root_path" | "target_sha256" | "images"
> & {
readonly images: readonly (Omit<
DylibResolutionResult["images"][number],
"sha256"
> & { readonly sha256?: never })[];
};
interface LoadedImage {
readonly slice: MachoSlice;
/** Images from the process root to this image; the rpath stack, outermost first. */
readonly chain: readonly string[];
/** Some edge on the chain was conditional: an unknown earlier candidate may load instead. */
readonly conditional: boolean;
}
interface ProcessContext {
readonly view: DylibTreeView;
readonly root: string;
readonly architecture: string;
readonly executable: string | null;
readonly loaded: Map<string, LoadedImage>;
readonly byInstallName: Map<string, string>;
readonly images: Map<string, MachoImageFacts>;
}
interface CandidateTemplate {
readonly expansion: Expansion;
readonly source: Candidate["source"];
readonly rpath: string | null;
readonly rpathOwner: string | null;
}
const candidateTemplates = (
dependency: MachoDependency,
loader: string,
context: ProcessContext,
): CandidateTemplate[] => {
const name = dependency.install_name;
if (!name.startsWith("@rpath/")) {
const source = name.startsWith("@executable_path")
? "executable_path"
: name.startsWith("@loader_path")
? "loader_path"
: "literal";
return [
{
expansion: expandPrefix(name, {
ownerDirectory: directoryOf(loader),
executable: context.executable,
}),
source,
rpath: null,
rpathOwner: null,
},
];
}
const rest = name.slice("@rpath/".length);
const owners = [...(context.loaded.get(loader)?.chain ?? [loader])].reverse();
return owners.flatMap((owner) =>
(context.loaded.get(owner)?.slice.rpaths ?? []).map((rpath) => {
const base = expandPrefix(rpath, {
ownerDirectory: directoryOf(owner),
executable: context.executable,
});
const expansion: Expansion = {
scope: base.scope,
path:
base.scope === "outside"
? `${base.path.replace(/\/+$/u, "")}/${rest}`
: joinPath(base.path, rest),
};
return { expansion, source: "rpath" as const, rpath, rpathOwner: owner };
}),
);
};
const evaluateCandidate = async (
template: CandidateTemplate,
context: ProcessContext,
): Promise<Candidate> => {
const base = {
path: template.expansion.path,
source: template.source,
rpath: template.rpath,
rpath_owner: template.rpathOwner,
};
if (template.expansion.scope === "outside")
return { ...base, outcome: "outside-target", resolved_path: null };
if (template.expansion.scope === "undetermined")
return { ...base, outcome: "undetermined", resolved_path: null };
const lookup = await resolveTreePath(context.view, template.expansion.path);
if (lookup.kind === "escapes")
return { ...base, outcome: "escapes-target", resolved_path: null };
if (lookup.kind !== "file")
return { ...base, outcome: "absent", resolved_path: null };
const facts = await imageFacts(context, lookup.path);
const outcome: Candidate["outcome"] =
facts.status !== "parsed"
? facts.status
: compatibleSlice(facts.slices, context.architecture) === undefined
? "architecture-missing"
: "resolved";
return { ...base, outcome, resolved_path: lookup.path };
};
const imageFacts = async (
context: ProcessContext,
path: string,
): Promise<MachoImageFacts> => {
const known = context.images.get(path);
if (known !== undefined) return known;
const facts = await context.view.image(path);
context.images.set(path, facts);
return facts;
};
const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
let external = false;
for (const candidate of candidates) {
if (candidate.outcome === "resolved")
return {
status: external ? "conditional" : "resolved",
image: candidate.resolved_path,
};
// dyld might load these; REA cannot decide them from the analyzed root.
if (
candidate.outcome === "outside-target" ||
candidate.outcome === "escapes-target" ||
candidate.outcome === "unsupported" ||
candidate.outcome === "undetermined"
)
external = true;
}
return { status: external ? "undetermined" : "unresolved", image: null };
};
const resolveDependency = async (
dependency: MachoDependency,
loader: string,
context: ProcessContext,
): Promise<Edge> => {
const current = context.loaded.get(loader);
const chain = current?.chain ?? [loader];
const loaded = context.byInstallName.get(dependency.install_name);
const candidates: Candidate[] = [];
if (loaded !== undefined)
candidates.push({
path: dependency.install_name,
source: "already-loaded",
rpath: null,
rpath_owner: null,
outcome: "resolved",
resolved_path: loaded,
});
else
for (const template of candidateTemplates(dependency, loader, context)) {
const candidate = await evaluateCandidate(template, context);
candidates.push(candidate);
// dyld stops at the first loadable candidate.
if (candidate.outcome === "resolved") break;
}
const searched = resolution(candidates);
// Reusing an image that itself loads only conditionally is conditional too.
const resolved: Edge["resolution"] =
loaded !== undefined &&
context.loaded.get(loaded)?.conditional === true &&
searched.status === "resolved"
? { ...searched, status: "conditional" }
: searched;
const image =
resolved.image === null ? undefined : context.images.get(resolved.image);
const slice =
image?.status === "parsed"
? compatibleSlice(image.slices, context.architecture)
: undefined;
return {
root: context.root,
architecture: context.architecture,
loader,
via: [...chain],
...dependency,
candidates,
resolution: resolved,
install_name_matches:
slice === undefined || slice.install_name === null
? null
: slice.install_name === dependency.install_name,
loader_conditional: current?.conditional ?? false,
};
};
/**
* Follow dyld4's dependents-first order: resolve every dependency of one
* image, then recurse into the images it newly loaded, in load-command order.
*/
const traceProcess = async (
context: ProcessContext,
rootSlice: MachoSlice,
signal?: AbortSignal,
): Promise<Edge[]> => {
const edges: Edge[] = [];
context.loaded.set(context.root, {
slice: rootSlice,
chain: [context.root],
conditional: false,
});
if (rootSlice.install_name !== null)
context.byInstallName.set(rootSlice.install_name, context.root);
const pending = [context.root];
while (pending.length > 0) {
signal?.throwIfAborted();
const loader = pending.pop() ?? "";
const current = context.loaded.get(loader);
if (current === undefined) continue;
const created: string[] = [];
for (const dependency of current.slice.dependencies) {
const edge = await resolveDependency(dependency, loader, context);
edges.push(edge);
// dyld loads LC_LAZY_LOAD_DYLIB images on first use, not at launch.
if (dependency.command === "LC_LAZY_LOAD_DYLIB") continue;
const image = edge.resolution.image;
if (image === null || context.loaded.has(image)) continue;
const facts = context.images.get(image);
const slice =
facts?.status === "parsed"
? compatibleSlice(facts.slices, context.architecture)
: undefined;
if (slice === undefined) continue;
context.loaded.set(image, {
slice,
chain: [...current.chain, image],
// dyld may load an unknown earlier candidate instead of this fallback.
conditional:
current.conditional || edge.resolution.status === "conditional",
});
if (
slice.install_name !== null &&
!context.byInstallName.has(slice.install_name)
)
context.byInstallName.set(slice.install_name, image);
created.push(image);
}
pending.push(...created.reverse());
}
return edges;
};
/** Trace dyld load paths from each process root through the analyzed root. */
export const traceDylibLoading = async (
view: DylibTreeView,
request: {
readonly roots: readonly string[];
/** Mach-O files whose root role could not be classified because they did not parse. */
readonly unclassified?: readonly string[];
readonly architecture?: string;
readonly signal?: AbortSignal;
},
): Promise<DylibTrace> => {
const images = new Map<string, MachoImageFacts>();
for (const path of request.unclassified ?? [])
images.set(path, await view.image(path));
const roots: DylibTrace["roots"][number][] = [];
const edges: Edge[] = [];
const withoutArchitecture: string[] = [];
for (const root of request.roots) {
const facts = await view.image(root);
images.set(root, facts);
if (facts.status !== "parsed") continue;
const slices = facts.slices.filter(
({ architecture }) =>
request.architecture === undefined ||
architecture === request.architecture,
);
if (slices.length === 0) withoutArchitecture.push(root);
for (const slice of slices) {
roots.push({ image: root, architecture: slice.architecture });
edges.push(
...(await traceProcess(
{
view,
root,
architecture: slice.architecture,
executable: slice.file_type === "execute" ? root : null,
loaded: new Map(),
byInstallName: new Map(),
images,
},
slice,
request.signal,
)),
);
}
}
const reported = [...images.entries()]
.filter(([, facts]) => facts.status !== "not-mach-o")
.sort(([left], [right]) => compare(left, right));
const unparsed = reported
.filter(([, facts]) => facts.status !== "parsed")
.map(([path]) => path);
return {
roots,
images: reported.map(([path, facts]) => ({
path,
parse_status:
facts.status === "not-mach-o" ? "unsupported" : facts.status,
reason:
facts.status === "parsed" || facts.status === "not-mach-o"
? null
: facts.reason,
slices:
facts.status === "parsed" ? facts.slices.map(withoutDependencies) : [],
})),
edges,
findings: deriveFindings(edges, roots, images),
coverage: {
status:
unparsed.length === 0 && withoutArchitecture.length === 0
? "complete"
: "partial",
unparsed_images: unparsed,
roots_without_architecture: withoutArchitecture,
},
limitations: DYLIB_RESOLUTION_LIMITATIONS,
};
};
const withoutDependencies = (
slice: MachoSlice,
): Omit<MachoSlice, "dependencies"> => ({
architecture: slice.architecture,
file_type: slice.file_type,
install_name: slice.install_name,
rpaths: slice.rpaths,
dyld_environment: slice.dyld_environment,
code_signature_present: slice.code_signature_present,
});
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
@@ -0,0 +1,93 @@
import type {
DylibEdge as Edge,
DylibFinding as Finding,
DylibTrace,
MachoImageFacts,
} from "./dylibResolution.js";
export const deriveFindings = (
edges: readonly Edge[],
roots: DylibTrace["roots"],
images: ReadonlyMap<string, MachoImageFacts>,
): Finding[] => {
const findings: Finding[] = [];
edges.forEach((edge, index) => {
if (edge.resolution.status === "unresolved")
findings.push(unresolvedFinding(edge, index));
const resolvedAt = edge.candidates.findIndex(
({ outcome }) => outcome === "resolved",
);
const earlier = edge.candidates
.slice(0, Math.max(resolvedAt, 0))
.filter(
({ source, outcome }) => source === "rpath" && outcome === "absent",
)
.map(({ path }) => path);
if (resolvedAt > 0 && earlier.length > 0)
findings.push({
kind: "earlier-rpath-candidate-absent",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: `dyld searches ${earlier.join(", ")} before ${edge.resolution.image ?? edge.install_name}. A Mach-O placed at an earlier path would load first unless code-signing library validation rejects it; library validation is not evaluated here (see inspect_signature).`,
});
});
for (const { image, architecture } of roots) {
const facts = images.get(image);
const environment =
facts?.status === "parsed"
? (facts.slices.find((slice) => slice.architecture === architecture)
?.dyld_environment ?? [])
: [];
if (environment.length > 0)
findings.push({
kind: "dyld-environment-present",
edge_index: null,
image,
basis: "derived",
explanation: `${image} (${architecture}) sets dyld environment variables through LC_DYLD_ENVIRONMENT (${environment.join(", ")}); search paths they add are not modeled.`,
});
}
return findings;
};
const unresolvedFinding = (edge: Edge, index: number): Finding => {
const base = {
edge_index: index,
image: edge.loader,
basis: "derived",
} as const;
const missing = `No candidate for ${edge.command === "LC_LAZY_LOAD_DYLIB" ? "lazily loaded " : edge.weak ? "weak dependency " : ""}${edge.install_name} exists in the analyzed root`;
// Below a conditional fallback, every consequence applies only if it loads.
const when = edge.loader_conditional
? `. ${edge.loader} loads only conditionally; if it loads, `
: "; ";
if (edge.command === "LC_LAZY_LOAD_DYLIB")
return {
...base,
kind: "lazy-load-unresolved",
explanation: `${missing}${when}dyld loads it on first use, which would fail unless the image is supplied elsewhere.`,
};
return edge.weak
? {
...base,
kind: "weak-load-unresolved",
explanation: `${missing}${when}dyld continues without it.`,
}
: {
...base,
kind: "required-load-unresolved",
explanation: `${missing}${when}dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`,
};
};
export const DYLIB_RESOLUTION_LIMITATIONS = [
"LC_LAZY_LOAD_DYLIB dependencies are resolved but not traversed, because dyld loads them only on first use.",
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
];
+57 -44
View File
@@ -202,53 +202,66 @@ export const buildInterfaceBuilderAnalysis = (input: {
};
let hierarchyCount = 0;
let hierarchyTruncated = false;
const visitHierarchy = (value: unknown, parentId: string): void => {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
return;
}
if (Array.isArray(value)) {
for (const child of value) visitHierarchy(child, parentId);
return;
}
if (typeof value !== "object" || value === null) return;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
const visitHierarchy = (
initial: unknown,
initialParentId: string,
): void => {
const pending: { readonly value: unknown; readonly parentId: string }[] =
[{ value: initial, parentId: initialParentId }];
while (pending.length > 0) {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
return;
}
const entry = pending.pop();
if (entry === undefined) break;
const { value, parentId } = entry;
if (Array.isArray(value)) {
for (let index = value.length - 1; index >= 0; index -= 1) {
const child = value[index];
if (child !== undefined) pending.push({ value: child, parentId });
}
continue;
}
if (typeof value !== "object" || value === null) continue;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
nextParent = childId;
hierarchyCount += 1;
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
);
nextParent = childId;
hierarchyCount += 1;
}
pending.push({ value: item.children, parentId: nextParent });
}
visitHierarchy(item.children, nextParent);
};
for (const hierarchy of parsed.hierarchy) visitHierarchy(hierarchy, rootId);
for (const [index, item] of parsed.connections
@@ -196,39 +196,85 @@ const keyedArchiveTable = (objectTable: readonly unknown[]) => {
};
const hierarchy = (start: unknown): unknown[] => {
const visited = new Set<number>();
const node = (
const root: unknown[] = [];
const pending: { readonly value: unknown; readonly output: unknown[] }[] = [
{ value: start, output: root },
];
const appendNode = (
item: Record<string, unknown>,
uid: number | undefined,
depth: number,
): unknown[] => {
output: unknown[],
): void => {
const objectId = firstString(
authoredId(item),
text(item.id),
uid === undefined ? null : String(uid),
);
const children = Object.entries(item)
.filter(([key]) => HIERARCHY_KEY.test(key))
.flatMap(([, child]) => visit(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
if (objectId === null) {
for (const [key, child] of Object.entries(item).reverse())
if (HIERARCHY_KEY.test(key)) pending.push({ value: child, output });
return;
}
const children: unknown[] = [];
output.push({ objectID: objectId, children });
for (const [key, child] of Object.entries(item).reverse())
if (HIERARCHY_KEY.test(key))
pending.push({ value: child, output: children });
};
const visit = (value: unknown, depth: number): unknown[] => {
if (depth > 32) return [];
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined) break;
const { value, output } = entry;
const uid = archiveUid(value);
if (uid !== undefined) {
if (visited.has(uid)) return [];
if (visited.has(uid)) continue;
visited.add(uid);
const target = objectTable[uid];
if (Array.isArray(target)) return visit(target, depth + 1);
return typeof target === "object" && target !== null
? node(record(target), uid, depth)
: [];
if (Array.isArray(target)) {
for (let index = target.length - 1; index >= 0; index -= 1) {
const child = target[index];
if (child !== undefined) pending.push({ value: child, output });
}
continue;
}
if (typeof target !== "object" || target === null) continue;
const item = record(target);
if (archivedArrayClass(item.$class)) {
const members = item["NS.objects"];
if (Array.isArray(members))
for (let index = members.length - 1; index >= 0; index -= 1) {
const child = members[index];
if (child !== undefined) pending.push({ value: child, output });
}
continue;
}
appendNode(item, uid, output);
continue;
}
if (Array.isArray(value))
return value.flatMap((item) => visit(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
return node(record(value), undefined, depth);
};
return visit(start, 0);
if (Array.isArray(value)) {
for (let index = value.length - 1; index >= 0; index -= 1) {
const child = value[index];
if (child !== undefined) pending.push({ value: child, output });
}
} else if (typeof value === "object" && value !== null) {
appendNode(record(value), undefined, output);
}
}
return root;
};
const archivedArrayClass = (classReference: unknown): boolean => {
const uid = archiveUid(classReference);
const descriptor = record(
uid === undefined ? classReference : objectTable[uid],
);
const classNames = Array.isArray(descriptor.$classes)
? descriptor.$classes.filter(
(name): name is string => typeof name === "string",
)
: [];
return (
classNames.includes("NSArray") || classNames.includes("NSMutableArray")
);
};
return { resolve, hierarchy };
};
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { MAX_JSON_DEPTH } from "../jsonValue.js";
import { projectKeyedArchive } from "./keyedArchive.js";
const deepValue = (depth: number): unknown => {
let value: unknown = 1;
for (let index = 0; index < depth; index += 1) value = { nested: value };
return value;
};
describe("projectKeyedArchive input bound", () => {
it("rejects an over-deep archive value with a validation error instead of crashing", () => {
let error: unknown;
try {
projectKeyedArchive(deepValue(MAX_JSON_DEPTH + 1), {
offset: 0,
limit: 1,
});
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(z.ZodError);
expect(error).not.toBeInstanceOf(RangeError);
});
});
+9 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { AnalysisInputError } from "../analysisErrorCore.js";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
/** Select one archive within the active bundle and optionally one named root. */
@@ -85,7 +86,14 @@ export const projectKeyedArchive = (
if (top === undefined || Object.keys(top).length === 0)
throw new TypeError("Keyed archive has no $top roots");
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
throw new TypeError(`Archive root does not exist: ${selection.root}`);
throw new AnalysisInputError("inspect_keyed_archive", undefined, [
{
path: ["root"],
reason: "invalid_value",
message: `Archive root does not exist: ${selection.root}. Select one of the archive's $top roots or omit root.`,
expected: Object.keys(top),
},
]);
const roots =
selection.root === undefined
? top
+1
View File
@@ -12,6 +12,7 @@ export class ArtifactOperationError extends AnalysisError {
| "decode_interface_builder"
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "trace_dylib_resolution"
| "export_web_scripts"
| "trace_web_module_imports"
| "trace_web_source_location"
+5
View File
@@ -12,6 +12,11 @@ describe("artifact path syntax", () => {
expect(hasScheme("https://example.test/app.js")).toBe(true);
expect(hasScheme("file:///app.js")).toBe(true);
expect(hasScheme("node:fs")).toBe(true);
expect(hasScheme("web3:app.js")).toBe(true);
expect(hasScheme("h323:user@example.test")).toBe(true);
expect(hasScheme("x1+custom.v2-test:asset")).toBe(true);
expect(hasScheme("3web:app.js")).toBe(false);
expect(hasScheme("./web3:app.js")).toBe(false);
expect(hasScheme("./relative.js")).toBe(false);
expect(hasScheme("/absolute.js")).toBe(false);
expect(hasScheme("app.js")).toBe(false);
+1 -1
View File
@@ -17,7 +17,7 @@
/** Whether a reference carries a URI scheme (`https:`, `file:`, …). */
export const hasScheme = (value: string): boolean =>
/^[A-Za-z][A-Za-z+.-]*:/u.test(value);
/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);
/** Whether a reference is scheme-qualified or protocol-relative. */
export const looksExternal = (value: string): boolean =>
+1 -1
View File
@@ -94,7 +94,7 @@ const browserInput = {
};
/** Public input for complete discovery, optionally filtered by exact origin. */
export const listBrowserTargetsInputSchema = z.object({
export const listBrowserTargetsInputSchema = z.strictObject({
...browserInput,
});
+15
View File
@@ -114,6 +114,21 @@ const browserNetworkRequestSchema = z.object({
status: z.number().nullable(),
mime_type: z.string().nullable(),
encoded_data_length: z.number().min(0).nullable(),
redirects: z
.array(
z.object({
url: z.string(),
response_url: z.string(),
method: z.string(),
resource_type: z.string().nullable(),
status: z.number().nullable(),
mime_type: z.string().nullable(),
encoded_data_length: z.number().min(0).nullable(),
request_timestamp: z.number().nullable(),
redirect_event_timestamp: z.number().nullable(),
}),
)
.optional(),
initiator: z.object({
type: z.string(),
url: z.string().nullable(),
+1 -1
View File
@@ -56,7 +56,7 @@ it("does not require duplicate origin scope declarations", () => {
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
executable_path: "chrome",
executable_path: "/opt/chromium/chrome",
},
start_url: { url: "https://app.example.test/" },
actions: [
+12 -2
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { isAbsoluteLocalPath } from "./localPath.js";
import { browserNetworkContentSelectionSchema } from "./browserNetworkEvidence.js";
import {
@@ -11,7 +12,14 @@ export const scenarioIdentifierSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9._-]*$/u);
const browserExecutablePathSchema = z.string().trim().min(1);
const browserExecutablePathSchema = z
.string()
.trim()
.min(1)
.refine(isAbsoluteLocalPath, {
message:
"executable_path must be an absolute local filesystem path (for example /opt/chromium/chrome or C:\\chromium\\chrome.exe)",
});
const browserScenarioBaseUrlSchema = z
.string()
@@ -67,7 +75,9 @@ export type BrowserScenarioUrl = z.infer<typeof browserScenarioUrlSchema>;
export const browserScenarioBrowserSchema = z.discriminatedUnion("mode", [
z.strictObject({
mode: z.literal("launch"),
executable_path: browserExecutablePathSchema,
executable_path: browserExecutablePathSchema.describe(
"Absolute local filesystem path for the browser executable; relative paths are rejected.",
),
headless: z
.boolean()
.default(true)
-160
View File
@@ -1,160 +0,0 @@
import { describe, expect, it } from "vitest";
import {
analyzeBytecodeArtifacts,
bytecodeAnalysisSchema,
classifyProvenance,
detectArtifactFormat,
detectBytecodeFamily,
type BytecodeArtifact,
} from "./bytecodeProvider.js";
describe("bytecode provider", () => {
it("detects JVM family from extensions", () => {
expect(detectBytecodeFamily("App.class")).toBe("jvm");
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
});
it("detects Python family from extensions", () => {
expect(detectBytecodeFamily("module.pyc")).toBe("python");
expect(detectBytecodeFamily("module.pyo")).toBe("python");
expect(detectBytecodeFamily("package.whl")).toBe("python");
expect(detectBytecodeFamily("app.pyz")).toBe("python");
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
});
it("returns null for unknown extensions", () => {
expect(detectBytecodeFamily("readme.txt")).toBeNull();
expect(detectBytecodeFamily("script.js")).toBeNull();
});
it("detects artifact format from path", () => {
expect(detectArtifactFormat("App.class")).toBe("class");
expect(detectArtifactFormat("lib.jar")).toBe("jar");
expect(detectArtifactFormat("web.war")).toBe("war");
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
});
it("classifies standard library provenance", () => {
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
"standard_library",
);
expect(
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
).toBe("standard_library");
});
it("classifies generated provenance", () => {
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
"generated",
);
expect(
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
).toBe("generated");
});
it("classifies vendored provenance", () => {
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
"vendored",
);
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
"vendored",
);
});
it("classifies application provenance", () => {
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
"application",
);
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
});
it("analyzes bytecode artifacts and computes summary", () => {
const artifacts: BytecodeArtifact[] = [
{
path: "src/App.class",
family: "jvm",
format: "class",
size: 1000,
digest: "a".repeat(64),
symbols: [
{
name: "com.example.App",
raw_location: "0x1000",
kind: "class",
bytecode_version: 52,
provenance: "application",
is_public: true,
},
{
name: "java.lang.String",
raw_location: "0x2000",
kind: "class",
bytecode_version: 52,
provenance: "standard_library",
is_public: true,
},
],
is_standard_library: false,
is_generated: false,
is_vendored: false,
},
{
path: "lib/generated/Generated.class",
family: "jvm",
format: "class",
size: 500,
digest: "b".repeat(64),
symbols: [
{
name: "GeneratedClass",
raw_location: "0x3000",
kind: "class",
bytecode_version: 52,
provenance: "generated",
is_public: false,
},
],
is_standard_library: false,
is_generated: true,
is_vendored: false,
},
];
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.family).toBe("jvm");
expect(result.total_symbols).toBe(3);
expect(result.application_symbols).toBe(1);
expect(result.standard_library_symbols).toBe(1);
expect(result.generated_symbols).toBe(1);
expect(result.vendored_symbols).toBe(0);
// Validate schema
const parsed = bytecodeAnalysisSchema.safeParse(result);
expect(parsed.success).toBe(true);
});
it("returns every artifact when the inventory exceeds ten thousand entries", () => {
const artifacts = Array.from({ length: 10_001 }, (_, index) => ({
path: `classes/${index}.class`,
family: "jvm" as const,
format: "class" as const,
size: 1,
digest: "a".repeat(64),
symbols: [],
is_standard_library: false,
is_generated: false,
is_vendored: false,
}));
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.artifacts).toHaveLength(artifacts.length);
expect(bytecodeAnalysisSchema.parse(result).artifacts).toHaveLength(
artifacts.length,
);
});
});
-204
View File
@@ -1,204 +0,0 @@
import { z } from "zod";
/** Supported managed-runtime bytecode families. */
export const bytecodeFamilySchema = z.enum(["jvm", "python"]);
export type BytecodeFamily = z.infer<typeof bytecodeFamilySchema>;
/** Classification of bytecode provenance. */
export const bytecodeProvenanceSchema = z.enum([
"application",
"generated",
"vendored",
"bundled",
"standard_library",
]);
export type BytecodeProvenance = z.infer<typeof bytecodeProvenanceSchema>;
/** A bytecode symbol discovered through static analysis. */
export const bytecodeSymbolSchema = z.strictObject({
/** Fully qualified name. */
name: z.string().min(1),
/** Raw bytecode location or offset. */
raw_location: z.string().min(1),
/** Normalized symbol type. */
kind: z.enum([
"class",
"interface",
"method",
"field",
"function",
"module",
"variable",
]),
/** Bytecode version if known. */
bytecode_version: z.number().int().nullable(),
/** Provenance classification. */
provenance: bytecodeProvenanceSchema,
/** Whether the symbol is accessible (public). */
is_public: z.boolean().default(false),
});
/** A discovered bytecode artifact (class file, wheel, etc). */
export const bytecodeArtifactSchema = z.strictObject({
/** Artifact path relative to the analysis root. */
path: z.string().min(1),
/** Bytecode family. */
family: bytecodeFamilySchema,
/** Artifact format. */
format: z.enum(["class", "jar", "war", "ear", "pyc", "pyo", "whl", "zipapp"]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z.string().regex(/^[a-f0-9]{64}$/u),
/** Discovered symbols. */
symbols: z.array(bytecodeSymbolSchema).default([]),
/** Whether this is a standard library artifact. */
is_standard_library: z.boolean().default(false),
/** Whether this is a generated artifact. */
is_generated: z.boolean().default(false),
/** Whether this is a vendored artifact. */
is_vendored: z.boolean().default(false),
});
export type BytecodeArtifact = z.infer<typeof bytecodeArtifactSchema>;
/** Static bytecode analysis result. */
export const bytecodeAnalysisSchema = z.strictObject({
/** Bytecode family. */
family: bytecodeFamilySchema,
/** All discovered artifacts. */
artifacts: z.array(bytecodeArtifactSchema),
/** Total symbols across all artifacts. */
total_symbols: z.number().int().nonnegative(),
/** Symbols classified as application code. */
application_symbols: z.number().int().nonnegative(),
/** Symbols classified as generated code. */
generated_symbols: z.number().int().nonnegative(),
/** Symbols classified as vendored code. */
vendored_symbols: z.number().int().nonnegative(),
/** Symbols classified as standard library. */
standard_library_symbols: z.number().int().nonnegative(),
});
export type BytecodeAnalysis = z.infer<typeof bytecodeAnalysisSchema>;
/** Detect bytecode family from file extension. */
export function detectBytecodeFamily(path: string): BytecodeFamily | null {
const lower = path.toLowerCase();
if (
lower.endsWith(".class") ||
lower.endsWith(".jar") ||
lower.endsWith(".war") ||
lower.endsWith(".ear")
) {
return "jvm";
}
if (
lower.endsWith(".pyc") ||
lower.endsWith(".pyo") ||
lower.endsWith(".whl") ||
lower.endsWith(".pyz") ||
lower.endsWith(".zipapp")
) {
return "python";
}
return null;
}
/** Detect artifact format from file path. */
export function detectArtifactFormat(
path: string,
): `class` | `jar` | `war` | `ear` | `pyc` | `pyo` | `whl` | `zipapp` | null {
const lower = path.toLowerCase();
if (lower.endsWith(".class")) return "class";
if (lower.endsWith(".jar")) return "jar";
if (lower.endsWith(".war")) return "war";
if (lower.endsWith(".ear")) return "ear";
if (lower.endsWith(".pyc")) return "pyc";
if (lower.endsWith(".pyo")) return "pyo";
if (lower.endsWith(".whl")) return "whl";
if (lower.endsWith(".pyz") || lower.endsWith(".zipapp")) return "zipapp";
return null;
}
const STANDARD_LIBRARY_PATH_MARKERS = [
"/stdlib/",
"/site-packages/",
"java/",
"javax/",
"sun/",
];
const STANDARD_LIBRARY_SYMBOL_MARKERS = ["java.", "javax.", "sun.", "__"];
const GENERATED_PATH_MARKERS = [
"/generated/",
"_generated",
"/build/",
"/target/",
"/dist-packages/",
"/__pycache__/",
];
const GENERATED_SYMBOL_MARKERS = ["Generated", "_generated"];
const VENDORED_PATH_MARKERS = [
"/vendor/",
"/vendored/",
"/third_party/",
"/3rdparty/",
"/node_modules/",
];
const BUNDLED_PATH_MARKERS = ["/bundle/", "/bundled/", ".jar!", ".war!"];
const includesAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.includes(marker));
const startsWithAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.startsWith(marker));
/** Classify bytecode symbol provenance. */
export function classifyProvenance(
path: string,
symbolName: string,
): BytecodeProvenance {
const lower = path.toLowerCase();
if (
includesAny(lower, STANDARD_LIBRARY_PATH_MARKERS) ||
startsWithAny(symbolName, STANDARD_LIBRARY_SYMBOL_MARKERS)
)
return "standard_library";
if (
includesAny(lower, GENERATED_PATH_MARKERS) ||
includesAny(symbolName, GENERATED_SYMBOL_MARKERS)
)
return "generated";
if (includesAny(lower, VENDORED_PATH_MARKERS)) return "vendored";
if (includesAny(lower, BUNDLED_PATH_MARKERS)) return "bundled";
return "application";
}
/** Analyze a set of bytecode artifacts and produce a summary. */
export function analyzeBytecodeArtifacts(
artifacts: readonly BytecodeArtifact[],
family: BytecodeFamily,
): BytecodeAnalysis {
const totals = artifacts.reduce(
(counts, artifact) => {
counts.total += artifact.symbols.length;
for (const symbol of artifact.symbols) counts[symbol.provenance] += 1;
return counts;
},
{
total: 0,
application: 0,
generated: 0,
vendored: 0,
standard_library: 0,
bundled: 0,
},
);
return {
family,
artifacts: [...artifacts],
total_symbols: totals.total,
application_symbols: totals.application,
generated_symbols: totals.generated,
vendored_symbols: totals.vendored,
standard_library_symbols: totals.standard_library,
};
}
+1 -1
View File
@@ -24,7 +24,7 @@ export const parseCallPathAddress = (input: unknown): string =>
inputAddressSchema.parse(input);
/** Strict input for explicit call-path reconstruction from complete dossiers. */
export const callPathInputSchema = z.object({
export const callPathInputSchema = z.strictObject({
functions: z.array(evidenceSchema).min(1),
start: z.object({ address: inputAddressSchema }).strict(),
goal: z.object({ address: inputAddressSchema }).strict(),
+7
View File
@@ -62,6 +62,13 @@ describe("incremental canonical digest", () => {
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
});
it("keeps digests identical when buffered parts cross flush boundaries", () => {
const manyKeys: Record<string, unknown> = {};
for (let i = 0; i < 2000; i += 1) manyKeys[`k${i}`] = i;
const value = { keys: manyKeys, tail: ["€", "😀", "x".repeat(9000)] };
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
});
it("preserves canonicalize property access and toJSON cycle behavior", () => {
const createAccessor = () => {
let reads = 0;
+12 -1
View File
@@ -6,8 +6,19 @@ export const digestCanonicalValue = (
context = "Comparison",
): string => {
const hash = createHash("sha256");
const encoded = emitCanonical(value, (part) => hash.update(part), new Set());
// Batch small emitted parts to cut hash.update crossings.
// Flush cuts only at part boundaries, so the hashed byte stream is unchanged.
let buffered = "";
const emit = (part: string): void => {
buffered += part;
if (buffered.length >= 8192) {
hash.update(buffered);
buffered = "";
}
};
const encoded = emitCanonical(value, emit, new Set());
if (!encoded) throw new TypeError(`${context} could not canonicalize data`);
if (buffered) hash.update(buffered);
return hash.digest("hex");
};
+3 -3
View File
@@ -7,19 +7,19 @@ import { functionComparisonResultSchema } from "./functionComparison.js";
import {
PROCESS_PROVIDER,
isProcessEvidenceProvider,
} from "./processEvidenceProvider.js";
} from "./process/processEvidenceProvider.js";
import {
comparisonStatusSchema,
deriveProcessComparisonStatus,
PROCESS_COMPARISON_DIMENSIONS,
processCaptureComparisonSchema,
} from "./processCapture.js";
} from "./process/processCapture.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
/** Input for aggregating existing comparison Evidence. */
export const changedBehaviorInputSchema = z.object({
export const changedBehaviorInputSchema = z.strictObject({
comparisons: z.array(evidenceSchema).default([]),
});
+1 -7
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { absenceClaimable, canonicalDigest } from "./comparisonSemantics.js";
import { absenceClaimable } from "./comparisonSemantics.js";
describe("shared comparison semantics", () => {
it("permits absence claims only for complete, non-truncated inventories", () => {
@@ -27,10 +27,4 @@ describe("shared comparison semantics", () => {
).toBe(false);
expect(absenceClaimable({ status: "partial" })).toBe(false);
});
it("produces one stable SHA-256 for equivalent canonical JSON values", () => {
expect(canonicalDigest({ b: 2, a: 1 })).toBe(
canonicalDigest({ a: 1, b: 2 }),
);
});
});
-86
View File
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vitest";
import {
bundleClassificationToCanonical,
comparisonConclusionSchema,
comparisonStatusSchema,
functionStatusToCanonical,
scenarioArtifactStatusToCanonical,
sourceToBundleStatusToCanonical,
} from "./comparisonStatus.js";
describe("comparison status vocabulary", () => {
it("owns the canonical unchanged/changed/unknown triple", () => {
expect(comparisonStatusSchema.options).toEqual([
"unchanged",
"changed",
"unknown",
]);
expect(comparisonConclusionSchema.options).toEqual([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
});
it("projects every bundle classification", () => {
expect(
(
[
"added",
"removed",
"changed",
"unknown",
"history_advanced",
"history_diverged",
] as const
).map(bundleClassificationToCanonical),
).toEqual([
"changed",
"changed",
"changed",
"unknown",
"changed",
"changed",
]);
});
it("projects every source-to-bundle item status", () => {
expect(
(
[
"unchanged",
"modified",
"removed",
"split",
"merged",
"duplicated",
"unknown",
] as const
).map(sourceToBundleStatusToCanonical),
).toEqual([
"unchanged",
"changed",
"changed",
"changed",
"changed",
"changed",
"unknown",
]);
});
it("projects every function dimension status without claiming truncated work", () => {
expect(
(["unchanged", "changed", "truncated", "unknown"] as const).map(
functionStatusToCanonical,
),
).toEqual(["unchanged", "changed", "unknown", "unknown"]);
});
it("projects every scenario artifact status", () => {
expect(
(["changed", "unknown"] as const).map(scenarioArtifactStatusToCanonical),
).toEqual(["changed", "unknown"]);
});
});
+2 -60
View File
@@ -2,69 +2,11 @@ import { z } from "zod";
/**
* Canonical top-level comparison outcome shared by every comparison
* pipeline. Pipeline-native detail enums (bundle classifications,
* source-to-bundle split/merge kinds, scenario alignment states, function
* truncation) keep their wire schemas; the mappers below project each of
* them onto this triple without changing any pipeline result.
* pipeline. Pipeline-native detail enums keep their wire schemas, while
* shared result contracts use this canonical triple.
*/
export const comparisonStatusSchema = z.enum([
"unchanged",
"changed",
"unknown",
]);
export type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
/** Canonical comparison conclusion shared by every comparison pipeline. */
export const comparisonConclusionSchema = z.enum([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
/** Project a bundle change classification onto the canonical triple. */
export const bundleClassificationToCanonical = (
classification:
| "added"
| "removed"
| "changed"
| "unknown"
| "history_advanced"
| "history_diverged",
): ComparisonStatus => (classification === "unknown" ? "unknown" : "changed");
/** Project a source-to-bundle item status onto the canonical triple. */
export const sourceToBundleStatusToCanonical = (
status:
| "unchanged"
| "modified"
| "removed"
| "split"
| "merged"
| "duplicated"
| "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "unknown"
? "unknown"
: "changed";
/**
* Project a function dimension status onto the canonical triple. A
* truncated dimension cannot support an unchanged/changed claim.
*/
export const functionStatusToCanonical = (
status: "unchanged" | "changed" | "truncated" | "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "changed"
? "changed"
: "unknown";
/** Project a browser-scenario artifact status onto the canonical triple. */
export const scenarioArtifactStatusToCanonical = (
status: "changed" | "unknown",
): ComparisonStatus => status;
-18
View File
@@ -51,19 +51,6 @@ const VOLATILE_DIMENSIONS = new Set([
"updated_at",
]);
/** Dimension that carries semantic content. */
const SEMANTIC_DIMENSIONS = new Set([
"exit_code",
"stdout",
"stderr",
"filesystem",
"process",
"process_tree",
"shim_events",
"protocol_events",
"event_journal",
]);
type IncompleteStatus = "unknown" | "truncated";
type EvidenceView = {
@@ -214,11 +201,6 @@ export function isVolatileDimension(name: string): boolean {
return VOLATILE_DIMENSIONS.has(name);
}
/** Check if a dimension name carries semantic content. */
export function isSemanticDimension(name: string): boolean {
return SEMANTIC_DIMENSIONS.has(name);
}
/**
* Compare two values for a dimension, classifying semantic diffs
* from timing/normalization noise.
-158
View File
@@ -1,158 +0,0 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
authEventsByProtocol,
authFlowDuration,
customProtocolCaptureSchema,
correlateProcessIdentity,
failedAuthEvents,
framesByTransport,
looksLikeCredentialFrame,
successfulAuthEvents,
type AuthFlowEvent,
type ProtocolFrame,
} from "./customProtocolCapture.js";
const sampleFrames: ProtocolFrame[] = [
{
sequence: 0,
at_ms: 100,
transport: "tcp",
direction: "sent",
source_pid: 100,
dest_pid: 200,
source_endpoint: "127.0.0.1:8080",
dest_endpoint: "127.0.0.1:9090",
raw_data: "hello",
decoded_content: "hello",
size: 5,
truncated: false,
},
{
sequence: 1,
at_ms: 200,
transport: "udp",
direction: "received",
source_pid: 200,
dest_pid: 100,
source_endpoint: "127.0.0.1:9090",
dest_endpoint: "127.0.0.1:8080",
raw_data: "world",
decoded_content: "world",
size: 5,
truncated: false,
},
];
const sampleAuthEvents: AuthFlowEvent[] = [
{
sequence: 0,
at_ms: 100,
stage: "init",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: false,
error: null,
},
{
sequence: 1,
at_ms: 500,
stage: "success",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: true,
error: null,
},
];
describe("custom protocol capture", () => {
it("rejects a capture with an unknown transport", () => {
const result = customProtocolCaptureSchema.safeParse({
transport: "carrier-pigeon",
frames: sampleFrames,
auth_events: sampleAuthEvents,
has_truncated: false,
credentials_detected: false,
});
expect(result.success).toBe(false);
});
it("retains every captured frame at any size", () => {
fc.assert(
fc.property(
// The bound must sit well above any ceiling a future change would
// plausibly introduce. A generated length of 40 would pass unnoticed
// against a cap at 100, so the generated arrays cross 1,000.
fc.array(fc.constant(sampleFrames[0]!), {
minLength: 300,
maxLength: 1_000,
}),
(frames) => {
const parsed = customProtocolCaptureSchema.parse({
transport: "tcp",
frames: frames.map((frame, sequence) => ({ ...frame, sequence })),
});
expect(parsed.frames).toHaveLength(frames.length);
},
),
{ numRuns: 25 },
);
});
it("correlates process identity", () => {
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
});
it("filters frames by transport", () => {
const tcpFrames = framesByTransport(sampleFrames, "tcp");
expect(tcpFrames).toHaveLength(1);
const udpFrames = framesByTransport(sampleFrames, "udp");
expect(udpFrames).toHaveLength(1);
});
it("detects credential-like frames", () => {
const credFrame: ProtocolFrame = {
...sampleFrames[0]!,
decoded_content: { password: "secret" },
};
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
});
it("filters auth events by protocol", () => {
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
expect(oauthEvents).toHaveLength(2);
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
expect(otherEvents).toHaveLength(0);
});
it("gets successful auth events", () => {
const success = successfulAuthEvents(sampleAuthEvents);
expect(success).toHaveLength(1);
expect(success[0]!.succeeded).toBe(true);
});
it("gets failed auth events", () => {
const failed = failedAuthEvents(sampleAuthEvents);
expect(failed).toHaveLength(1);
expect(failed[0]!.succeeded).toBe(false);
});
it("computes auth flow duration", () => {
const duration = authFlowDuration(sampleAuthEvents);
expect(duration).toBe(400);
});
it("returns null for empty auth events", () => {
expect(authFlowDuration([])).toBeNull();
});
});
-169
View File
@@ -1,169 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Supported transport types for custom protocol capture. */
export const transportTypeSchema = z.enum([
"tcp",
"udp",
"ipc",
"unix-socket",
"named-pipe",
"xpc",
]);
export type TransportType = z.infer<typeof transportTypeSchema>;
/** Direction of a protocol frame. */
export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
/** A captured protocol frame. */
export const protocolFrameSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Transport type. */
transport: transportTypeSchema,
/** Direction of the frame. */
direction: frameDirectionSchema,
/** Source process identity. */
source_pid: z.number().int().nullable(),
/** Destination process identity. */
dest_pid: z.number().int().nullable(),
/** Endpoint address (IP:port, socket path, pipe name). */
source_endpoint: z.string().nullable(),
/** Destination endpoint. */
dest_endpoint: z.string().nullable(),
/** Raw frame data as base64. */
raw_data: z.string().nullable(),
/** Decoded/parsed frame content if known. */
decoded_content: jsonValueSchema.nullable(),
/** Frame size in bytes. */
size: z.number().int().nonnegative(),
/** Whether the frame was truncated. */
truncated: z.boolean().default(false),
});
export type ProtocolFrame = z.infer<typeof protocolFrameSchema>;
/** Authentication flow stage. */
export const authStageSchema = z.enum([
"init",
"challenge",
"response",
"token_exchange",
"renewal",
"revocation",
"failure",
"success",
]);
/** Token lifecycle event. */
export const tokenLifecycleEventSchema = z.enum([
"issued",
"refreshed",
"expired",
"revoked",
"renewed",
]);
/** A captured authentication flow event. */
export const authFlowEventSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Authentication stage. */
stage: authStageSchema,
/** Protocol used. */
protocol: z.string().min(1),
/** Token type if applicable. */
token_type: z.string().nullable(),
/** Token lifecycle event. */
token_lifecycle: tokenLifecycleEventSchema.nullable(),
/** Correlation ID linking challenge-response pairs. */
correlation_id: z.string().nullable(),
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
/** Whether the authentication succeeded. */
succeeded: z.boolean().default(false),
/** Error message if authentication failed. */
error: z.string().nullable(),
});
export type AuthFlowEvent = z.infer<typeof authFlowEventSchema>;
/** A captured protocol session. */
export const customProtocolCaptureSchema = z.strictObject({
/** Transport type for this session. */
transport: transportTypeSchema,
/** Captured frames in order. */
frames: z.array(protocolFrameSchema),
/** Authentication flow events. */
auth_events: z.array(authFlowEventSchema).default([]),
/** Whether any frame was truncated. */
has_truncated: z.boolean().default(false),
/** Whether the capture producer detected credential content. */
credentials_detected: z.boolean().default(false),
});
/** Correlate a frame with process identity. */
export function correlateProcessIdentity(
frame: ProtocolFrame,
pid: number,
): boolean {
return frame.source_pid === pid || frame.dest_pid === pid;
}
/** Check if a frame contains credential-like content. */
export function looksLikeCredentialFrame(frame: ProtocolFrame): boolean {
const patterns = [
"password",
"token",
"secret",
"api_key",
"apikey",
"authorization",
"credential",
];
const content = JSON.stringify(frame.decoded_content ?? "").toLowerCase();
return patterns.some((p) => content.includes(p));
}
/** Filter frames by transport type. */
export function framesByTransport(
frames: readonly ProtocolFrame[],
transport: TransportType,
): ProtocolFrame[] {
return frames.filter((f) => f.transport === transport);
}
/** Get all authentication flow events for a specific protocol. */
export function authEventsByProtocol(
events: readonly AuthFlowEvent[],
protocol: string,
): AuthFlowEvent[] {
return events.filter((e) => e.protocol === protocol);
}
/** Get successful authentication events. */
export function successfulAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => e.succeeded);
}
/** Get failed authentication events. */
export function failedAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => !e.succeeded);
}
/** Compute the duration of an authentication flow in milliseconds. */
export function authFlowDuration(
events: readonly AuthFlowEvent[],
): number | null {
const first = events.at(0);
const last = events.at(-1);
if (first === undefined || last === undefined) return null;
return last.at_ms - first.at_ms;
}
-6
View File
@@ -5,7 +5,6 @@ import {
isDigest,
isPrefixedDigest,
prefixedDigestSchema,
SHA256_PATTERN,
} from "./digests.js";
const DIGEST = "a".repeat(64);
@@ -59,9 +58,4 @@ describe("digest shapes", () => {
`jag_${OTHER_DIGEST}`,
);
});
it("exposes the pattern for callers that cannot use zod", () => {
expect(SHA256_PATTERN.test(DIGEST)).toBe(true);
expect(SHA256_PATTERN.test(DIGEST.toUpperCase())).toBe(false);
});
});
-21
View File
@@ -1,21 +0,0 @@
import { describe, expect, it } from "vitest";
import { emptyArraySchema } from "./emptyArraySchema.js";
describe("empty array schema", () => {
it("accepts only an empty array", () => {
expect(emptyArraySchema.parse([])).toEqual([]);
for (const value of [
[null],
["candidate"],
[0],
[false],
[{}],
[[]],
null,
{},
]) {
expect(emptyArraySchema.safeParse(value).success).toBe(false);
}
});
});
-112
View File
@@ -1,112 +0,0 @@
import type { ProcessNode, ProcessTreeEvent } from "./eventProcessTree.js";
/**
* Defaults shared by every fixture event. Tests vary only the fields they are
* actually asserting on, so a tree reads as the sequence of transitions under
* test rather than thirteen repeated literal fields per event.
*/
const eventDefaults: {
arguments: string[];
previous_pid: number | null;
previous_ppid: number | null;
exit_code: number | null;
signal: number | null;
tid: number | null;
} = {
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
};
/** One `spawn` event, numbering itself from the sequence given. */
export const spawnEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable?: string | null;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "spawn",
executable: event.executable ?? `/${event.process_name}`,
...event,
});
/** One `exit` event. */
export const exitEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number | null;
process_name: string | null;
exit_code?: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "exit",
executable: null,
exit_code: 0,
...event,
});
/** One `re_exec` event, which keeps the pid and replaces the executable. */
export const reExecEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable: string;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "re_exec",
previous_pid: null,
...event,
});
/** One `reparent` event, which records the pid the process was adopted from. */
export const reparentEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
previous_ppid: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "reparent",
executable: null,
...event,
});
/** A reconstructed node, defaulting to a childless process with no lifecycle. */
export const processNode = (node: {
pid: number;
ppid: number | null;
process_name: string;
children?: number[];
}): ProcessNode => ({
executable: null,
arguments: [],
spawn_time_ms: null,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
...node,
children: node.children ?? [],
});
/** The common `spawn` of a root process at pid 1. */
export const rootSpawn = (sequence = 0): ProcessTreeEvent =>
spawnEvent({ sequence, pid: 1, ppid: 0, process_name: "root" });
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
containsProcess,
getDescendants,
maxTreeDepth,
reconstructProcessTree,
type ProcessTreeEvent,
} from "./eventProcessTree.js";
import {
exitEvent,
processNode,
reExecEvent,
reparentEvent,
rootSpawn,
spawnEvent,
} from "./eventProcessTree.fixture.js";
describe("event-backed process tree reconstruction", () => {
it("walks trees larger than ten thousand nodes", () => {
const childPids = Array.from({ length: 10_001 }, (_, index) => index + 2);
const root = processNode({
pid: 1,
ppid: null,
process_name: "root",
children: childPids,
});
const children = childPids.map((pid) =>
processNode({ pid, ppid: 1, process_name: "root" }),
);
expect(maxTreeDepth([root, ...children], 1)).toBe(1);
expect(getDescendants([root, ...children], 1)).toHaveLength(
childPids.length,
);
});
it("reconstructs a simple process tree", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
exitEvent({
sequence: 2,
at_ms: 20,
pid: 2,
ppid: 1,
process_name: "child",
}),
exitEvent({
sequence: 3,
at_ms: 30,
pid: 1,
ppid: 0,
process_name: "root",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.processes).toHaveLength(2);
expect(result.events_consumed).toBe(4);
expect(result.events_unmatched).toBe(0);
expect(result.short_lived_descendants).toBe(2);
});
});
describe("short-lived process descendants", () => {
it("detects short-lived descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "short",
executable: "/short",
}),
exitEvent({
sequence: 2,
at_ms: 11,
pid: 2,
ppid: 1,
process_name: "short",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.short_lived_descendants).toBe(1);
});
});
describe("event-backed process tree transitions", () => {
it("detects re-exec", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
reExecEvent({
sequence: 1,
pid: 1,
ppid: 0,
process_name: "root",
executable: "/newroot",
arguments: ["--new"],
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_re_exec).toBe(true);
const root = result.processes.find((p) => p.pid === 1);
expect(root?.is_re_exec).toBe(true);
expect(root?.executable).toBe("/newroot");
});
it("detects reparenting", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
reparentEvent({
sequence: 2,
pid: 2,
ppid: 0,
process_name: "child",
previous_ppid: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_reparenting).toBe(true);
const child = result.processes.find((p) => p.pid === 2);
expect(child?.is_reparented).toBe(true);
expect(child?.previous_ppid).toBe(1);
expect(child?.ppid).toBe(0);
});
it("reports unmatched events for unknown exits", () => {
const events: ProcessTreeEvent[] = [
exitEvent({
sequence: 0,
at_ms: 0,
pid: 999,
ppid: null,
process_name: null,
exit_code: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.events_unmatched).toBe(1);
expect(result.processes).toHaveLength(0);
});
});
describe("event-backed process tree queries", () => {
it("gets descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child1",
executable: "/c1",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "grandchild",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
const descendants = getDescendants(result.processes, 1);
expect(descendants).toHaveLength(2);
expect(descendants).toContain(2);
expect(descendants).toContain(3);
});
it("checks process containment", () => {
const events: ProcessTreeEvent[] = [rootSpawn(0)];
const result = reconstructProcessTree(events, 1);
expect(containsProcess(result.processes, 1)).toBe(true);
expect(containsProcess(result.processes, 999)).toBe(false);
});
});
describe("event-backed process tree depth and types", () => {
it("computes max tree depth", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/c",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "gc",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
expect(maxTreeDepth(result.processes, 1)).toBe(2);
});
});
-262
View File
@@ -1,262 +0,0 @@
import { z } from "zod";
/** Event types for event-backed process-tree capture. */
export const processEventTypeSchema = z.enum([
"spawn",
"exit",
"re_exec",
"reparent",
"signal",
"name_change",
"thread_create",
"thread_exit",
]);
/** A single event-backed process-tree event. */
export const processTreeEventSchema = z.strictObject({
/** Monotonic event sequence number. */
sequence: z.number().int().nonnegative(),
/** Event timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Event type. */
type: processEventTypeSchema,
/** Process ID. */
pid: z.number().int().positive(),
/** Parent process ID. */
ppid: z.number().int().nullable(),
/** Process name if known. */
process_name: z.string().nullable(),
/** Executable path if known. */
executable: z.string().nullable(),
/** Command line arguments. */
arguments: z.array(z.string()).default([]),
/** Previous PID (for reparent events). */
previous_pid: z.number().int().nullable(),
/** Previous PPID (for reparent events). */
previous_ppid: z.number().int().nullable(),
/** Exit code (for exit events). */
exit_code: z.number().int().nullable(),
/** Signal number (for signal events). */
signal: z.number().int().nullable(),
/** Thread ID (for thread events). */
tid: z.number().int().nullable(),
});
export type ProcessTreeEvent = z.infer<typeof processTreeEventSchema>;
/** Process node in a reconstructed tree. */
export const processNodeSchema = z.strictObject({
pid: z.number().int().positive(),
ppid: z.number().int().nullable(),
process_name: z.string().nullable(),
executable: z.string().nullable(),
arguments: z.array(z.string()).default([]),
children: z.array(z.number().int()).default([]),
spawn_time_ms: z.number().int().nullable(),
exit_time_ms: z.number().int().nullable(),
exit_code: z.number().int().nullable(),
is_re_exec: z.boolean().default(false),
is_reparented: z.boolean().default(false),
previous_ppid: z.number().int().nullable(),
});
export type ProcessNode = z.infer<typeof processNodeSchema>;
/** Result of event-backed process-tree reconstruction. */
export const processTreeReconstructionSchema = z.strictObject({
/** Root PID of the process tree. */
root_pid: z.number().int().positive(),
/** All reconstructed process nodes. */
processes: z.array(processNodeSchema).min(0),
/** Events that were consumed. */
events_consumed: z.number().int().nonnegative(),
/** Events that could not be matched. */
events_unmatched: z.number().int().nonnegative(),
/** Short-lived descendants that were missed by sampling. */
short_lived_descendants: z.number().int().nonnegative(),
/** Whether any re-exec was detected. */
has_re_exec: z.boolean().default(false),
/** Whether any reparenting was detected. */
has_reparenting: z.boolean().default(false),
});
export type ProcessTreeReconstruction = z.infer<
typeof processTreeReconstructionSchema
>;
type ProcessTreeAccumulator = {
readonly nodes: Map<number, ProcessNode>;
readonly children: Map<number, number[]>;
eventsUnmatched: number;
hasReExec: boolean;
hasReparenting: boolean;
shortLivedDescendants: number;
};
const applyProcessTreeEvent = (
event: ProcessTreeEvent,
state: ProcessTreeAccumulator,
): void => {
let node = state.nodes.get(event.pid);
switch (event.type) {
case "spawn": {
if (!node) {
node = {
pid: event.pid,
ppid: event.ppid,
process_name: event.process_name,
executable: event.executable,
arguments: event.arguments,
children: [],
spawn_time_ms: event.at_ms,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
};
state.nodes.set(event.pid, node);
}
if (event.ppid !== null) {
const parentChildren = state.children.get(event.ppid) ?? [];
parentChildren.push(event.pid);
state.children.set(event.ppid, parentChildren);
}
break;
}
case "exit":
if (node) {
node.exit_time_ms = event.at_ms;
node.exit_code = event.exit_code;
if (
node.spawn_time_ms !== null &&
event.at_ms - node.spawn_time_ms < 100
)
state.shortLivedDescendants++;
} else state.eventsUnmatched++;
break;
case "re_exec":
if (node) {
node.is_re_exec = true;
node.executable = event.executable ?? node.executable;
node.arguments = event.arguments;
state.hasReExec = true;
} else state.eventsUnmatched++;
break;
case "reparent":
if (node) {
node.previous_ppid = node.ppid;
node.ppid = event.ppid;
node.is_reparented = true;
state.hasReparenting = true;
} else state.eventsUnmatched++;
break;
case "signal":
case "name_change":
case "thread_create":
case "thread_exit":
// These events are recorded but don't modify the tree structure.
break;
}
};
/** Reconstruct a process tree from event-backed capture. */
export function reconstructProcessTree(
events: readonly ProcessTreeEvent[],
rootPid: number,
): ProcessTreeReconstruction {
const nodes = new Map<number, ProcessNode>();
const children = new Map<number, number[]>();
let eventsConsumed = 0;
const state: ProcessTreeAccumulator = {
nodes,
children,
eventsUnmatched: 0,
hasReExec: false,
hasReparenting: false,
shortLivedDescendants: 0,
};
const sorted = [...events].sort((a, b) => a.at_ms - b.at_ms);
for (const event of sorted) {
eventsConsumed++;
applyProcessTreeEvent(event, state);
}
// Attach children to nodes
for (const [pid, childPids] of children) {
const node = nodes.get(pid);
if (node) node.children = childPids;
}
return {
root_pid: rootPid,
processes: [...nodes.values()],
events_consumed: eventsConsumed,
events_unmatched: state.eventsUnmatched,
short_lived_descendants: state.shortLivedDescendants,
has_re_exec: state.hasReExec,
has_reparenting: state.hasReparenting,
};
}
/** Get all descendant PIDs of a given root PID. */
export function getDescendants(
processes: readonly ProcessNode[],
rootPid: number,
): number[] {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const visited = new Set<number>();
const result: number[] = [];
const queue: number[] = [rootPid];
for (let head = 0; head < queue.length; head += 1) {
const pid = queue[head];
if (pid === undefined) continue;
if (visited.has(pid)) continue;
visited.add(pid);
const node = byPid.get(pid);
if (node) {
for (const child of node.children) {
if (!visited.has(child)) {
result.push(child);
queue.push(child);
}
}
}
}
return result;
}
/** Check if a process tree contains a specific PID. */
export function containsProcess(
processes: readonly ProcessNode[],
pid: number,
): boolean {
return processes.some((p) => p.pid === pid);
}
/** Get the maximum tree depth from the root. */
export function maxTreeDepth(
processes: readonly ProcessNode[],
rootPid: number,
): number {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const pending = [{ pid: rootPid, depth: 0 }];
const visited = new Set<number>();
let maximumDepth = 0;
while (pending.length > 0) {
const current = pending.pop();
if (!current || visited.has(current.pid)) continue;
visited.add(current.pid);
const node = byPid.get(current.pid);
if (!node || node.children.length === 0) continue;
const childDepth = current.depth + 1;
maximumDepth = Math.max(maximumDepth, childDepth);
for (const childPid of node.children)
if (!visited.has(childPid))
pending.push({ pid: childPid, depth: childDepth });
}
return maximumDepth;
}
+106 -1
View File
@@ -4,6 +4,7 @@ import { describe, expect } from "vitest";
import { createAnalysisProfile } from "./analysisProfile.js";
import type { BinaryTarget } from "./binaryTarget.js";
import { createEvidence, evidenceSchema, parseEvidence } from "./evidence.js";
import { MAX_JSON_DEPTH } from "./jsonValue.js";
import { createEvidenceBundle } from "./evidenceBundle.js";
const TARGET: BinaryTarget = {
@@ -17,14 +18,53 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("snapshots caller-owned payloads before deriving their identity", () => {
const result = { nested: { values: ["observed"] } };
const rawResult = { entries: [{ value: "raw" }] };
const parameters = { selected: ["target"] };
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "inspect",
parameters,
result,
rawResult,
});
result.nested.values.push("later");
const rawEntry = rawResult.entries[0];
if (rawEntry !== undefined) rawEntry.value = "changed";
parameters.selected.push("other");
expect(evidence.normalized_result).toEqual({
nested: { values: ["observed"] },
});
expect(evidence.raw_result).toEqual({ entries: [{ value: "raw" }] });
expect(evidence.parameters).toEqual({ selected: ["target"] });
expect(parseEvidence(evidence)).toEqual(evidence);
expect(() =>
parseEvidence({ ...evidence, normalized_result: result }),
).toThrow(/semantic identifier/u);
});
describe("analysis evidence identity", () => {
it("normalizes prototype-named parameter keys", () => {
it("preserves prototype-named parameter keys and their semantic identity", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: Object.fromEntries([["__proto__", false]]),
result: true,
});
expect(evidence.parameters).toEqual({ ["__proto__"]: false });
expect(Object.hasOwn(evidence.parameters, "__proto__")).toBe(true);
expect(parseEvidence(evidence)).toEqual(evidence);
const stripped = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
expect(() =>
parseEvidence({
...evidence,
parameters: { ["__proto__"]: true },
}),
).toThrow(/semantic identifier/u);
});
it.prop([
@@ -156,6 +196,23 @@ describe("analysis evidence identity", () => {
});
});
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
const reason = "Caller excluded the observed digest.";
const observation = { operation: "health", parameters: {}, result: true };
const explicit = createEvidence(undefined, PROVIDER, {
...observation,
subjectUnavailableReason: reason,
});
const defaulted = createEvidence(undefined, PROVIDER, observation);
expect(explicit.subject).toBeNull();
expect(explicit.limitations).toEqual([reason]);
expect(defaulted.limitations).toEqual([
"Artifact identity is unavailable for this observation.",
]);
expect(explicit.evidence_id).not.toBe(defaulted.evidence_id);
expect(parseEvidence(explicit)).toEqual(explicit);
});
it("derives byte-stable bundle manifests independent of record order", () => {
const artifactEvidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
@@ -213,3 +270,51 @@ describe("DOS analysis evidence identity", () => {
);
});
});
describe("evidence parameter depth bound", () => {
it("rejects evidence whose parameters nest past the JSON depth limit", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
let value: unknown = 1;
for (let index = 0; index <= MAX_JSON_DEPTH; index += 1)
value = { nested: value };
const result = evidenceSchema.safeParse({
...evidence,
parameters: { attack: value },
});
expect(result.success).toBe(false);
if (result.success) return;
expect(
result.error.issues.some((issue) =>
issue.message.includes("maximum nesting depth"),
),
).toBe(true);
});
});
it("preserves prototype-named raw and normalized results with aligned identity", () => {
const result = { ["__proto__"]: { preserved: 7 }, constructor: "ordinary" };
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result,
rawResult: result,
});
const parsed = parseEvidence(evidence);
expect(parsed.normalized_result).toEqual(result);
expect(parsed.raw_result).toEqual(result);
expect(Object.getPrototypeOf(parsed.normalized_result)).toBe(
Object.prototype,
);
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
const stripped = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: { constructor: "ordinary" },
rawResult: { constructor: "ordinary" },
});
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
});
+26 -7
View File
@@ -7,7 +7,11 @@ import {
type AnalysisProfileCommitment,
} from "./analysisProfile.js";
import type { BinaryTarget } from "./binaryTarget.js";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import {
jsonObjectSchema,
jsonValueSchema,
type JsonValue,
} from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
@@ -89,7 +93,7 @@ const evidenceBaseSchema = z
provider: providerSchema,
predicate_type: z.string().min(1),
operation: z.string().min(1),
parameters: z.record(z.string(), jsonValueSchema),
parameters: jsonObjectSchema,
raw_result: jsonValueSchema.nullable(),
normalized_result: jsonValueSchema,
confidence: z.enum(["observed", "derived", "inferred"]),
@@ -169,6 +173,8 @@ export interface EvidenceObservation {
readonly authority?: EvidenceAuthority;
readonly environment?: ExecutionEnvironment | null;
readonly limitations?: readonly string[];
/** Reason the subject identity is unavailable, when no target identity is supplied. */
readonly subjectUnavailableReason?: string;
readonly locations?: readonly EvidenceLocation[];
readonly evidenceLinks?: readonly string[];
}
@@ -229,7 +235,7 @@ export const createEvidence = (
target === undefined
? null
: {
name: target.path.split("/").at(-1) ?? target.path,
name: target.path.split("/").at(-1) || "artifact",
digest: { sha256: target.sha256 },
format: target.format,
architecture: target.architecture ?? null,
@@ -262,20 +268,33 @@ export const createEvidence = (
environment: observation.environment ?? null,
limitations: [
...(target === undefined
? ["Artifact identity is unavailable for this observation."]
? [
observation.subjectUnavailableReason ??
"Artifact identity is unavailable for this observation.",
]
: []),
...(observation.limitations ?? []),
],
locations: [...(observation.locations ?? [])],
evidence_links: [...(observation.evidenceLinks ?? [])],
} satisfies JsonValue;
const normalized = evidenceRecordSchema.parse({
// Select the known envelope before parsing. A union otherwise traverses and
// clones a legacy result for the profiled branch before rejecting its absent
// profile and trying the legacy branch.
const schema =
observation.analysisProfile === undefined
? evidenceBaseSchema
: profiledEvidenceSchema;
const normalized = schema.parse({
...semantic,
evidence_id: `ev_${"0".repeat(64)}`,
subject,
});
return parseEvidence({
// The envelope has already been parsed into an independent snapshot. Only
// its derived identifier changes here; parsing again clones the full payload
// and recomputes the same digest while the previous snapshot is still live.
return {
...normalized,
evidence_id: computeEvidenceId(normalized),
});
};
};
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "./evidence.js";
import {
createEvidenceBundle,
evidenceBundleForTarget,
parseEvidenceBundle,
} from "./evidenceBundle.js";
import {
createResidualUnknown,
recordUnknownInputSchema,
} from "./residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
const targetDigest = "a".repeat(64);
const foreignDigest = "b".repeat(64);
const makeUnknown = (
question: string,
scopeDigest: string,
dependency?: string,
) => {
const input = recordUnknownInputSchema.parse({
question,
severity: "medium",
domain: "bundle-projection",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships:
dependency === undefined
? []
: [{ type: "depends-on", unknown_id: dependency }],
});
const mutation = createEvidence(undefined, provider, {
predicateType: "rea.residual-unknown-mutation",
operation: "record_unknown",
parameters: { domain: input.domain, severity: input.severity },
result: {
action: "record",
question: input.question,
required_authority: input.required_authority,
required_confidence: input.required_confidence,
},
});
return {
evidence: mutation,
unknown: createResidualUnknown(input, mutation.evidence_id, scopeDigest),
};
};
describe("evidenceBundleForTarget", () => {
it("removes dependent unknowns when their foreign-scope root is excluded", () => {
const foreignRoot = makeUnknown("Foreign root", foreignDigest);
const child = makeUnknown(
"Target child",
targetDigest,
foreignRoot.unknown.unknown_id,
);
const grandchild = makeUnknown(
"Target grandchild",
targetDigest,
child.unknown.unknown_id,
);
const retained = makeUnknown("Independent target", targetDigest);
const bundle = createEvidenceBundle(
[
foreignRoot.evidence,
child.evidence,
grandchild.evidence,
retained.evidence,
],
[
foreignRoot.unknown,
child.unknown,
grandchild.unknown,
retained.unknown,
],
);
expect(evidenceBundleForTarget(bundle, targetDigest)).toEqual(
createEvidenceBundle([retained.evidence], [retained.unknown]),
);
});
it("projects a valid graph with more than 125,000 dependents", () => {
const foreignRoot = makeUnknown("Foreign high-fan-out root", foreignDigest);
const middle = makeUnknown(
"Target middle depending on foreign root",
targetDigest,
foreignRoot.unknown.unknown_id,
);
const unknowns = [foreignRoot.unknown, middle.unknown];
for (let index = 0; index < 125_000; index += 1) {
const input = recordUnknownInputSchema.parse({
question: `Target child ${index}`,
severity: "medium",
domain: "bundle-projection",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [
{ type: "depends-on", unknown_id: middle.unknown.unknown_id },
],
});
unknowns.push(
createResidualUnknown(input, middle.evidence.evidence_id, targetDigest),
);
}
const bundle = parseEvidenceBundle(
createEvidenceBundle([foreignRoot.evidence, middle.evidence], unknowns),
);
expect(evidenceBundleForTarget(bundle, targetDigest)).toEqual(
createEvidenceBundle([], []),
);
});
});
+136 -41
View File
@@ -111,28 +111,57 @@ export const evidenceBundleForTarget = (
const recordsById = new Map(
bundle.records.map((record) => [record.evidence_id, record]),
);
let unknowns = bundle.unknowns.filter(
const candidates = bundle.unknowns.filter(
({ scope_digest: scopeDigest }) => scopeDigest === sha256,
);
let changed = true;
while (changed) {
const ids = new Set(unknowns.map(({ unknown_id: id }) => id));
const retained = unknowns.filter(
(unknown) =>
unknown.relationships.every(({ unknown_id: id }) => ids.has(id)) &&
referencedEvidenceIds(unknown).every((id) => {
const record = recordsById.get(id);
return (
record?.subject?.digest.sha256 === sha256 ||
(unknown.mutation_evidence_ids.includes(id) &&
record?.subject === null &&
record.predicate_type === "rea.residual-unknown-mutation")
);
}),
const retained = new Set<ResidualUnknown>();
const revisionsById = new Map<string, number>();
const dependents = new Map<string, Set<ResidualUnknown>>();
for (const unknown of candidates) {
const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids);
const evidenceAvailable = referencedEvidenceIds(unknown).every((id) => {
const record = recordsById.get(id);
return (
record?.subject?.digest.sha256 === sha256 ||
(mutationEvidenceIds.has(id) &&
record?.subject === null &&
record.predicate_type === "rea.residual-unknown-mutation")
);
});
if (!evidenceAvailable) continue;
retained.add(unknown);
revisionsById.set(
unknown.unknown_id,
(revisionsById.get(unknown.unknown_id) ?? 0) + 1,
);
changed = retained.length !== unknowns.length;
unknowns = retained;
for (const relatedId of new Set(
unknown.relationships.map(({ unknown_id: id }) => id),
)) {
const references =
dependents.get(relatedId) ?? new Set<ResidualUnknown>();
references.add(unknown);
dependents.set(relatedId, references);
}
}
const pending: ResidualUnknown[] = [];
for (const unknown of retained)
if (
unknown.relationships.some(({ unknown_id: id }) => !revisionsById.has(id))
)
pending.push(unknown);
for (let index = 0; index < pending.length; index += 1) {
const unknown = pending[index];
if (unknown === undefined || !retained.delete(unknown)) continue;
const remaining = (revisionsById.get(unknown.unknown_id) ?? 1) - 1;
if (remaining > 0) {
revisionsById.set(unknown.unknown_id, remaining);
continue;
}
revisionsById.delete(unknown.unknown_id);
for (const dependent of dependents.get(unknown.unknown_id) ?? [])
pending.push(dependent);
}
const unknowns = candidates.filter((unknown) => retained.has(unknown));
const mutationIds = new Set(
unknowns.flatMap(({ mutation_evidence_ids: ids }) => ids),
);
@@ -153,6 +182,34 @@ const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
...(unknown.resolution?.evidence_ids ?? []),
];
/**
* Name the bundle constraint that failed and how to recover. A single
* Evidence record, such as one command result, is not a bundle.
*/
export const describeEvidenceBundleFailure = (
input: unknown,
cause: unknown,
): string => {
const record = evidenceRecordSchema.safeParse(input);
if (record.success)
return `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${record.data.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`;
return cause instanceof z.ZodError
? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
: `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`;
};
/** Locate the first schema issue, or keep a thrown constraint message. */
export const describeValidationFailure = (cause: unknown): string => {
if (!(cause instanceof z.ZodError))
return cause instanceof Error ? cause.message : String(cause);
const [first, ...rest] = cause.issues;
const location =
first === undefined || first.path.length === 0
? "the document root"
: first.path.map(String).join(".");
return `at ${location}: ${first?.message ?? "invalid value"}${rest.length === 0 ? "" : ` (${String(rest.length)} more issues)`}`;
};
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
const parsed = evidenceBundleSchema.parse(input);
@@ -285,26 +342,28 @@ export const validateResidualUnknownAddition = (
);
if (unknown.resolution?.disposition === "verified")
validateVerifiedResolution(unknown, evidenceById);
for (const relationship of unknown.relationships)
// In a valid graph, no existing node can point to an absent ID. Since the
// schema rejects self-relations, a new node's outgoing edges cannot close a
// cycle; keep graph traversal for revisions of existing nodes only.
if (current !== undefined) {
const dependencies = unknown.relationships
.filter((relationship) => relationship.type === "depends-on")
.map(({ unknown_id }) => unknown_id);
if (
relationship.type === "depends-on" &&
reachesUnknown(
relationship.unknown_id,
unknown.unknown_id,
currentHeads,
unknown,
)
dependencies.length > 0 &&
reachesUnknown(dependencies, unknown.unknown_id, currentHeads, unknown)
)
throw new TypeError("Residual unknown dependency graph contains a cycle");
}
};
const reachesUnknown = (
start: string,
starts: readonly string[],
goal: string,
currentHeads: ReadonlyMap<string, ResidualUnknown>,
candidate: ResidualUnknown,
): boolean => {
const pending = [start];
const pending = [...starts];
const visited = new Set<string>();
while (pending.length > 0) {
const id = pending.pop();
@@ -356,20 +415,56 @@ const rejectDependencyCycles = (
): void => {
const visited = new Set<string>();
const active = new Set<string>();
const visit = (id: string): void => {
if (active.has(id))
throw new TypeError("Residual unknown dependency graph contains a cycle");
if (visited.has(id)) return;
active.add(id);
const unknown = unknownById.get(id);
if (unknown === undefined)
const pending: {
readonly id: string;
readonly relationships: ResidualUnknown["relationships"];
nextRelationship: number;
}[] = [];
for (const root of unknownById.keys()) {
if (visited.has(root)) continue;
const rootUnknown = unknownById.get(root);
if (rootUnknown === undefined)
throw new TypeError("Residual unknown dependency graph is inconsistent");
for (const relationship of unknown.relationships)
if (relationship.type === "depends-on") visit(relationship.unknown_id);
active.delete(id);
visited.add(id);
};
for (const id of unknownById.keys()) visit(id);
active.add(root);
pending.push({
id: root,
relationships: rootUnknown.relationships,
nextRelationship: 0,
});
while (pending.length > 0) {
const frame = pending[pending.length - 1];
if (frame === undefined) break;
let descended = false;
while (frame.nextRelationship < frame.relationships.length) {
const relationship = frame.relationships[frame.nextRelationship];
frame.nextRelationship += 1;
if (relationship?.type !== "depends-on") continue;
const dependency = relationship.unknown_id;
if (active.has(dependency))
throw new TypeError(
"Residual unknown dependency graph contains a cycle",
);
if (visited.has(dependency)) continue;
const unknown = unknownById.get(dependency);
if (unknown === undefined)
throw new TypeError(
"Residual unknown dependency graph is inconsistent",
);
active.add(dependency);
pending.push({
id: dependency,
relationships: unknown.relationships,
nextRelationship: 0,
});
descended = true;
break;
}
if (descended) continue;
pending.pop();
active.delete(frame.id);
visited.add(frame.id);
}
}
};
/** Encode a validated bundle as byte-stable RFC 8785 canonical JSON. */
+19 -3
View File
@@ -1,8 +1,20 @@
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** Evidence identity, schema, or bundle manifests failed integrity checks. */
export class EvidenceIntegrityError extends AnalysisError {
readonly _tag = "EvidenceIntegrityError";
override readonly userMessage: string | undefined;
constructor(
message: string,
options?: AnalysisErrorOptions & { readonly userMessage?: string },
) {
super(message, options);
this.userMessage = options?.userMessage;
}
}
/** A session Evidence reference is missing or has the wrong semantic identity. */
@@ -25,11 +37,15 @@ export class EvidenceReferenceError extends EvidenceIntegrityError {
export class EvidenceFileError extends AnalysisError {
readonly _tag = "EvidenceFileError";
/** Caller-selected path that failed, resolved against the working directory. */
readonly path: string | undefined;
constructor(
readonly operation: "read" | "write",
readonly reason: "not-file" | "exists" | "invalid-json" | "io",
options?: ErrorOptions,
readonly reason: "not-file" | "exists" | "invalid-json" | "missing" | "io",
options?: ErrorOptions & { readonly path?: string },
) {
super(`Evidence bundle ${operation} failed: ${reason}`, options);
this.path = options?.path;
}
}
+36
View File
@@ -0,0 +1,36 @@
import { expect, it } from "vitest";
import { evmInterfaceSchema } from "./evmInterface.js";
import { evmInterfaceFixture } from "../../../tests/fixtures/evm/interface.js";
it("preserves original carrier and decoded byte identity as distinct observations", () => {
const fixture = evmInterfaceFixture();
expect(evmInterfaceSchema.parse(fixture)).toEqual(fixture);
expect(fixture.artifact.sha256).not.toBe(fixture.bytecode.sha256);
});
it.each(["byte-count", "body-offset", "selector", "authenticity"])(
"rejects false interface evidence: %s",
(problem) => {
const value = evmInterfaceFixture();
const raw = {
...value,
...(problem === "authenticity"
? {
bytecode: {
...value.bytecode,
deployment_authenticity: "verified",
},
}
: {}),
};
if (problem === "byte-count") raw.bytecode.bytes++;
if (problem === "body-offset" || problem === "selector")
raw.functions.push({
selector: problem === "selector" ? "bad" : "0xaabbccdd",
bytecode_offset: problem === "body-offset" ? 5 : 0,
dispatch: "abi",
inferred_arguments: null,
inferred_state_mutability: null,
});
expect(evmInterfaceSchema.safeParse(raw).success).toBe(false);
},
);
+76
View File
@@ -0,0 +1,76 @@
import { z } from "zod";
const byteOffset = z.number().int().nonnegative();
const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
/** Select the carrier representation explicitly; no RPC or deployed-contract lookup is implied. */
export const inspectEvmInterfaceInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute path to caller-selected local bytecode carrier"),
encoding: z
.enum(["raw", "hex"])
.describe(
"Raw bytes or UTF-8 hex with optional 0x prefix and outer ASCII whitespace",
),
});
/** Recovered interface candidates are inferences, independently of observed byte identity. */
export const evmInterfaceSchema = z
.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256,
bytes: byteOffset,
encoding: z.enum(["raw", "hex"]),
}),
bytecode: z.strictObject({
sha256,
bytes: byteOffset,
hex: z.string().regex(/^(?:[0-9a-f]{2})*$/),
digest_algorithm: z.literal("sha256"),
kind: z.literal("unknown"),
deployment_authenticity: z.literal("unknown"),
hardfork: z.literal("unknown"),
}),
evidence_kind: z.literal("inferred"),
functions: z.array(
z.strictObject({
selector: z.string().regex(/^0x[0-9a-f]{8}$/),
bytecode_offset: byteOffset,
dispatch: z.enum(["abi", "fallback"]),
inferred_arguments: z.string().nullable(),
inferred_state_mutability: z.string().nullable(),
}),
),
discovery_completeness: z.literal("unknown"),
runtime_execution: z.literal("not-performed"),
diagnostics: z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
}),
limitations: z.array(z.string()),
})
.superRefine((value, context) => {
if (value.bytecode.hex.length !== value.bytecode.bytes * 2)
context.addIssue({
code: "custom",
path: ["bytecode"],
message:
"Selected byte count does not match the bytecode hex representation.",
});
for (const [index, fn] of value.functions.entries())
if (fn.bytecode_offset >= value.bytecode.bytes)
context.addIssue({
code: "custom",
path: ["functions", index, "bytecode_offset"],
message: "Inferred body offset lies outside the selected bytecode.",
});
});
export type InspectEvmInterfaceInput = z.infer<
typeof inspectEvmInterfaceInputSchema
>;
export type EvmInterface = z.infer<typeof evmInterfaceSchema>;
+126
View File
@@ -0,0 +1,126 @@
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
import { expect, it } from "vitest";
import {
AnalysisInputError,
AnalysisCapabilityUnavailableError,
} from "./analysisErrorCore.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
import {
redactExplicitFailure,
redactExplicitPointer,
} from "./explicitSensitiveFailure.js";
it.each([
["/metadata/private~1~0/numeric", ["private/~"], "/metadata"],
["/metadata/private/child", ["private"], "/metadata"],
["/ordinary/path", [], "/ordinary/path"],
])(
"preserves a real parent for excluded pointer identities: %s",
(pointer, values, expected) => {
expect(redactExplicitPointer(pointer, values)).toBe(expected);
},
);
it("preserves cleanup failure authority and resources while excluding diagnostics", () => {
const error = new ProviderCleanupError(
"har",
["/root/private/capture", "pid:123"],
{
capture_path: "/root/private/capture",
nested: { "private-key": 5, ordinary: "private ordinary" },
exit_code: 2,
},
{ operation: "inspect_web_network_capture" },
);
const projected = projectAnalysisError(
redactExplicitFailure(error, ["private", "REDACTED"]),
);
expect(projected.code).toBe("cleanup_incomplete");
expect(JSON.stringify(projected)).not.toContain("private");
expect(JSON.stringify(projected)).not.toContain("REDACTED");
expect(JSON.stringify(projected)).toContain("pid:123");
expect(JSON.stringify(projected)).toContain('"exit_code":2');
});
it("keeps unsupported profile reasons distinct from malformed input", () => {
const error = new AnalysisCapabilityUnavailableError(
"mitmproxy",
"inspect_web_network_capture",
"Unsupported private profile",
{ userMessage: "Select private-compatible profile" },
);
const result = redactExplicitFailure(error, ["private"]);
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
expect(projectAnalysisError(result).code).toBe("capability_unavailable");
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("coarsens format issue pointers without creating replacement coordinates", () => {
const error = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[
{
path: ["capture_path", "/metadata/private~1~0/nested"],
reason: "invalid_format",
message: "Malformed private field",
},
],
);
const result = redactExplicitFailure(error, ["private/~", "private"]);
expect(result).toBeInstanceOf(AnalysisInputError);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual(["capture_path", "/metadata"]);
});
it("excludes a marked permission-denied path without losing its host error code", () => {
const error = redactExplicitFailure(
new AnalysisAccessDeniedError(
"inspect_web_network_capture",
"/declared-path-value/capture.har",
"EACCES",
),
["declared-path-value"],
);
expect(error._tag).toBe("AnalysisAccessDeniedError");
const projected = projectAnalysisError(error);
expect(projected).toMatchObject({
code: "access_denied",
category: "unavailable",
details: { system_code: "EACCES" },
});
expect(JSON.stringify(projected)).not.toContain("declared-path-value");
});
it("coarsens ordinary sensitive issue-path segments to their real parent", () => {
const input = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[
{
path: ["input", "mysecret", "child"],
reason: "unknown_argument",
message: "Unrecognized mysecret",
},
],
);
const result = redactExplicitFailure(input, ["secret"]);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual(["input"]);
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("secret");
});
it("does not reinterpret an unknown argument name as a JSON pointer", () => {
const input = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[{ path: ["/ordinary/secret"], reason: "unknown_argument" }],
);
const result = redactExplicitFailure(input, ["secret"]);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual([]);
});
+136
View File
@@ -0,0 +1,136 @@
import type { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCapabilityUnavailableError,
} from "./analysisErrorCore.js";
import { redactExplicitText } from "./explicitSensitiveValues.js";
import type { JsonValue } from "./jsonValue.js";
import { ProviderAdapterError } from "./providerAdapterError.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
/** Keep a real JSON-pointer ancestor when a property identity is explicitly excluded. */
export const redactExplicitPointer = (
pointer: string,
values: readonly string[],
): string => {
let parent = "";
for (const segment of pointer.split("/").slice(1)) {
const decoded = segment.replaceAll("~1", "/").replaceAll("~0", "~");
const child = `${parent}/${segment}`;
if (
values.some(
(literal) => decoded.includes(literal) || child.includes(literal),
)
)
return parent;
parent = child;
}
return parent;
};
/** Exclude explicit literals from common acquisition/decoder failures, preserving typed diagnostics. */
export const redactExplicitFailure = (
error: AnalysisError,
values: readonly string[],
): AnalysisError => {
if (values.length === 0) return error;
const text = (value: string): string => redactExplicitText(value, values);
const path = (
parts: readonly (string | number)[],
ordinaryNames: boolean,
): (string | number)[] => {
const retained: (string | number)[] = [];
for (const part of parts) {
if (typeof part !== "string") {
retained.push(part);
} else if (!ordinaryNames && part.startsWith("/")) {
const pointer = redactExplicitPointer(part, values);
retained.push(pointer);
if (pointer !== part) break;
} else {
if (values.some((literal) => part.includes(literal))) break;
retained.push(part);
}
}
return retained;
};
const diagnostics = (
value: Readonly<Record<string, JsonValue>>,
): Record<string, JsonValue> =>
Object.fromEntries(
Object.entries(value)
.filter(([key]) => !values.some((literal) => key.includes(literal)))
.map(([key, item]) => [key, visit(item)]),
);
const visit = (value: JsonValue): JsonValue => {
if (typeof value === "string") return text(value);
if (Array.isArray(value)) return value.map(visit);
if (typeof value === "object" && value !== null) return diagnostics(value);
return value;
};
if (error instanceof AnalysisAccessDeniedError)
return new AnalysisAccessDeniedError(
error.operation,
text(error.path),
error.systemCode,
{ cause: error },
);
if (error instanceof AnalysisArtifactChangedError)
return new AnalysisArtifactChangedError(
error.operation,
text(error.path),
text(error.reason),
{ cause: error },
);
if (error instanceof AnalysisInputError)
return new AnalysisInputError(
error.operation,
{ cause: error },
error.issues.map((issue) => ({
...issue,
// Unknown-argument paths contain literal field names, including names
// beginning with '/'; they are not producer JSON-pointer coordinates.
path: path(issue.path, issue.reason === "unknown_argument"),
...(issue.message === undefined
? {}
: { message: text(issue.message) }),
...(issue.expected === undefined
? {}
: { expected: visit(issue.expected) }),
})),
);
if (error instanceof AnalysisOutputError)
return new AnalysisOutputError(error.operation, text(error.reason), {
cause: error,
});
if (error instanceof AnalysisCapabilityUnavailableError)
return new AnalysisCapabilityUnavailableError(
error.providerId,
error.operation,
text(error.reason),
{
cause: error,
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
},
);
if (error instanceof ProviderCleanupError)
return new ProviderCleanupError(
error.providerId,
error.cleanupResources.map(text),
diagnostics(error.diagnostics ?? {}),
{ 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 error;
};
@@ -0,0 +1,22 @@
import { expect, it } from "vitest";
import { redactExplicitText } from "./explicitSensitiveValues.js";
it.each([
["secret context", ["secret"]],
["secret context", ["secret", "REDACTED"]],
["secret context", ["secret", "[", "…"]],
["secretable context", ["secret", "able", "table"]],
["secretsecret context", ["secret", "…", "REDACTED"]],
] as const)(
"keeps declared literals out of replacement text: %s",
(input, values) => {
const result = redactExplicitText(input, values);
for (const value of values) expect(result).not.toContain(value);
},
);
it("does not guess sensitivity or treat empty declarations as matches", () => {
expect(redactExplicitText("API_SECRET ordinary evidence", [""])).toBe(
"API_SECRET ordinary evidence",
);
});
+20
View File
@@ -0,0 +1,20 @@
/** Replace caller-declared literal text values without guessing sensitivity from names. */
export const redactExplicitText = (
value: string,
sensitiveValues: readonly string[],
): string => {
const literals = [...new Set(sensitiveValues)].filter(
(literal) => literal !== "",
);
const replacement =
["[REDACTED]", "…", ""].find((candidate) =>
literals.every((literal) => !candidate.includes(literal)),
) ?? "";
let result = value;
for (const literal of literals.sort(
(left, right) => right.length - left.length,
))
result = result.replaceAll(literal, replacement);
// Replacement boundaries can form another declaration; exclude that text.
return literals.some((literal) => result.includes(literal)) ? "" : result;
};
+11 -1
View File
@@ -1,11 +1,21 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { jsonValueSchema } from "../jsonValue.js";
import { isAbsoluteLocalPath } from "../localPath.js";
const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const range = z.strictObject({ offset: bytes, length: bytes.positive() });
const target = {
path: z.string().min(1).describe("Local firmware file; never executed"),
path: z
.string()
.min(1)
.refine(isAbsoluteLocalPath, {
message:
"path must be an absolute local filesystem path (for example /tmp/firmware.bin or C:\\firmware\\firmware.bin)",
})
.describe(
"Absolute local firmware file; never executed. Relative paths are rejected.",
),
};
/** Explicit firmware inspection and extraction intent, independent of engines. */
+106
View File
@@ -246,6 +246,112 @@ describe("function collection collation ties", () => {
});
});
describe("function comparison ordering controls", () => {
const composed = { address: "0x2000", name: "caf\u00e9" };
const decomposed = { address: "0x3000", name: "cafe\u0301" };
it("preserves duplicate Unicode collections and nullable endpoints", () => {
const controlled = (base: "0x1000" | "0x2000", reverse: boolean) => {
const endpoint = base === "0x1000" ? "0x1010" : "0x2010";
const edges = [
{
source_address: base,
target_address: endpoint,
source_procedure: null,
target_procedure: { address: endpoint, name: "caf\u00e9" },
kind: {
available: true,
provenance: "provider-reference-manager",
type: "UNCONDITIONAL_CALL",
flow: true,
call: true,
jump: false,
data: false,
read: false,
write: false,
indirect: false,
computed: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 0,
external: false,
},
},
{
source_address: base,
target_address: endpoint,
source_procedure: { address: base, name: "dispatch" },
target_procedure: null,
kind: {
available: true,
provenance: "provider-reference-manager",
type: "READ",
flow: false,
call: false,
jump: false,
data: true,
read: true,
write: false,
indirect: false,
computed: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 1,
external: false,
},
},
];
const strings = [
{ address: endpoint, source_address: base, value: "caf\u00e9" },
{ address: endpoint, source_address: base, value: "cafe\u0301" },
{ address: endpoint, source_address: base, value: "cafe\u0301" },
];
return functionDossierSchema.parse({
...dossier("return 0;", base),
callees: [composed, decomposed, composed],
incoming_references: reverse ? [...edges].reverse() : edges,
outgoing_references: reverse ? [...edges].reverse() : edges,
referenced_strings: reverse ? [...strings].reverse() : strings,
referenced_names: reverse ? [...strings].reverse() : strings,
});
};
const makeEvidence = (digit: string, result: unknown): Evidence =>
createEvidence(
{
path: `/tmp/function-${digit}`,
sha256: digit.repeat(64),
format: "mach-o",
},
{ id: "rea-workflow", name: "REA workflow", version: "1" },
{
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: "dispatch",
}),
result: jsonValueSchema.parse(result),
confidence: "derived",
authority: "shipped-artifact",
},
);
const left = controlled("0x1000", false);
const right = controlled("0x2000", true);
const { native_api: _nativeApi, ...rightWithoutNativeApi } = right;
const comparison = compareFunctions(
makeEvidence("d", left),
makeEvidence("e", rightWithoutNativeApi),
);
expect(comparison.status).toBe("unchanged");
for (const dimension of ["calls", "references", "strings_names"] as const)
expect(
comparison.dimensions.find((item) => item.dimension === dimension),
).toMatchObject({ status: "unchanged" });
});
});
describe("function comparison CFG address normalization", () => {
it("matches CFG successors by numeric address", () => {
const make = (base: "0x1000" | "0x2000") =>
+13 -9
View File
@@ -177,15 +177,19 @@ export const stringAndNameProjection = (
};
export const sorted = (values: readonly unknown[]): readonly unknown[] =>
[...values].sort((left, right) => {
const leftJson = canonicalJson(left, "Function normalization");
const rightJson = canonicalJson(right, "Function normalization");
// Preserve existing collation while ordering distinct values within a tie.
return (
leftJson.localeCompare(rightJson) ||
compareCodePoints(leftJson, rightJson)
);
});
values
.map((value) => ({
value,
json: canonicalJson(value, "Function normalization"),
}))
.sort((left, right) => {
// Preserve existing collation while ordering distinct values within a tie.
return (
left.json.localeCompare(right.json) ||
compareCodePoints(left.json, right.json)
);
})
.map(({ value }) => value);
export const combineCoverage = <Item>(
left: FunctionCollection<Item>,
+37
View File
@@ -2,8 +2,45 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { projectInputIssues } from "./inputIssueProjection.js";
import { processScenarioSchema } from "./process/processScenario.js";
describe("input issue projection", () => {
it("preserves static regex guidance without echoing the rejected value", () => {
const schema = z.object({
value: z.string().regex(/^[^\0]*$/u, "Values cannot contain NUL"),
});
const input = { value: "private\0value" };
const parsed = schema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["value"],
reason: "invalid_format",
expected: "regex",
message: "Values cannot contain NUL",
},
]);
});
it("projects reserved process environment key constraints at the key path", () => {
const input = {
executable: "/usr/bin/true",
environment: { REA_PROCESS_RUN_ID: "caller-value" },
};
const parsed = processScenarioSchema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["environment", "REA_PROCESS_RUN_ID"],
reason: "invalid_format",
expected: "regex",
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
},
]);
});
it("preserves schema-authored custom correction guidance", () => {
const schema = z
.object({ left: z.string().optional(), right: z.string().optional() })
+17 -1
View File
@@ -27,6 +27,13 @@ const projectIssue = (
),
),
);
if (issue.code === "invalid_key")
return issue.issues.flatMap((keyIssue) =>
projectIssue(
{ ...keyIssue, path: [...issue.path, ...keyIssue.path] },
input,
),
);
if (issue.code === "unrecognized_keys")
return issue.keys.map((key) => ({
path: [...path, key],
@@ -48,7 +55,16 @@ const projectIssue = (
if (issue.code === "too_big")
return [boundedIssue(path, "maximum", numericBound(issue.maximum))];
if (issue.code === "invalid_format")
return [{ path, reason: "invalid_format", expected: issue.format }];
return [
{
path,
reason: "invalid_format",
expected: issue.format,
...(issue.format === "regex" && issue.message.length > 0
? { message: issue.message }
: {}),
},
];
if (issue.code === "invalid_value")
return [
{
@@ -1,6 +1,11 @@
import { z } from "zod";
const pathInputSchema = z.string().trim().min(1);
import { isAbsoluteLocalPath } from "../localPath.js";
const pathInputSchema = z.string().trim().min(1).refine(isAbsoluteLocalPath, {
message:
"Electron executable, application, and root paths must be absolute local filesystem paths (for example /Applications/Electron.app/Contents/MacOS/Electron)",
});
const absolutePathSchema = z
.string()
.min(1)
@@ -60,9 +65,17 @@ const actionSchema = z.discriminatedUnion("kind", [
/** Input for one explicit, provider-owned Electron runtime experiment. */
export const electronActiveObservationInputSchema = z.strictObject({
executable_path: pathInputSchema,
application_path: pathInputSchema,
application_root: pathInputSchema.optional(),
executable_path: pathInputSchema.describe(
"Absolute local filesystem path for the Electron executable; relative paths are rejected.",
),
application_path: pathInputSchema.describe(
"Absolute local filesystem path for the Electron application; relative paths are rejected.",
),
application_root: pathInputSchema
.optional()
.describe(
"Absolute local filesystem root for application-relative paths; omit to derive it from the application path. Relative paths are rejected.",
),
args: z.array(z.string()).default([]),
actions: z.array(actionSchema).default([]),
});
@@ -2,156 +2,46 @@ import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
describe.each(["webPreferences", "serviceName"] as const)(
"Electron %s option lookup",
(name) => {
const value =
name === "webPreferences"
? '{ preload: "./kept.js", sandbox: true }'
: '"kept"';
const explicit = `${name}: ${value}`;
const method = `${name}() { return ${value}; }`;
const getter = `get ${name}() { return ${value}; }`;
const setter = `set ${name}(value) {}`;
describe("Electron option evidence", () => {
it("keeps the final explicit preload and service name with unrelated keys", () => {
const analysis = analyzeJavaScriptStaticSource(`
new BrowserWindow({ webPreferences: { preload: "./kept.js", sandbox: true }, title: "App" });
utilityProcess.fork("./worker.js", [], { serviceName: "kept", cwd: "/app" });
`);
const explicitCases = [
["plain key", explicit],
["quoted key", `"${name}": ${value}`],
["computed string key", `["${name}"]: ${value}`],
["duplicate key", `${name}: null, ${explicit}`],
["computed duplicate key", `${name}: null, ["${name}"]: ${value}`],
["earlier spread", `...options, ${explicit}`],
["earlier computed identifier", `[key]: null, ${explicit}`],
["earlier computed expression", `[getKey()]: null, ${explicit}`],
["earlier getter", `${getter}, ${explicit}`],
["earlier method", `${method}, ${explicit}`],
["unrelated later key", `${explicit}, title: "title"`],
["unrelated computed literal", `${explicit}, ["title"]: null`],
["unrelated numeric key", `${explicit}, [1]: null`],
["unrelated empty key", `${explicit}, [""]: null`],
["unrelated getter", `${explicit}, get title() { return "title"; }`],
];
it.each(explicitCases)(
"retains the explicit value with %s",
(_, members) => {
const analysis = analyzeOption(name, `{ ${members} }`);
expect(analysis.parse_status).toBe("complete");
if (name === "webPreferences") {
expect(analysis.electron.browser_windows).toEqual([
expect.objectContaining({
options_status: "object-literal",
web_preferences_status: "object-literal",
preload_path: "./kept.js",
preload_resolution_context: "module-specifier",
web_preferences: [
{ name: "preload", value: literal("./kept.js") },
{ name: "sandbox", value: literal(true) },
],
}),
]);
} else {
expect(analysis.electron.utility_processes).toEqual([
expect.objectContaining({ service_name: "kept" }),
]);
}
},
);
const dynamicCases = [
["same-spelled computed binding", `[${name}]: ${value}`],
["different computed binding", `[key]: ${value}`],
["computed expression", `[getKey()]: ${value}`],
["unevaluated template key", `[\`${name}\`]: ${value}`],
["spread only", "...options"],
["later spread", `${explicit}, ...options`],
["later computed binding", `${explicit}, [key]: null`],
["later computed expression", `${explicit}, [getKey()]: null`],
["exact getter", getter],
["exact setter", setter],
["exact method", method],
["computed string method", `["${name}"]() { return ${value}; }`],
["overriding getter", `${explicit}, ${getter}`],
["overriding setter", `${explicit}, ${setter}`],
["overriding method", `${explicit}, ${method}`],
["dynamic explicit value", `${name}: dynamicValue`],
["null explicit value", `${name}: null`],
["duplicate null value", `${explicit}, ${name}: null`],
];
it.each(dynamicCases)("preserves uncertainty for %s", (_, members) => {
expectUnknownOption(name, `{ ${members} }`, "object-literal");
});
it.each(["null", "options"])(
"preserves nonliteral options %s",
(options) => {
expectUnknownOption(name, options, "dynamic");
},
);
it.each(["", "{}", '{ title: "title", ["other"]: null }'])(
"reports an omitted option in %s without inventing a default",
(options) => {
const analysis = analyzeOption(name, options);
expect(analysis.parse_status).toBe("complete");
if (name === "webPreferences")
expect(analysis.electron.browser_windows[0]).toMatchObject({
options_status: options === "" ? "missing" : "object-literal",
web_preferences_status: "missing",
web_preferences: [],
preload_path: null,
preload_resolution_context: null,
});
else
expect(
analysis.electron.utility_processes[0]?.service_name,
).toBeNull();
},
);
},
);
type OptionName = "webPreferences" | "serviceName";
const analyzeOption = (name: OptionName, options: string) =>
analyzeJavaScriptStaticSource(`
const webPreferences = "title";
const serviceName = "env";
${
name === "webPreferences"
? `new BrowserWindow(${options});`
: `utilityProcess.fork("./worker.js", []${options === "" ? "" : `, ${options}`});`
}
`);
const literal = (value: string | boolean) => ({
status: "literal",
value,
expression: null,
});
const expectUnknownOption = (
name: OptionName,
options: string,
optionsStatus: "object-literal" | "dynamic",
): void => {
const analysis = analyzeOption(name, options);
expect(analysis.parse_status).toBe("partial");
expect(analysis.parse_error_count).toBe(0);
expect(analysis.limitations.join(" ")).toContain("remain unknown");
if (name === "webPreferences")
expect(analysis.parse_status).toBe("complete");
expect(analysis.electron.browser_windows[0]).toMatchObject({
options_status: optionsStatus,
preload_path: "./kept.js",
preload_resolution_context: "module-specifier",
web_preferences: [
{ name: "preload", value: { status: "literal", value: "./kept.js" } },
{ name: "sandbox", value: { status: "literal", value: true } },
],
});
expect(analysis.electron.utility_processes[0]).toMatchObject({
module_path: "./worker.js",
service_name: "kept",
});
});
it("keeps values unknown when a later computed key can override them", () => {
const analysis = analyzeJavaScriptStaticSource(`
new BrowserWindow({ webPreferences: { preload: "./maybe.js" }, [key]: null });
utilityProcess.fork("./worker.js", [], { serviceName: "maybe", [key]: null });
`);
expect(analysis.parse_status).toBe("partial");
expect(analysis.parse_error_count).toBe(0);
expect(analysis.limitations.join(" ")).toContain("remain unknown");
expect(analysis.electron.browser_windows[0]).toMatchObject({
preload_path: null,
preload_resolution_context: null,
web_preferences_status: "dynamic",
web_preferences: [],
preload_path: null,
preload_resolution_context: null,
});
else
expect(analysis.electron.utility_processes[0]).toMatchObject({
module_path: "./worker.js",
module_expression: null,
service_name: null,
});
};
});
});
@@ -0,0 +1,70 @@
import { expect, it } from "vitest";
import { htmlArtifactReferences } from "./htmlArtifactReferences.js";
it.each([
['<script data-src="decoy.js"></script>', []],
['<script x:src="decoy.js"></script>', []],
[`<script title='src="decoy.js"'></script>`, []],
["<script src=actual.js></script>", ["actual.js"]],
['<script title=">" src="actual.js"></script>', ["actual.js"]],
['<SCRIPT SRC="actual.js"></SCRIPT>', ["actual.js"]],
["<script src='actual.js'></script>", ["actual.js"]],
['<script data-src="decoy.js" src="actual.js"></script>', ["actual.js"]],
['<script src="actual.js" src="decoy.js"></script>', ["actual.js"]],
['<script src="" src="decoy.js"></script>', []],
['<script src="actual&#46;js"></script>', ["actual.js"]],
['<!-- <script src="decoy.js"></script> -->', []],
['<textarea><script src="decoy.js"></script></textarea>', []],
['<style><script src="decoy.js"></script></style>', []],
[`<script>const text = '<script src="decoy.js">';</script>`, []],
[
'<template><base href="decoy/"><script src="decoy.js"></script></template>',
[],
],
['<svg><script src="decoy.js"></script></svg>', []],
[
'<svg><foreignObject><script src="actual.js"></script></foreignObject></svg>',
["actual.js"],
],
// The existing extraction contract does not classify script MIME types.
['<script type="application/json" src="actual.js"></script>', ["actual.js"]],
])("extracts document references from %s", (text, expected) => {
expect(
htmlArtifactReferences(text).scripts.map(({ scriptPath }) => scriptPath),
).toEqual(expected);
});
it("retains exact opening-tag offsets rather than the script body", () => {
const opening = '<script\n title=">" src=actual.js>';
const prefix = "<!doctype html>\n\n";
const text = `${prefix}${opening}ignored body</script>`;
expect(htmlArtifactReferences(text)).toEqual({
baseHref: null,
scripts: [
{
scriptPath: "actual.js",
startOffset: prefix.length,
endOffset: prefix.length + opening.length,
},
],
});
});
it.each([
['<base data-href="decoy/"><base href=actual/>', "actual/"],
['<base href="actual&#47;" href="decoy/"><base href="later/">', "actual/"],
['<base href=""><base href="decoy/">', ""],
['<template><base href="decoy/"></template><base href="actual/">', "actual/"],
['<!-- <base href="decoy/"> --><base title=">" href="actual/">', "actual/"],
])("selects the first real base href from %s", (text, expected) => {
expect(htmlArtifactReferences(text).baseHref).toBe(expected);
});
it("traverses deep valid document content without recursive stack growth", () => {
const depth = 12_000;
const text = `${"<div>".repeat(depth)}<script src=actual.js></script>${"</div>".repeat(depth)}`;
expect(
htmlArtifactReferences(text).scripts.map(({ scriptPath }) => scriptPath),
).toEqual(["actual.js"]);
});
@@ -0,0 +1,55 @@
import {
defaultTreeAdapter,
parse,
type DefaultTreeAdapterTypes,
} from "parse5";
interface HtmlScriptReference {
readonly scriptPath: string;
readonly startOffset: number;
readonly endOffset: number;
}
/** Extract inert HTML script references and the first document base href. */
export const htmlArtifactReferences = (
text: string,
): {
readonly baseHref: string | null;
readonly scripts: readonly HtmlScriptReference[];
} => {
const pending: DefaultTreeAdapterTypes.Node[] = [
parse(text, { sourceCodeLocationInfo: true }),
];
const scripts: HtmlScriptReference[] = [];
let baseHref: string | null = null;
while (pending.length > 0) {
const node = pending.pop();
if (node === undefined) continue;
if (
defaultTreeAdapter.isElementNode(node) &&
node.namespaceURI === "http://www.w3.org/1999/xhtml"
) {
if (node.tagName === "base" && baseHref === null) {
const href = node.attrs.find(({ name }) => name === "href");
if (href !== undefined) baseHref = href.value;
}
if (node.tagName === "script") {
const src = node.attrs.find(({ name }) => name === "src");
const location = node.sourceCodeLocation?.startTag;
if (src !== undefined && src.value !== "" && location !== undefined) {
scripts.push({
scriptPath: src.value,
startOffset: location.startOffset,
endOffset: location.endOffset,
});
}
}
}
// Template content belongs to a separate inert document fragment. Only
// traverse the actual document children, without recursion on deep input.
if ("childNodes" in node) {
for (const child of node.childNodes.toReversed()) pending.push(child);
}
}
return { baseHref, scripts };
};
@@ -149,6 +149,8 @@ const comparisonLimitations = (
input: ApplicationVersionComparisonProjectionInput,
): string[] =>
uniqueSorted([
...input.left.graph.limitations,
...input.right.graph.limitations,
"Application comparison never uses bundler module ordinals as persistent identity and performs no fuzzy pairing.",
"Exact digest equality proves byte identity only; source-map, structural-fingerprint, and semantic-key matches retain inferred confidence.",
"Minified names and chunk locations are not assumed stable across versions.",
@@ -1,5 +1,8 @@
import { uniqueSorted } from "../canonicalOrdering.js";
import { digestExportShapeValue } from "./javascriptExportShapeComparisonIdentity.js";
import { compareCodePoints, uniqueSorted } from "../canonicalOrdering.js";
import {
canonicalExportShapeValue,
digestExportShapeValue,
} from "./javascriptExportShapeComparisonIdentity.js";
import {
javaScriptExportShapeComparisonResultSchema,
type JavaScriptExportShapeComparisonChange,
@@ -14,7 +17,6 @@ import {
} from "./javascriptExportShapeSelection.js";
import {
buildJavaScriptExportShapeChanges,
compareJavaScriptExportShapeChanges,
hasPartialJavaScriptExportPropertyCoverage,
pairJavaScriptExportShapeVariants,
type JavaScriptExportShapePairing,
@@ -42,14 +44,16 @@ export const compareJavaScriptExportShapes = (
input.left.evidenceId,
input.right.evidenceId,
);
const allChanges = buildJavaScriptExportShapeChanges({
leftSelection: left,
rightSelection: right,
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
evidenceLinks,
}).sort(compareJavaScriptExportShapeChanges);
const allChanges = sortChanges(
buildJavaScriptExportShapeChanges({
leftSelection: left,
rightSelection: right,
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
evidenceLinks,
}),
);
const changes = allChanges;
const omittedChanges = 0;
const coverage = comparisonCoverage({
@@ -62,7 +66,11 @@ export const compareJavaScriptExportShapes = (
allChanges,
omittedChanges,
});
const limitations = comparisonLimitations(left, right, coverage.status);
const limitations = uniqueSorted([
...input.left.graph.limitations,
...input.right.graph.limitations,
...comparisonLimitations(left, right, coverage.status),
]);
const semantic = {
left: left.selection,
right: right.selection,
@@ -78,6 +86,29 @@ export const compareJavaScriptExportShapes = (
});
};
const sortChanges = (
changes: readonly JavaScriptExportShapeComparisonChange[],
): JavaScriptExportShapeComparisonChange[] =>
changes
.map((change, index) => ({
change,
index,
sortKey: canonicalExportShapeValue({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
}),
}))
.sort(
(left, right) =>
compareCodePoints(left.sortKey, right.sortKey) ||
left.index - right.index,
)
.map(({ change }) => change);
interface CoverageInput {
readonly input: JavaScriptExportShapeComparisonProjectionInput;
readonly left: SelectedJavaScriptExport;
@@ -1,9 +1,6 @@
import { expect, it } from "vitest";
import {
javaScriptExportShapeComparisonResultSchema,
projectedExportReturnShapesSchema,
} from "./javascriptExportShapeComparisonSchemas.js";
import { projectedExportReturnShapesSchema } from "./javascriptExportShapeComparisonSchemas.js";
const projectionWithField = (field: unknown) => ({
semantic_role: "export-return-shapes",
@@ -54,104 +51,3 @@ it("parses projected fields into literal, union, or unknown values", () => {
).success,
).toBe(true);
});
it("accepts every projected return site and field without presentation caps", () => {
const fields = Array.from({ length: 65 }, (_, index) => ({
path: `/field-${String(index)}`,
state: "literal",
value: index,
reason: null,
}));
const propertyCoverage = fields.map(({ path }) => ({
path,
status: "complete",
omitted: 0,
}));
const shapes = Array.from({ length: 33 }, () => ({
source_range: {
start: { line: 1, column: 0 },
end: { line: 1, column: 10 },
},
value_status: "object",
fields,
property_coverage: propertyCoverage,
}));
expect(
projectedExportReturnShapesSchema.parse({
...projectionWithField(fields[0]),
static_return_shapes: shapes,
return_shape_coverage: {
status: "complete",
retained_return_sites: shapes.length,
omitted_return_sites: 0,
omitted_fields: 0,
omitted_property_coverage: 0,
projection_complete: true,
},
}).static_return_shapes,
).toHaveLength(33);
});
it("accepts complete candidate and change inventories without page ceilings", () => {
const evidenceId = `ev_${"a".repeat(64)}`;
const graphId = `jag_${"b".repeat(64)}`;
const selector = {
evidence_id: evidenceId,
graph_id: graphId,
requested_module_path: "index.js",
requested_export_name: "render",
candidates: Array.from({ length: 1_001 }, (_, index) => ({
node_id: `jag_node_${index.toString(16).padStart(64, "0")}`,
module_path: "index.js",
export_name: "render",
matches_requested_module: true,
matches_requested_export: true,
})),
omitted_candidates: 0,
status: "missing",
selected_node_id: null,
};
const changes = Array.from({ length: 10_001 }, (_, index) => ({
change_id: `jesc_change_${index.toString(16).padStart(64, "0")}`,
status: "unknown",
path: `/field-${String(index)}`,
discriminant: null,
left: { availability: "absent" },
right: { availability: "absent" },
left_source_range: null,
right_source_range: null,
evidence_links: [evidenceId, `ev_${"c".repeat(64)}`],
limitations: [],
}));
expect(
javaScriptExportShapeComparisonResultSchema.parse({
comparison_id: `jesc_${"d".repeat(64)}`,
left: selector,
right: { ...selector, graph_id: `jag_${"e".repeat(64)}` },
summary: { added: 0, removed: 0, changed: 0, unknown: changes.length },
changes,
coverage: {
status: "complete-within-inputs",
left_graph_status: "complete",
right_graph_status: "complete",
paired_variants: 0,
unpaired_left_variants: 0,
unpaired_right_variants: 0,
omitted_left_variants: 0,
omitted_right_variants: 0,
left_source_omitted_variants: 0,
right_source_omitted_variants: 0,
left_omitted_fields: 0,
right_omitted_fields: 0,
left_omitted_property_coverage: 0,
right_omitted_property_coverage: 0,
omitted_candidates: 0,
omitted_changes: 0,
},
evidence_links: [evidenceId, `ev_${"c".repeat(64)}`],
limitations: [],
}).changes,
).toHaveLength(10_001);
});
@@ -112,16 +112,6 @@ export const buildJavaScriptExportShapeChanges = (
return [...paired, ...unpairedLeft, ...unpairedRight];
};
/** Sort changes by semantic content rather than traversal order. */
export const compareJavaScriptExportShapeChanges = (
left: JavaScriptExportShapeComparisonChange,
right: JavaScriptExportShapeComparisonChange,
): number =>
compareCodePoints(
canonicalExportShapeValue(changeSortKey(left)),
canonicalExportShapeValue(changeSortKey(right)),
);
/** Report whether any retained shape lacks complete property coverage. */
export const hasPartialJavaScriptExportPropertyCoverage = (
shapes: readonly Shape[],
@@ -429,15 +419,6 @@ const changeWithId = (
change_id: `jesc_change_${digestExportShapeValue(semantic)}`,
});
const changeSortKey = (change: JavaScriptExportShapeComparisonChange) => ({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
});
const literalValue = (
field: Field,
):
@@ -253,56 +253,58 @@ describe("feature seed selection controls", () => {
});
describe("public feature trace from contextBridge source members", () => {
it.each(matchingModes)(
"traces $match / $value / case-sensitive $case_sensitive",
(mode) => {
const graph = contextBridgeGraph();
const before = structuredClone(graph);
const input = {
sourceEvidenceId,
graph,
nativeEvidence: [],
direction: "both" as const,
};
const generic = traceApplicationFeature({
...input,
seed: { kind: "string", ...mode },
});
const typed = traceApplicationFeature({
...input,
seed: { kind: "api", ...mode },
});
it("traces one exact member seed through the public feature workflow", () => {
const mode = {
value: "openProject",
match: "exact" as const,
case_sensitive: true,
};
const graph = contextBridgeGraph();
const before = structuredClone(graph);
const input = {
sourceEvidenceId,
graph,
nativeEvidence: [],
direction: "both" as const,
};
const generic = traceApplicationFeature({
...input,
seed: { kind: "string", ...mode },
});
const typed = traceApplicationFeature({
...input,
seed: { kind: "api", ...mode },
});
expect(typed.coverage).toEqual({
status: "complete-within-source",
source_graph_status: "complete",
total_seed_matches: 1,
});
expect(typed.seed_matches).toEqual(generic.seed_matches);
expect(typed.seed_matches).toEqual([
{
node_id: graph.nodes[0]?.node_id,
kind: "context-bridge-api",
basis: "property",
field: "observations[0].properties.members[1]",
},
]);
expect(typed.graph?.nodes).toEqual(graph.nodes);
expect(typed.graph?.edges).toEqual([]);
expect(typed.evidence_links).toEqual([sourceEvidenceId]);
expect(typed.summary).toMatchObject({
matched_seeds: 1,
traced_nodes: 1,
traced_edges: 0,
observed_facts: 1,
inferred_facts: 0,
unknown_facts: 0,
unavailable_facts: 0,
});
expect(typed.native_handoffs).toEqual([]);
expect(graph).toEqual(before);
},
);
expect(typed.coverage).toEqual({
status: "complete-within-source",
source_graph_status: "complete",
total_seed_matches: 1,
});
expect(typed.seed_matches).toEqual(generic.seed_matches);
expect(typed.seed_matches).toEqual([
{
node_id: graph.nodes[0]?.node_id,
kind: "context-bridge-api",
basis: "property",
field: "observations[0].properties.members[1]",
},
]);
expect(typed.graph?.nodes).toEqual(graph.nodes);
expect(typed.graph?.edges).toEqual([]);
expect(typed.evidence_links).toEqual([sourceEvidenceId]);
expect(typed.summary).toMatchObject({
matched_seeds: 1,
traced_nodes: 1,
traced_edges: 0,
observed_facts: 1,
inferred_facts: 0,
unknown_facts: 0,
unavailable_facts: 0,
});
expect(typed.native_handoffs).toEqual([]);
expect(graph).toEqual(before);
});
it("keeps a missing member explicit without changing source coverage", () => {
const graph = contextBridgeGraph();
@@ -119,6 +119,7 @@ const noMatchResult = (
evidence_links: [input.sourceEvidenceId],
limitations: uniqueSorted([
"No graph entity matched the literal seed; this is not evidence that the feature is absent.",
...input.graph.limitations,
...sourceCoverageLimitations(input.graph),
]),
};
@@ -239,6 +240,7 @@ const traceCoverageStatus = (
const traceLimitations = (graph: JavaScriptApplicationGraph): string[] =>
uniqueSorted([
...graph.limitations,
"A trace reports graph relationships, not proof that code executed or that a feature is reachable in every state.",
"Static, native, passive-runtime, inferred, and unknown facts retain their original authority in the returned graph.",
"Native handoffs never open a binary or invoke a provider automatically; snapshot reuse remains provider/profile/target exact.",
@@ -2,19 +2,6 @@ import { describe, expect, it } from "vitest";
import { javascriptRecoveryInputSchema } from "./javascriptRecovery.js";
describe("JavaScript recovery requests", () => {
it("defaults omitted transform metadata without requiring engine confirmations", () => {
expect(
javascriptRecoveryInputSchema.parse({
path: "/tmp/bundle.js",
output_directory: "/tmp/recovered",
}),
).toEqual({
path: "/tmp/bundle.js",
output_directory: "/tmp/recovered",
extraction_mode: "structural",
rewrite_level: "standard",
});
});
it.each([
{ path: "", output_directory: "/tmp/recovered" },
{ path: "/tmp/bundle.js" },
@@ -1,39 +1,15 @@
import { expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
it.each(["namespace", "default", "named-default"])(
"retains Node built-in effects from %s imports",
(mode) => {
const imports = ["fs", "child_process", "timers", "http"]
.map((name, index) => {
const declaration =
mode === "namespace"
? `* as m${String(index)}`
: mode === "default"
? `m${String(index)}`
: `{default as m${String(index)}}`;
return `import ${declaration} from 'node:${name}';`;
})
.join("\n");
const ir = analyzeJavaScriptSemantics(`${imports}
const text = m0.readFileSync('config.json','utf8');
const stream = m0.createReadStream('config.json'); stream.destroy();
const child = m1.spawn('/usr/bin/tool', ['--version']);
const timer = m2.setTimeout(work,1000); m2.clearTimeout(timer);
const request = m3.get('http://localhost/');
it("does not assign built-in APIs to unrelated or shadowed bindings", () => {
const ir = analyzeJavaScriptSemantics(`
import fs from "./fs.js";
import { constants as constantsFs } from "node:fs";
fs.createReadStream("config.json");
constantsFs.createReadStream("config.json");
function run(fs) { fs.createReadStream("config.json"); }
`);
expect(ir.configurationOperations).toHaveLength(1);
expect(ir.resourceOperations).toHaveLength(2);
expect(ir.childProcessSpawns).toHaveLength(1);
expect(ir.timerOperations).toHaveLength(2);
expect(ir.requestOperations).toHaveLength(1);
},
);
it.each([
"import fs from './fs.js'; fs.createReadStream('config.json');",
"import {constants as fs} from 'node:fs'; fs.createReadStream('config.json');",
"function run(fs) { fs.createReadStream('config.json'); }",
])("does not invent a built-in namespace for %s", (source) => {
expect(analyzeJavaScriptSemantics(source).resourceOperations).toEqual([]);
expect(ir.resourceOperations).toEqual([]);
});
@@ -155,19 +155,6 @@ describe("JavaScript semantic analysis: calls 2", () => {
]);
});
it("retains every promise operation found in the finite source", () => {
const ir = analyzeJavaScriptSemantics(
`
Promise.resolve(1);
Promise.resolve(2);
Promise.resolve(3);
`,
);
expect(ir.promiseOperations).toHaveLength(3);
expect(ir.coverage.status).toBe("complete");
});
it("fingerprints formatting and local-name changes identically", () => {
const left = analyzeJavaScriptSemantics(`
function calculate(value) {
@@ -1,67 +1,43 @@
import * as t from "@babel/types";
import { expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import {
analyzeJavaScriptSemantics,
analyzeParsedJavaScriptSemantics,
} from "./javascriptSemanticAnalysis.js";
import { onlyBinding, origin } from "./javascriptSemanticAnalysis.fixture.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { calleeName } from "./javascriptStaticAnalysisHelpers.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import { analyzeParsedJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const memberChain = ".next".repeat(12_000);
const ordinaryMemberChain = ".next".repeat(64);
it("retains native addon observations through a deep member initializer", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = require("./addon.node")${memberChain}.last[""];`,
it("preserves a 12,000-member native import through both analyzers", () => {
const parsed = parseJavaScriptSource(
`const value = require("./addon.node")${memberChain}.last; const ordinary = root.next.last;`,
);
expect(analysis.electron.native_addon_bindings).toEqual([
if (parsed === null) throw new Error("Expected valid JavaScript");
const staticAnalysis = analyzeParsedJavaScriptStaticSource("", parsed);
const ir = analyzeParsedJavaScriptSemantics(parsed);
expect(staticAnalysis.parse_status).toBe("complete");
expect(staticAnalysis.electron.native_addon_bindings).toEqual([
expect.objectContaining({ specifier: "./addon.node", members: ["last"] }),
]);
expect(analysis.parse_error_count).toBe(0);
});
it("keeps a deep non-native initializer outside native addon observations", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = root${memberChain}.last;`,
);
expect(analysis.electron.native_addon_bindings).toEqual([]);
expect(analysis.parse_status).toBe("complete");
});
it("retains unknown value diagnostics and references after a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`const value = root${memberChain}.last;`,
);
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, "value")).toMatchObject({
value: { status: "unknown", reason: "Cannot project last from unknown." },
provenance: { status: "unknown", reason: "Unbound identifier root." },
});
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
]);
});
it.each([
`const value = require("./dependency.js")${memberChain}[""].last;`,
`const dependency = require("./dependency.js"); const value = dependency${memberChain}[""].last;`,
`const value = require("./dependency.js")?.next${memberChain}[""].last;`,
])("preserves the full literal module path (case %#)", (source) => {
const ir = analyzeJavaScriptSemantics(source);
const path = origin(onlyBinding(ir, "value"));
expect(path.specifier).toBe("./dependency.js");
expect(path.specifier).toBe("./addon.node");
expect(path.importedPath).toEqual([
...(source.includes("?.next") ? ["next"] : []),
...Array.from({ length: 12_000 }, () => "next"),
"",
"last",
]);
expect(ir.coverage.status).toBe("complete");
});
it("retains a deep CommonJS re-export path without inventing dynamic module links", () => {
const ir = analyzeJavaScriptSemantics(`
module.exports.result = require("./dependency.js")${memberChain}.last;
const dynamic = require("./other.js")${memberChain}[key].last;
module.exports.result = require("./dependency.js")${ordinaryMemberChain}.last;
const dynamic = require("./other.js")${ordinaryMemberChain}[key].last;
`);
expect(ir.moduleLinks).toEqual([
expect.objectContaining({
@@ -80,7 +56,7 @@ it("retains a deep CommonJS re-export path without inventing dynamic module link
it("invalidates a deep mutation while retaining unrelated literal properties", () => {
const ir = analyzeJavaScriptSemantics(`
const root = { untouched: "retained" };
root${memberChain}.last = 1;
root${ordinaryMemberChain}.last = 1;
const value = root.untouched;
`);
expect(onlyBinding(ir, "root").value).toEqual({
@@ -98,7 +74,7 @@ it("invalidates a deep mutation while retaining unrelated literal properties", (
});
it("retains the complete location and unresolved target of a deep call", () => {
const callee = `root${memberChain}.last`;
const callee = `root${ordinaryMemberChain}.last`;
const ir = analyzeJavaScriptSemantics(`${callee}();`);
expect(ir.callSites).toEqual([
expect.objectContaining({
@@ -115,7 +91,7 @@ it("retains the complete location and unresolved target of a deep call", () => {
it("retains deep default values without confusing their reads with parameter bindings", () => {
const ir = analyzeJavaScriptSemantics(
`export function inspect(value = root${memberChain}.last) { return value; }`,
`export function inspect(value = root${ordinaryMemberChain}.last) { return value; }`,
);
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
@@ -126,7 +102,7 @@ it("retains deep default values without confusing their reads with parameter bin
it("keeps a shadowed require local through a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`function inspect(require) { const value = require("./dependency.js")${memberChain}.last; return value; }`,
`function inspect(require) { const value = require("./dependency.js")${ordinaryMemberChain}.last; return value; }`,
);
expect(ir.moduleLinks).toEqual([]);
expect(onlyBinding(ir, "value").provenance.origins).toEqual([]);
@@ -140,7 +116,7 @@ it.each([
["root[0].last()", "root.0.last"],
["root[key].last()", "root.[computed@5].last"],
["root?.first.last()", "root.first.last"],
[`root${memberChain}.last()`, `root${memberChain}.last`],
[`root${ordinaryMemberChain}.last()`, `root${ordinaryMemberChain}.last`],
])("preserves exact callee syntax (case %#)", (source, expected) => {
const file = parseJavaScriptSource(source);
const statement = file?.program.body[0];
@@ -147,3 +147,54 @@ it("keeps an explicit return statement's full range and the producer's location"
});
expect(site.location.start.column).toBe(source.indexOf("return"));
});
it("links returned promises to the exact return site in each callable", () => {
const ir = analyzeJavaScriptSemantics(
[
"function first() { return Promise.resolve(1); }",
"function second() { return Promise.resolve(2); }",
].join("\n"),
);
const callables = new Map(
ir.callables.map((callable) => [callable.name, callable]),
);
const promises = ir.promiseOperations.filter(
({ method }) => method === "resolve",
);
expect(promises).toHaveLength(2);
for (const name of ["first", "second"] as const) {
const callable = callables.get(name);
const promise = promises.find(
({ ownerCallableId }) => ownerCallableId === callable?.callableId,
);
expect(callable?.returnSites).toHaveLength(1);
expect(promise).toMatchObject({
ownership: "returned",
ownerCallableId: callable?.callableId,
returnSiteId: callable?.returnSites[0]?.returnSiteId,
});
}
});
it("does not assign a return site to a Promise owned by a binding", () => {
const ir = analyzeJavaScriptSemantics(
"function unrelated() { return Promise.resolve(2); }\nconst pending = Promise.resolve(1);",
);
const owned = ir.promiseOperations.find(
({ ownerCallableId }) => ownerCallableId !== null,
);
const assigned = ir.promiseOperations.find(
({ ownerCallableId }) => ownerCallableId === null,
);
expect(owned).toMatchObject({
ownership: "returned",
returnSiteId: ir.callables.find(({ name }) => name === "unrelated")
?.returnSites[0]?.returnSiteId,
});
expect(assigned).toMatchObject({
ownership: "assigned",
returnSiteId: null,
});
});
@@ -18,6 +18,19 @@ const valueOf = (expression: string) =>
analyzeJavaScriptSemantics(`const answer = ${expression};`),
"answer",
).value;
const valuesOf = (expressions: readonly string[]) => {
const ir = analyzeJavaScriptSemantics(
expressions
.map(
(expression, index) =>
`const candidate${String(index)} = ${expression};`,
)
.join("\n"),
);
return expressions.map(
(_, index) => topLevelBinding(ir, `candidate${String(index)}`).value,
);
};
describe("conditional primitive unions", () => {
const cases = conditionalCandidates.flatMap((known) =>
@@ -35,11 +48,11 @@ describe("conditional primitive unions", () => {
]),
);
it.each(cases)("preserves incompatible alternatives in %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
it("preserves incompatible alternatives across conditional expressions", () => {
expect(valuesOf(cases)).toEqual(cases.map(() => incompatibleValue));
});
it.each([
const exactCases = [
[
'condition ? (choice ? "two" : "one") : "three"',
{ status: "union", values: ["one", "three", "two"] },
@@ -69,8 +82,12 @@ describe("conditional primitive unions", () => {
{ status: "union", values: [null, "one", "two"] },
],
["condition ? null : null", { status: "literal", value: null }],
])("retains exact primitive candidates in %s", (expression, expected) => {
expect(valueOf(expression)).toEqual(expected);
] as const;
it("retains exact primitive candidates across conditional expressions", () => {
expect(valuesOf(exactCases.map(([expression]) => expression))).toEqual(
exactCases.map(([, expected]) => expected),
);
});
it("propagates an incompatible nested branch through an outer union", () => {
@@ -119,11 +136,11 @@ describe("logical primitive unions", () => {
),
);
it.each(cases)("preserves unresolved alternatives in %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
it("preserves unresolved alternatives across logical expressions", () => {
expect(valuesOf(cases)).toEqual(cases.map(() => incompatibleValue));
});
it.each([
const exactCases = [
[
'(choice ? "" : "one") || "two"',
{ status: "union", values: ["", "one", "two"] },
@@ -138,19 +155,24 @@ describe("logical primitive unions", () => {
],
['"one" || "one"', { status: "literal", value: "one" }],
["null ?? null", { status: "literal", value: null }],
])(
"retains the conservative primitive union in %s",
(expression, expected) => {
expect(valueOf(expression)).toEqual(expected);
},
);
] as const;
it.each([
it("retains conservative primitive unions across logical expressions", () => {
expect(valuesOf(exactCases.map(([expression]) => expression))).toEqual(
exactCases.map(([, expected]) => expected),
);
});
const unevaluatedCases = [
'true ? "one" : missing',
'"one" || missing',
"false && missing",
'"one" ?? missing',
])("does not introduce short-circuit evaluation for %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
];
it("does not introduce short-circuit evaluation", () => {
expect(valuesOf(unevaluatedCases)).toEqual(
unevaluatedCases.map(() => incompatibleValue),
);
});
});
@@ -38,7 +38,8 @@ const normalizeEvidence = (
evidence_ids: uniqueSorted(evidence.evidence_ids),
});
const nodeId = (
/** Derive a semantic node ID from its kind and exact artifact identity. */
export const javaScriptSemanticNodeId = (
node: Pick<JavaScriptSemanticGraphNode, "kind" | "identity">,
): string =>
`jsrg_node_${canonicalDigest({ kind: node.kind, identity: node.identity }, "JavaScript semantic graph")}`;
@@ -59,7 +60,7 @@ export const createJavaScriptSemanticGraphNode = (
};
return javaScriptSemanticNodeSchema.parse({
...semantic,
node_id: nodeId(semantic),
node_id: javaScriptSemanticNodeId(semantic),
});
};
@@ -129,11 +130,21 @@ export const createJavaScriptSemanticFingerprint = (input: unknown) => {
type GraphRecord = z.infer<typeof javaScriptSemanticGraphRecordSchema>;
type SemanticGraphIssue = {
readonly code: "custom";
readonly path: PropertyKey[];
readonly message: string;
};
interface GraphIssueReporter {
readonly addIssue: (issue: SemanticGraphIssue) => void;
}
const sortedUniqueIssue = (
values: readonly string[],
path: PropertyKey[],
label: string,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (let index = 1; index < values.length; index += 1) {
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") < 0)
@@ -147,7 +158,10 @@ const sortedUniqueIssue = (
}
};
const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCoverage = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
const families = graph.coverage.families.map(({ family }) => family);
if (
canonicalJson(families, "JavaScript semantic graph") !==
@@ -221,7 +235,7 @@ const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCanonicalOrder = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
sortedUniqueIssue(
graph.root_node_ids,
@@ -259,10 +273,10 @@ const checkCanonicalOrder = (
const checkNodes = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, node] of graph.nodes.entries()) {
if (node.node_id !== nodeId(node))
if (node.node_id !== javaScriptSemanticNodeId(node))
context.addIssue({
code: "custom",
path: ["nodes", index, "node_id"],
@@ -283,7 +297,7 @@ const checkNodes = (
const checkRoots = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const root of graph.root_node_ids)
if (!nodes.has(root))
@@ -297,7 +311,7 @@ const checkRoots = (
const checkRelations = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, relation] of graph.relations.entries()) {
const { relation_id: identifier, ...semantic } = relation;
@@ -340,7 +354,7 @@ const checkRelations = (
const checkUnknowns = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, unknown] of graph.unknowns.entries()) {
const { unknown_id: identifier, ...semantic } = unknown;
@@ -386,7 +400,7 @@ const checkUnknowns = (
const checkUnknownReferences = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
const unknownIds = new Set(
graph.unknowns.map(({ unknown_id }) => unknown_id),
@@ -403,7 +417,7 @@ const checkUnknownReferences = (
const checkFingerprints = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, fingerprint] of graph.fingerprints.entries()) {
if (nodes.get(fingerprint.function_node_id)?.kind !== "function")
@@ -449,7 +463,10 @@ const checkFingerprints = (
}
};
const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkGraphContent = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
checkCanonicalOrder(graph, context);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
checkNodes(graph, nodes, context);
@@ -465,6 +482,10 @@ const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
path: ["limitations"],
message: "Non-complete graph coverage requires a limitation",
});
};
const checkGraph = (graph: GraphRecord, context: GraphIssueReporter): void => {
checkGraphContent(graph, context);
const { graph_id: identifier, ...semantic } = graph;
if (
identifier !==
@@ -523,10 +544,21 @@ export const createJavaScriptSemanticGraph = (
},
limitations: uniqueSorted(parsed.limitations),
};
return javaScriptSemanticGraphSchema.parse({
// The input schema already cloned and validated every field. Validate the
// normalized relationships in place, then derive the only added field. The
// public schema still verifies arbitrary records and their commitments.
const record: GraphRecord = {
...semantic,
graph_id: `jsrg_${canonicalDigest(semantic, "JavaScript semantic graph")}`,
};
const issues: SemanticGraphIssue[] = [];
checkGraphContent(record, {
addIssue: (issue) => {
issues.push(issue);
},
});
if (issues.length > 0) throw new z.ZodError(issues);
return record;
};
export type { JavaScriptSemanticGraphNode, JavaScriptSemanticGraphRelation };
@@ -15,7 +15,7 @@ import {
} from "./javascriptSemanticState.js";
import { compareCodePoints } from "../canonicalOrdering.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { range, sourceRangesEqual } from "./javascriptStaticAnalysisHelpers.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
assignedSemanticResultBindings,
dataEffectMemberCallee,
@@ -56,7 +56,10 @@ interface PromiseOwnershipContext {
readonly candidate: PromiseCandidate;
readonly candidateByNode: WeakMap<t.Node, PromiseCandidate>;
readonly state: JavaScriptSemanticAnalysisState;
readonly callables: readonly JavaScriptSemanticCallable[];
readonly returnSiteIdFor: (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
) => string | null;
}
/** Recover explicit Promise construction, chaining, aggregation, and ownership. */
@@ -66,6 +69,7 @@ export const collectJavaScriptSemanticPromises = (
callables: readonly JavaScriptSemanticCallable[],
): JavaScriptSemanticPromiseOperation[] => {
const candidates = collectCandidates(program, state, callables);
const returnSiteIdFor = createReturnSiteLookup(callables);
const candidateByNode = new WeakMap<t.Node, PromiseCandidate>();
for (const candidate of candidates)
candidateByNode.set(candidate.node, candidate);
@@ -74,7 +78,7 @@ export const collectJavaScriptSemanticPromises = (
candidate,
candidateByNode,
state,
callables,
returnSiteIdFor,
);
const sources = promiseSources(candidate, candidateByNode, state);
return {
@@ -180,14 +184,14 @@ const promiseOwnership = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => {
if (candidate.kind === "awaited-expression") return emptyOwnership("awaited");
const context: PromiseOwnershipContext = {
candidate,
candidateByNode,
state,
callables,
returnSiteIdFor,
};
for (let index = candidate.ancestors.length - 1; index >= 0; index -= 1) {
const ancestor = candidate.ancestors[index];
@@ -203,7 +207,7 @@ const ownershipAtAncestor = (
ancestor: t.Node,
context: PromiseOwnershipContext,
): PromiseOwnership | "boundary" | null => {
const { candidate, candidateByNode, state, callables } = context;
const { candidate, candidateByNode, state, returnSiteIdFor } = context;
if (t.isAwaitExpression(ancestor))
return unwrapExpression(ancestor.argument) === candidate.node
? emptyOwnership("awaited")
@@ -234,7 +238,7 @@ const ownershipAtAncestor = (
return returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor),
callables,
returnSiteIdFor,
);
}
if (t.isExpressionStatement(ancestor))
@@ -249,7 +253,7 @@ const ownershipAtAncestor = (
? returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor.body),
callables,
returnSiteIdFor,
)
: "boundary";
};
@@ -283,11 +287,11 @@ const assignedPromiseBinding = (
const returnedPromiseOwnership = (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
callables: readonly JavaScriptSemanticCallable[],
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => ({
ownership: "returned",
ownerBindingId: null,
returnSiteId: matchingReturnSite(callableId, location, callables),
returnSiteId: returnSiteIdFor(callableId, location),
});
const outerConsumesCandidate = (
@@ -329,16 +333,56 @@ const emptyOwnership = (
returnSiteId: null,
});
const matchingReturnSite = (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
const indexReturnSites = (
callable: JavaScriptSemanticCallable,
): ReadonlyMap<string, string> => {
const output = new Map<string, string>();
for (const site of callable.returnSites) {
const key = returnSiteKey(site.location);
if (!output.has(key)) output.set(key, site.returnSiteId);
}
return output;
};
const createReturnSiteLookup = (
callables: readonly JavaScriptSemanticCallable[],
): string | null =>
callables
.find(({ callableId: candidate }) => candidate === callableId)
?.returnSites.find(({ location: candidate }) =>
sourceRangesEqual(candidate, location),
)?.returnSiteId ?? null;
): PromiseOwnershipContext["returnSiteIdFor"] => {
let callablesById:
| ReadonlyMap<string, JavaScriptSemanticCallable>
| undefined;
let returnSiteIdsByCallable:
| Map<string, ReadonlyMap<string, string>>
| undefined;
return (callableId, location) => {
if (callableId === null) return null;
callablesById ??= indexCallablesById(callables);
const callable = callablesById.get(callableId);
if (callable === undefined) return null;
returnSiteIdsByCallable ??= new Map();
let returnSiteIds = returnSiteIdsByCallable.get(callableId);
if (returnSiteIds === undefined) {
returnSiteIds = indexReturnSites(callable);
returnSiteIdsByCallable.set(callableId, returnSiteIds);
}
return returnSiteIds.get(returnSiteKey(location)) ?? null;
};
};
const indexCallablesById = (
callables: readonly JavaScriptSemanticCallable[],
): ReadonlyMap<string, JavaScriptSemanticCallable> => {
const output = new Map<string, JavaScriptSemanticCallable>();
for (const callable of callables) {
if (output.has(callable.callableId)) continue;
output.set(callable.callableId, callable);
}
return output;
};
const returnSiteKey = (
location: JavaScriptSemanticPromiseOperation["location"],
): string =>
`${location.start.line}:${location.start.column}:${location.end.line}:${location.end.column}`;
const promiseSources = (
candidate: PromiseCandidate,
@@ -1,28 +1,8 @@
import { expect, it } from "vitest";
import {
javaScriptSemanticQueryInputSchema,
javaScriptSemanticQueryResultSchema,
} from "./javascriptSemanticQuerySchemas.js";
import { javaScriptSemanticQueryInputSchema } from "./javascriptSemanticQuerySchemas.js";
it("accepts long selectors and complete relation and class selections", () => {
const longText = "x".repeat(16_385);
const result = javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "endpoint", value: longText },
direction: "forward-influence",
allowed_relations: Array(2).fill("calls"),
expected: {
role: "sink",
classes: Array(25).fill("module"),
},
});
expect(result.seed).toEqual({ kind: "endpoint", value: longText });
expect(result.allowed_relations).toHaveLength(2);
expect(result.expected?.classes).toHaveLength(25);
});
it("rejects the inert source-map authority setting", () => {
it("rejects a source-map authority setting that the query does not consume", () => {
expect(
javaScriptSemanticQueryInputSchema.safeParse({
seed: { kind: "endpoint", value: "/api" },
@@ -31,36 +11,3 @@ it("rejects the inert source-map authority setting", () => {
}).success,
).toBe(false);
});
it("accepts every reported limitation without a count ceiling", () => {
const limitations = Array.from(
{ length: 1_001 },
(_, index) => `gap-${index}`,
);
const id = "a".repeat(64);
const result = javaScriptSemanticQueryResultSchema.parse({
query_id: `jsrq_${id}`,
source_graph_id: `jsrg_${id}`,
seed: { kind: "literal", value: null },
direction: "forward-influence",
status: "no-match",
seed_node_ids: [],
nodes: [],
relations: [],
unknowns: [],
expected_match_node_ids: [],
summary: {
total_seed_matches: 0,
traversed_nodes: 0,
traversed_relations: 0,
traversed_functions: 0,
traversed_modules: 0,
relevant_unknowns: 0,
},
coverage: { status: "complete" },
limitations,
});
expect(result.limitations).toHaveLength(1_001);
});
@@ -12,16 +12,21 @@ import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const semanticNodeIdSchema = prefixedDigestSchema("jsrg_node");
const literalValueSchema = jsonValueSchema.refine(
(value) =>
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean",
"Literal seeds accept only JSON primitive values",
);
// Zod derivations drop the shared schema's JSON Schema projection override;
// re-apply it so MCP catalog generation keeps projecting `{}`.
literalValueSchema._zod.toJSONSchema = () => ({});
const literalSeedSchema = z.strictObject({
kind: z.literal("literal"),
value: jsonValueSchema.refine(
(value) =>
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean",
"Literal seeds accept only JSON primitive values",
),
value: literalValueSchema,
});
/** Authenticated starting points accepted by semantic tracing. */
@@ -1,66 +0,0 @@
import * as t from "@babel/types";
import { expect, it } from "vitest";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
it("preserves source-tree enter/exit order and detached ancestor snapshots", () => {
const parsed = parseJavaScriptSource("const answer = first + second;");
if (parsed === null)
throw new TypeError("Expected a parsed JavaScript fixture");
const visits: string[] = [];
const snapshots: (readonly t.Node[])[] = [];
traverseJavaScriptAst(parsed.program, {
enter: (node, parent, readAncestors) => {
visits.push(`enter:${node.type}`);
const ancestors = readAncestors();
expect(ancestors.at(-1) ?? null).toBe(parent);
if (t.isIdentifier(node)) snapshots.push(ancestors);
},
exit: (node) => visits.push(`exit:${node.type}`),
});
expect(visits).toEqual([
"enter:Program",
"enter:VariableDeclaration",
"enter:VariableDeclarator",
"enter:Identifier",
"exit:Identifier",
"enter:BinaryExpression",
"enter:Identifier",
"exit:Identifier",
"enter:Identifier",
"exit:Identifier",
"exit:BinaryExpression",
"exit:VariableDeclarator",
"exit:VariableDeclaration",
"exit:Program",
]);
expect(snapshots.map((nodes) => nodes.map(({ type }) => type))).toEqual([
["Program", "VariableDeclaration", "VariableDeclarator"],
[
"Program",
"VariableDeclaration",
"VariableDeclarator",
"BinaryExpression",
],
[
"Program",
"VariableDeclaration",
"VariableDeclarator",
"BinaryExpression",
],
]);
});
it("skips sparse child slots without disturbing sibling visit order", () => {
const parsed = parseJavaScriptSource("const values = [first, , second];");
if (parsed === null)
throw new TypeError("Expected a parsed JavaScript fixture");
const identifiers: string[] = [];
traverseJavaScriptAst(parsed.program, {
enter: (node) => {
if (t.isIdentifier(node)) identifiers.push(node.name);
},
});
expect(identifiers).toEqual(["values", "first", "second"]);
});
@@ -5,6 +5,7 @@ import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
const memberChain = ".next".repeat(12_000);
const ordinaryMemberChain = ".next".repeat(64);
it("collects a 12,000-member CommonJS export path without recursion", () => {
const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`);
@@ -48,8 +49,8 @@ it("keeps left-first and outer-member-first bundler runtime matches", () => {
).toBe("webpackChunkInner");
});
it("analyzes a 12,000-member bundler runtime chain without recursion", () => {
const source = `globalThis.webpackChunkApp${memberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
it("recognizes a bundler runtime through nested member names", () => {
const source = `globalThis.webpackChunkApp${ordinaryMemberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
const analysis = analyzeJavaScriptStaticSource(source);
expect(analysis.parse_status).toBe("complete");
expect(analysis.parse_error_count).toBe(0);
@@ -22,12 +22,6 @@ describe("source map directives", () => {
expect(sourceMapUrls(source)).toEqual([expected]);
});
it("keeps the comment terminator out of the declared url", () => {
expect(sourceMapUrls("/*# sourceMappingURL=app.js.map */")).toEqual([
"app.js.map",
]);
});
it("retains every directive in a source", () => {
expect(
sourceMapUrls(
@@ -84,30 +78,6 @@ describe("source map comment boundaries", () => {
});
describe("source map comment locations and recovery", () => {
it("keeps exact locations and the first occurrence of duplicate URLs", () => {
const line = "//# sourceMappingURL=first.map";
const block = "/*# sourceMappingURL=second.map";
const result = analyzeJavaScriptStaticSource(
['const marker = "😀";', line, `${block} */`, line].join("\r\n"),
);
expect(result.source_map_urls).toEqual([
{
declared_url: "first.map",
location: {
start: { line: 2, column: 0 },
end: { line: 2, column: line.length },
},
},
{
declared_url: "second.map",
location: {
start: { line: 3, column: 0 },
end: { line: 3, column: block.length },
},
},
]);
});
it("keeps real comments when the parser recovers and reports partial syntax", () => {
const result = analyzeJavaScriptStaticSource(
"let value; let value;\n//# sourceMappingURL=recovered.map",
+132
View File
@@ -0,0 +1,132 @@
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
jsonObjectSchema,
jsonValueSchema,
MAX_JSON_DEPTH,
} from "./jsonValue.js";
const values = [
"text",
0,
false,
null,
[],
{},
{ nested: [{ deeper: [1, "two", null, { three: true }] }] },
];
it("projects JSON values without recursive definitions", () => {
for (const io of ["input", "output"] as const) {
const schema = z.toJSONSchema(
z.object({ value: jsonValueSchema, map: jsonObjectSchema }),
{ io },
);
expect(JSON.stringify(schema)).not.toContain("$ref");
expect(schema).not.toHaveProperty("$defs");
const validate = new Ajv2020({ strict: false }).compile(schema);
for (const value of values)
expect(validate({ value, map: { value } })).toBe(true);
expect(validate({ value: 1, map: [] })).toBe(false);
}
});
it("still parses only JSON values at runtime", () => {
for (const value of values)
expect(jsonValueSchema.safeParse(value).success).toBe(true);
for (const value of [undefined, Number.NaN, Infinity, () => 0, [undefined]])
expect(jsonValueSchema.safeParse(value).success).toBe(false);
});
const deepObject = (depth: number): unknown => {
let value: unknown = 1;
for (let index = 0; index < depth; index += 1) value = { nested: value };
return value;
};
describe("jsonValueSchema depth bound", () => {
it("accepts values nested to the maximum depth", () => {
expect(jsonValueSchema.safeParse(deepObject(MAX_JSON_DEPTH)).success).toBe(
true,
);
});
it("rejects values nested past the maximum depth without throwing", () => {
const result = jsonValueSchema.safeParse(deepObject(MAX_JSON_DEPTH + 1));
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error.issues[0]?.message).toContain("maximum nesting depth");
});
it.each(["object", "array"])(
"rejects the original 10000-level %s crash without throwing",
(kind) => {
let value: unknown = 1;
for (let index = 0; index < 10_000; index += 1)
value = kind === "object" ? { nested: value } : [value];
const result = jsonValueSchema.safeParse(value);
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error.issues[0]?.message).toContain(
"maximum nesting depth",
);
},
);
it("rejects cyclic values instead of recursing forever", () => {
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
const result = jsonValueSchema.safeParse(cyclic);
expect(result.success).toBe(false);
});
it("keeps json semantics for non-JSON values", () => {
expect(jsonValueSchema.safeParse(undefined).success).toBe(false);
expect(jsonValueSchema.safeParse({ a: Number.NaN }).success).toBe(false);
expect(
jsonValueSchema.safeParse({ a: Number.POSITIVE_INFINITY }).success,
).toBe(false);
expect(jsonValueSchema.safeParse({ a: 1n }).success).toBe(false);
});
it("accepts ordinary nested JSON", () => {
expect(
jsonValueSchema.safeParse({
list: [1, "two", null, true, { deep: { further: [{}] } }],
}).success,
).toBe(true);
});
});
it("preserves prototype-named members without prototype mutation", () => {
const input: unknown = JSON.parse(
'{"__proto__":{"preserved":7},"constructor":"ordinary","prototype":[1],"nested":{"\\u005f\\u005fproto\\u005f\\u005f":"escaped"},"list":[{"__proto__":null}]}',
);
const parsed = jsonObjectSchema.parse(input);
expect(parsed).toEqual(input);
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
expect(Object.hasOwn(parsed, "__proto__")).toBe(true);
expect(parsed["__proto__"]).toEqual({ preserved: 7 });
expect(parsed["constructor"]).toBe("ordinary");
expect(parsed["prototype"]).toEqual([1]);
expect(parsed["nested"]).toEqual({ ["__proto__"]: "escaped" });
expect(parsed["list"]).toEqual([{ ["__proto__"]: null }]);
expect(Object.getPrototypeOf(parsed["nested"])).toBe(Object.prototype);
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
expect(JSON.parse(JSON.stringify(parsed))).toEqual(input);
});
it.each([undefined, Number.NaN, Infinity, 1n, () => 0, new Date(0)])(
"rejects non-JSON values in prototype-named members (%s)",
(value) => {
for (const input of [
{ ["__proto__"]: value },
{ nested: [{ ["__proto__"]: value }] },
]) {
expect(jsonValueSchema.safeParse(input).success).toBe(false);
expect(jsonObjectSchema.safeParse(input).success).toBe(false);
}
},
);
+82 -4
View File
@@ -1,9 +1,87 @@
import { z } from "zod";
/** Maximum JSON nesting accepted before recursive result cloning. */
export const MAX_JSON_DEPTH = 1000;
/** JSON-safe value shared by domain, application, and adapter boundaries. */
export const jsonValueSchema = z.json();
export type JsonValue =
| string
| number
| boolean
| null
| JsonValue[]
| { [key: string]: JsonValue };
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const recordShape = z.record(z.string(), z.unknown());
const jsonValidationIssue = (root: unknown): string | undefined => {
const pending: { value: unknown; depth: number }[] = [
{ value: root, depth: 0 },
];
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (item.depth > MAX_JSON_DEPTH)
return `JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`;
const value = item.value;
if (
value === null ||
typeof value === "string" ||
typeof value === "boolean"
)
continue;
if (typeof value === "number") {
if (!Number.isFinite(value)) return "JSON numbers must be finite";
} else if (Array.isArray(value)) {
for (const child of value)
pending.push({ value: child, depth: item.depth + 1 });
} else if (isRecord(value) && recordShape.safeParse(value).success) {
// Inspect every own member, including keys Zod's record parser skips.
for (const child of Object.values(value))
pending.push({ value: child, depth: item.depth + 1 });
} else return "Invalid JSON value";
}
return undefined;
};
const preserveJsonValue = (value: JsonValue): JsonValue => {
if (Array.isArray(value)) return value.map(preserveJsonValue);
if (value !== null && typeof value === "object")
return Object.fromEntries<JsonValue>(
Object.entries(value).map(([key, child]) => [
key,
preserveJsonValue(child),
]),
);
return value;
};
const validatedJsonValue = z.custom<JsonValue>(
(value) => jsonValidationIssue(value) === undefined,
{
error: (issue) => jsonValidationIssue(issue.input) ?? "Invalid JSON value",
},
);
// Keep both stages nonrecursive in public and Standard Schema projections.
validatedJsonValue._zod.toJSONSchema = () => ({});
/** Parse bounded JSON and retain all own data members without prototype setters. */
export const jsonValueSchema = z
.unknown()
.nonoptional()
.pipe(validatedJsonValue)
.transform(preserveJsonValue);
jsonValueSchema._zod.toJSONSchema = () => ({});
const objectValidation = z.custom<Record<string, JsonValue>>(
isRecord,
"Expected JSON object",
);
const objectProjection = () => ({ type: "object", additionalProperties: {} });
objectValidation._zod.toJSONSchema = objectProjection;
/** JSON object boundary for caller-visible parameter maps. */
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
export type JsonValue = z.infer<typeof jsonValueSchema>;
export const jsonObjectSchema = jsonValueSchema.pipe(objectValidation);
jsonObjectSchema._zod.toJSONSchema = objectProjection;
+4
View File
@@ -1,5 +1,9 @@
import { isAbsolute, relative, sep } from "node:path";
/** True when the value is an absolute filesystem path on the host platform. */
export const isAbsoluteLocalPath = (value: string): boolean =>
isAbsolute(value);
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
export const isPathWithinRoot = (root: string, path: string): boolean => {
const value = relative(root, path);
@@ -199,7 +199,10 @@ export const managedNativeVerificationResultSchema = z
path: ["summary", "native_body_unresolved"],
message: "Native body summary must match unresolved implementations",
});
});
})
.describe(
"Counts must agree across the result: native accepted plus unsupported equals total; each P/Invoke summary count equals the number of items with that status; and native_body_unresolved equals native_implementations.unresolved. REA checks these cross-field invariants after constructing the result.",
);
export type ManagedNativeVerificationResult = z.infer<
typeof managedNativeVerificationResultSchema
@@ -1,131 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyMobileResource,
detectMobileFormat,
detectPlatform,
getAllArchitectures,
hasInternetPermission,
mobileArtifactManifestSchema,
nativeLibsByArchitecture,
type MobileArtifactManifest,
type AndroidManifest,
type SigningInfo,
type NativeLibrary,
type MobileResource,
} from "./mobileApplicationInvestigation.js";
describe("mobile application investigation", () => {
it("detects mobile format from extension", () => {
expect(detectMobileFormat("app.apk")).toBe("apk");
expect(detectMobileFormat("app.aab")).toBe("aab");
expect(detectMobileFormat("app.ipa")).toBe("ipa");
expect(detectMobileFormat("classes.dex")).toBe("dex");
expect(detectMobileFormat("lib.so")).toBe("native_lib");
expect(detectMobileFormat("readme.txt")).toBeNull();
});
it("detects platform from format", () => {
expect(detectPlatform("apk")).toBe("android");
expect(detectPlatform("aab")).toBe("android");
expect(detectPlatform("dex")).toBe("android");
expect(detectPlatform("ipa")).toBe("ios");
expect(detectPlatform("native_lib")).toBe("cross_platform");
});
it("classifies resources by path", () => {
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
expect(classifyMobileResource("assets/data.json")).toBe("asset");
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
"native_lib",
);
expect(classifyMobileResource("unknown.xyz")).toBe("other");
});
const androidManifest: AndroidManifest = {
package_name: "com.example.app",
version_name: "1.0.0",
version_code: 1,
min_sdk: 21,
target_sdk: 34,
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
activities: ["MainActivity"],
services: ["BackgroundService"],
receivers: [],
providers: [],
};
const signing: SigningInfo = {
is_signed: true,
signer_identity: "CN=TestSigner",
certificate_fingerprint: "abc123",
signature_scheme: "v2",
is_debuggable: false,
};
const nativeLibs: NativeLibrary[] = [
{
path: "lib/arm64-v8a/libnative.so",
architecture: "arm64-v8a",
size: 100000,
digest: "a".repeat(64),
},
{
path: "lib/armeabi-v7a/libnative.so",
architecture: "armeabi-v7a",
size: 90000,
digest: "b".repeat(64),
},
];
const resources: MobileResource[] = [
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
];
const validManifest: MobileArtifactManifest = {
format: "apk",
platform: "android",
app_name: "TestApp",
android_manifest: androidManifest,
ios_manifest: null,
signing,
resources,
native_libraries: nativeLibs,
total_size: 5000000,
architectures: ["arm64-v8a", "armeabi-v7a"],
};
it("rejects a manifest with a negative total size", () => {
const result = mobileArtifactManifestSchema.safeParse({
...validManifest,
total_size: -1,
});
expect(result.success).toBe(false);
});
it("filters native libs by architecture", () => {
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
expect(arm64).toHaveLength(1);
expect(arm64[0]!.architecture).toBe("arm64-v8a");
});
it("checks internet permission", () => {
expect(hasInternetPermission(validManifest)).toBe(true);
const noInternet: MobileArtifactManifest = {
...validManifest,
android_manifest: { ...androidManifest, permissions: [] },
};
expect(hasInternetPermission(noInternet)).toBe(false);
});
it("gets all architectures", () => {
const archs = getAllArchitectures(validManifest);
expect(archs).toHaveLength(2);
expect(archs).toContain("arm64-v8a");
expect(archs).toContain("armeabi-v7a");
});
});
@@ -1,177 +0,0 @@
import { z } from "zod";
/** Supported mobile artifact formats. */
export const mobileArtifactFormatSchema = z.enum([
"apk",
"aab",
"ipa",
"dex",
"native_lib",
]);
export type MobileArtifactFormat = z.infer<typeof mobileArtifactFormatSchema>;
/** Mobile platform. */
export const mobilePlatformSchema = z.enum([
"android",
"ios",
"cross_platform",
]);
export type MobilePlatform = z.infer<typeof mobilePlatformSchema>;
/** Android manifest entry. */
export const androidManifestSchema = z.strictObject({
package_name: z.string().min(1),
version_name: z.string().nullable(),
version_code: z.number().int().nullable(),
min_sdk: z.number().int().nullable(),
target_sdk: z.number().int().nullable(),
permissions: z.array(z.string()).default([]),
activities: z.array(z.string()).default([]),
services: z.array(z.string()).default([]),
receivers: z.array(z.string()).default([]),
providers: z.array(z.string()).default([]),
});
export type AndroidManifest = z.infer<typeof androidManifestSchema>;
/** iOS app manifest (Info.plist). */
export const iosManifestSchema = z.strictObject({
bundle_identifier: z.string().min(1),
bundle_version: z.string().nullable(),
short_version: z.string().nullable(),
minimum_os_version: z.string().nullable(),
supported_platforms: z.array(z.string()).default([]),
ui_required_device_capabilities: z.array(z.string()).default([]),
app_permissions: z.array(z.string()).default([]),
});
/** Signing information. */
export const signingInfoSchema = z.strictObject({
is_signed: z.boolean().default(false),
signer_identity: z.string().nullable(),
certificate_fingerprint: z.string().nullable(),
signature_scheme: z.string().nullable(),
is_debuggable: z.boolean().default(false),
});
export type SigningInfo = z.infer<typeof signingInfoSchema>;
/** Native library entry. */
export const nativeLibrarySchema = z.strictObject({
path: z.string().min(1),
architecture: z.string().nullable(),
size: z.number().int().nonnegative(),
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type NativeLibrary = z.infer<typeof nativeLibrarySchema>;
/** Resource entry within a mobile artifact. */
export const mobileResourceSchema = z.strictObject({
path: z.string().min(1),
type: z.enum([
"layout",
"drawable",
"string",
"asset",
"raw",
"native_lib",
"manifest",
"entitlements",
"provisioning",
"other",
]),
size: z.number().int().nonnegative(),
});
export type MobileResource = z.infer<typeof mobileResourceSchema>;
/** Static analysis result for a mobile artifact. */
export const mobileArtifactManifestSchema = z.strictObject({
format: mobileArtifactFormatSchema,
platform: mobilePlatformSchema,
app_name: z.string().nullable(),
android_manifest: androidManifestSchema.nullable(),
ios_manifest: iosManifestSchema.nullable(),
signing: signingInfoSchema,
resources: z.array(mobileResourceSchema).default([]),
native_libraries: z.array(nativeLibrarySchema).default([]),
total_size: z.number().int().nonnegative(),
architectures: z.array(z.string()).default([]),
});
export type MobileArtifactManifest = z.infer<
typeof mobileArtifactManifestSchema
>;
/** Detect mobile artifact format from file extension. */
export function detectMobileFormat(path: string): MobileArtifactFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".apk")) return "apk";
if (lower.endsWith(".aab")) return "aab";
if (lower.endsWith(".ipa")) return "ipa";
if (lower.endsWith(".dex")) return "dex";
if (lower.endsWith(".so") || lower.endsWith(".dylib") || lower.endsWith(".a"))
return "native_lib";
return null;
}
/** Detect platform from format. */
export function detectPlatform(format: MobileArtifactFormat): MobilePlatform {
switch (format) {
case "apk":
case "aab":
case "dex":
return "android";
case "ipa":
return "ios";
case "native_lib":
return "cross_platform";
}
}
/** Classify a resource by its path. */
export function classifyMobileResource(path: string): MobileResource["type"] {
const lower = path.toLowerCase();
if (lower.includes("androidmanifest.xml")) return "manifest";
if (lower.includes(".entitlements")) return "entitlements";
if (lower.includes("provisioning") || lower.includes(".mobileprovision"))
return "provisioning";
if (lower.includes("/layout/")) return "layout";
if (lower.includes("/drawable/") || lower.includes("/mipmap/"))
return "drawable";
if (lower.includes("/values/")) return "string";
if (lower.includes("assets/") || lower.includes("raw/")) return "asset";
if (lower.endsWith(".so") || lower.endsWith(".dylib")) return "native_lib";
if (lower.endsWith(".xml")) return "layout";
return "other";
}
/** Get all native libraries for a specific architecture. */
export function nativeLibsByArchitecture(
manifest: MobileArtifactManifest,
arch: string,
): NativeLibrary[] {
return manifest.native_libraries.filter((l) => l.architecture === arch);
}
/** Check if an Android artifact has internet permission. */
export function hasInternetPermission(
manifest: MobileArtifactManifest,
): boolean {
if (!manifest.android_manifest) return false;
return manifest.android_manifest.permissions.some(
(p) => p.includes("INTERNET") || p.includes("android.permission.INTERNET"),
);
}
/** Get all unique architectures across native libraries. */
export function getAllArchitectures(
manifest: MobileArtifactManifest,
): string[] {
const archs = new Set<string>();
for (const lib of manifest.native_libraries) {
if (lib.architecture) archs.add(lib.architecture);
}
for (const arch of manifest.architectures) {
archs.add(arch);
}
return [...archs];
}
+362
View File
@@ -0,0 +1,362 @@
import { expect, it } from "vitest";
import { binaryLayoutSchema, type BinaryLayout } from "./binaryLayout.js";
const report = () => ({
artifact: { path: "/fixture.elf", sha256: "a".repeat(64), bytes: 128 },
format: "elf",
architecture: { machine: "EM_X86_64", bits: 64, byte_order: "little" },
image_type: "ET_EXEC",
entry_point: {
reported_value: "0x20000000000001",
meaning: "linked-virtual-address",
execution_status: "unknown",
},
runtime_load_base: null,
sections: [
{
index: 0,
name: {
display: "opaque",
bytes_base64: "b3BhcXVl",
location: { offset: "0x40", bytes: "0x7" },
unknown_reason: null,
},
name_offset: "0x0",
type: "SHT_NOBITS",
header_location: { offset: "0x0", bytes: "0x40" },
address: "0x20000000000001",
offset: "0xffffffffffffffff",
size: "0x2000",
alignment: "0x1",
flags: "0x3",
link: 0,
info: 0,
entry_size: "0x0",
file_backing: "none",
},
],
segments: [],
symbols: [],
relocations: [],
packed_relative_relocations: [],
relocation_inventory_completeness: "unknown",
linkage: {
needed_libraries: [],
interpreters: [],
got: [],
plt: [],
convenience_maps_completeness: "unknown",
runtime_library_paths: null,
},
mitigations: {
evidence_kind: "inferred",
position_independent: false,
nx_indicator: null,
executable_stack_indicator: false,
stack_canary_indicator: false,
relro: null,
},
diagnostics: { stdout: "", stderr: "", truncated: false },
limitations: [],
});
it("retains high linked values and NOBITS without inventing file backing", () => {
const value = binaryLayoutSchema.parse(report());
expect(value.entry_point.reported_value).toBe("0x20000000000001");
expect(value.sections[0]?.offset).toBe("0xffffffffffffffff");
expect(value.runtime_load_base).toBeNull();
});
it.each([
"file-backed-outside",
"header-outside",
"wrong-index",
"noncanonical-base64",
"wrong-machine",
"outside-elf64",
])("rejects a malformed source representation: %s", (problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
if (problem === "file-backed-outside") section.file_backing = "file";
if (problem === "header-outside") section.header_location.offset = "0x80";
if (problem === "wrong-index") section.index = 1;
if (problem === "wrong-machine") value.architecture.machine = "EM_AARCH64";
if (problem === "outside-elf64")
value.entry_point.reported_value = "0x10000000000000000";
if (problem === "noncanonical-base64") section.name.bytes_base64 = "AR==";
expect(binaryLayoutSchema.safeParse(value).success).toBe(false);
});
it.each([
["PT_NULL", "0xffffffffffffffff", "none", null, true],
["PT_LOAD", "0x0", "none", { read: true, write: true, execute: false }, true],
[
"PT_LOAD",
"0x1",
"file",
{ read: true, write: false, execute: false },
false,
],
["PT_NULL", "0x1", "file", null, false],
[
"PT_NULL",
"0x1",
"none",
{ read: false, write: false, execute: false },
false,
],
[
"PT_LOAD",
"0x1",
"none",
{ read: true, write: false, execute: false },
false,
],
])(
"validates actual segment backing/meaning for %s size %s",
(type, fileSize, backing, permissions, valid) => {
const value = {
...report(),
segments: [
{
index: 0,
type,
header_location: { offset: "0x0", bytes: "0x38" },
offset: "0xffffffffffffffff",
file_size: fileSize,
memory_size: fileSize,
virtual_address: "0x0",
physical_address: "0x0",
alignment: "0x0",
flags: "0x0",
file_backing: backing,
permissions,
},
],
};
expect(binaryLayoutSchema.safeParse(value).success).toBe(valid);
},
);
it.each([
["ET_EXEC", "0x0", "absent", true],
["ET_DYN", "0x0", "linked-virtual-address", false],
["ET_REL", "0x0", "not-applicable", true],
["ET_EXEC", "0x1", "absent", false],
])(
"validates actual entry meaning: %s %s %s",
(imageType, entry, meaning, valid) => {
expect(
binaryLayoutSchema.safeParse({
...report(),
image_type: imageType,
entry_point: {
reported_value: entry,
meaning,
execution_status: "unknown",
},
}).success,
).toBe(valid);
},
);
it.each([
"valid",
"byte-length",
"section-identity",
"decoded-order",
"noncanonical-bytes",
])(
"retains original packed bytes and derived offset provenance: %s",
(problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
section.type = "SHT_RELR";
section.file_backing = "file";
section.offset = "0x60";
section.size = "0x8";
const table = {
section_index: 0,
location: { offset: "0x60", bytes: "0x8" },
encoded_bytes_base64: "AAAAAAAAAAA=",
entries: [{ decoded_index: 0, reported_offset: "0x20000000000001" }],
offset_meaning: "linked-virtual-address",
evidence_kind: "derived",
entry_source_locations: null,
addends: null,
};
if (problem === "byte-length") table.location.bytes = "0x7";
if (problem === "section-identity") table.section_index = 1;
if (problem === "decoded-order")
table.entries[0] = { decoded_index: 1, reported_offset: "0x0" };
if (problem === "noncanonical-bytes") table.encoded_bytes_base64 = "AB==";
expect(
binaryLayoutSchema.safeParse({
...value,
packed_relative_relocations: [table],
}).success,
).toBe(problem === "valid");
},
);
it.each([
"valid",
"zero-symbol",
"zero-without-table",
"missing-table",
"wrong-table-kind",
"missing-symbol",
"symbol-outside-table",
"positive-without-table",
"owner-link-mismatch",
"wrong-meaning",
"valid-section-target",
"missing-target",
"wrong-target-owner",
"wrong-target-offset",
"undefined-target",
"inactive-target",
"false-resolved-zero-target",
"wrong-unknown-target",
"missing-string-table",
"wrong-string-table-kind",
])("validates relocation symbol reference semantics: %s", (problem) => {
const value = binaryLayoutSchema.parse(report());
value.artifact.bytes = 512;
const base = value.sections[0];
if (base === undefined) throw new Error("section missing");
value.sections.push(
{
...base,
index: 1,
type: "SHT_SYMTAB",
link: 3,
header_location: { offset: "0x40", bytes: "0x40" },
offset: "0x100",
size: "0x30",
entry_size: "0x18",
file_backing: "file",
},
{
...base,
index: 2,
type: "SHT_RELA",
header_location: { offset: "0x80", bytes: "0x40" },
offset: "0x130",
size: "0x18",
entry_size: "0x18",
link: 1,
file_backing: "file",
},
{
...base,
index: 3,
type: "SHT_STRTAB",
offset: "0x40",
size: "0x7",
file_backing: "file",
},
);
value.symbols.push({
table_index: 1,
entry_index: 1,
name: base.name,
name_offset: "0x0",
location: { offset: "0x118", bytes: "0x18" },
value: "0x0",
value_meaning: "undefined",
size: "0x0",
binding: "STB_GLOBAL",
type: "STT_NOTYPE",
visibility: "STV_DEFAULT",
section_index: "SHN_UNDEF",
});
const relocation: BinaryLayout["relocations"][number] = {
section_index: 2,
entry_index: 0,
reported_offset: "0x0",
target: { kind: "linked-virtual-address", address: "0x0" },
location: { offset: "0x130", bytes: "0x18" },
type: 1,
symbol_table_index: 1,
symbol_index: 1,
symbol_reference_meaning: "symbol-table-entry",
addend: "0",
};
const table = value.sections[1];
const owner = value.sections[2];
if (table === undefined || owner === undefined)
throw new Error("table or relocation owner missing");
if (problem.startsWith("zero")) {
relocation.symbol_index = 0;
relocation.symbol_reference_meaning = "zero-symbol-value";
}
if (problem === "zero-without-table" || problem === "positive-without-table")
owner.link = relocation.symbol_table_index = 0;
if (problem === "missing-table")
owner.link = relocation.symbol_table_index = 99;
if (problem === "wrong-table-kind") table.type = "SHT_PROGBITS";
if (problem === "missing-string-table") table.link = 99;
if (problem === "wrong-string-table-kind") table.link = 0;
if (problem === "missing-symbol") value.symbols = [];
if (problem === "symbol-outside-table") table.size = "0x18";
if (problem === "owner-link-mismatch") owner.link = 0;
if (problem === "wrong-meaning")
relocation.symbol_reference_meaning = "zero-symbol-value";
if (problem.includes("target")) {
value.image_type = "ET_REL";
value.entry_point.meaning = "not-applicable";
owner.info = 1;
relocation.target = {
kind: "section-offset",
section_index:
problem === "missing-target"
? 99
: problem === "wrong-target-owner"
? 2
: 1,
offset: problem === "wrong-target-offset" ? "0x1" : "0x0",
};
if (problem === "missing-target") owner.info = 99;
if (problem === "false-resolved-zero-target") {
owner.info = 0;
relocation.target.section_index = 0;
}
if (
["undefined-target", "inactive-target", "wrong-unknown-target"].includes(
problem,
)
) {
if (problem === "inactive-target")
value.sections.push({ ...base, index: 4, type: "SHT_NULL" });
owner.info =
problem === "undefined-target"
? 0
: problem === "inactive-target"
? 4
: 1;
relocation.target = {
kind: "unknown-section",
reported_section_index: owner.info,
offset: "0x0",
unknown_reason:
problem === "undefined-target"
? "undefined-section-reference"
: "inactive-section-header",
};
}
}
value.relocations.push(relocation);
expect(binaryLayoutSchema.safeParse(value).success).toBe(
[
"valid",
"zero-symbol",
"zero-without-table",
"valid-section-target",
"undefined-target",
"inactive-target",
].includes(problem),
);
});
+443
View File
@@ -0,0 +1,443 @@
import { z } from "zod";
const unsignedHex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const scalar = z.union([z.string(), z.number().int()]);
const range = z.strictObject({ offset: unsignedHex, bytes: unsignedHex });
const canonicalBase64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const name = z.strictObject({
display: z.string(),
bytes_base64: canonicalBase64.nullable(),
location: range.nullable(),
unknown_reason: z.string().nullable(),
});
/** Explicit local object selection, independent of an active disassembler target. */
export const inspectBinaryLayoutInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to the selected binary"),
});
/** File and linked-image evidence; numeric ELF values never pass through unsafe JSON numbers. */
const binaryLayoutObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf"),
architecture: z.strictObject({
machine: z.literal("EM_X86_64"),
bits: z.literal(64),
byte_order: z.literal("little"),
}),
image_type: z.enum(["ET_EXEC", "ET_DYN", "ET_REL"]),
entry_point: z.strictObject({
reported_value: unsignedHex,
meaning: z.enum(["linked-virtual-address", "not-applicable", "absent"]),
execution_status: z.literal("unknown"),
}),
runtime_load_base: z.null(),
sections: z.array(
z.strictObject({
index,
name,
name_offset: unsignedHex,
type: scalar,
header_location: range,
address: unsignedHex,
offset: unsignedHex,
size: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
link: index,
info: index,
entry_size: unsignedHex,
file_backing: z.enum(["file", "none"]),
}),
),
segments: z.array(
z.strictObject({
index,
type: scalar,
header_location: range,
offset: unsignedHex,
file_size: unsignedHex,
memory_size: unsignedHex,
virtual_address: unsignedHex,
physical_address: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
file_backing: z.enum(["file", "none"]),
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
}),
),
symbols: z.array(
z.strictObject({
table_index: index,
entry_index: index,
name,
name_offset: unsignedHex,
location: range,
value: unsignedHex,
value_meaning: z.enum([
"undefined",
"alignment",
"absolute-value",
"no-address",
"unknown-section-index",
"section-offset",
"tls-offset",
"linked-virtual-address",
]),
size: unsignedHex,
binding: scalar,
type: scalar,
visibility: scalar,
section_index: scalar,
}),
),
relocations: z.array(
z.strictObject({
section_index: index,
entry_index: index,
reported_offset: unsignedHex,
target: z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("section-offset"),
section_index: index,
offset: unsignedHex,
}),
z.strictObject({
kind: z.literal("linked-virtual-address"),
address: unsignedHex,
}),
z.strictObject({
kind: z.literal("unknown-section"),
reported_section_index: index,
offset: unsignedHex,
unknown_reason: z.enum([
"undefined-section-reference",
"inactive-section-header",
]),
}),
]),
location: range,
type: index,
symbol_table_index: index,
symbol_index: index,
symbol_reference_meaning: z.enum([
"zero-symbol-value",
"symbol-table-entry",
]),
addend: z
.string()
.regex(/^-?(?:0|[1-9][0-9]{0,18})$/)
.nullable(),
}),
),
packed_relative_relocations: z.array(
z.strictObject({
section_index: index,
location: range,
encoded_bytes_base64: canonicalBase64,
entries: z.array(
z.strictObject({ decoded_index: index, reported_offset: unsignedHex }),
),
offset_meaning: z.enum(["linked-virtual-address", "unknown"]),
evidence_kind: z.literal("derived"),
entry_source_locations: z.null(),
addends: z.null(),
}),
),
relocation_inventory_completeness: z.literal("unknown"),
linkage: z.strictObject({
needed_libraries: z.array(name),
interpreters: z.array(name),
got: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
plt: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
convenience_maps_completeness: z.literal("unknown"),
runtime_library_paths: z.null(),
}),
mitigations: z.strictObject({
evidence_kind: z.literal("inferred"),
position_independent: z.boolean(),
nx_indicator: z.boolean().nullable(),
executable_stack_indicator: z.boolean(),
stack_canary_indicator: z.boolean(),
relro: z.enum(["Partial", "Full"]).nullable(),
}),
diagnostics: z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
}),
limitations: z.array(z.string()),
});
/** Decoder payload excludes the artifact identity observed by the owning process boundary. */
export const binaryLayoutPayloadSchema = binaryLayoutObjectSchema.omit({
artifact: true,
diagnostics: true,
});
/** Check source ranges again at the public boundary, independently of upstream parsing. */
export const binaryLayoutSchema = binaryLayoutObjectSchema.superRefine(
(value, context) => {
const size = BigInt(value.artifact.bytes);
const check = (
offset: string,
length: string,
path: (string | number)[],
): void => {
const start = BigInt(offset);
const bytes = BigInt(length);
if (start > size || bytes > size - start)
context.addIssue({
code: "custom",
path,
message:
"Reported file-backed range lies outside the selected artifact.",
});
};
const checkLocation = (
where: z.infer<typeof range>,
path: (string | number)[],
): void => check(where.offset, where.bytes, path);
const checkName = (
reported: z.infer<typeof name>,
path: (string | number)[],
): void => {
if (reported.location !== null)
checkLocation(reported.location, [...path, "location"]);
};
const expectedEntryMeaning =
value.image_type === "ET_REL"
? "not-applicable"
: value.entry_point.reported_value === "0x0"
? "absent"
: "linked-virtual-address";
if (value.entry_point.meaning !== expectedEntryMeaning)
context.addIssue({
code: "custom",
path: ["entry_point", "meaning"],
message:
"Entry meaning must distinguish zero/unused fields from an actual linked address.",
});
for (const [index, section] of value.sections.entries()) {
if (
(section.type === "SHT_SYMTAB" || section.type === "SHT_DYNSYM") &&
value.sections[section.link]?.type !== "SHT_STRTAB"
)
context.addIssue({
code: "custom",
path: ["sections", index, "link"],
message:
"Symbol tables must link to an existing string-table section.",
});
if (section.index !== index)
context.addIssue({
code: "custom",
path: ["sections", index, "index"],
message:
"Complete section order must preserve original producer indices.",
});
checkLocation(section.header_location, [
"sections",
index,
"header_location",
]);
checkName(section.name, ["sections", index, "name"]);
if (section.file_backing === "file")
check(section.offset, section.size, ["sections", index]);
}
for (const [index, segment] of value.segments.entries()) {
if (segment.index !== index)
context.addIssue({
code: "custom",
path: ["segments", index, "index"],
message:
"Complete segment order must preserve original producer indices.",
});
checkLocation(segment.header_location, [
"segments",
index,
"header_location",
]);
const hasFileBytes =
segment.type !== "PT_NULL" && BigInt(segment.file_size) !== 0n;
if (segment.file_backing !== (hasFileBytes ? "file" : "none"))
context.addIssue({
code: "custom",
path: ["segments", index, "file_backing"],
message:
"File backing must follow the reported segment type and file size.",
});
if ((segment.type === "PT_NULL") !== (segment.permissions === null))
context.addIssue({
code: "custom",
path: ["segments", index, "permissions"],
message:
"Unused PT_NULL flags have no permission meaning; other segment flags retain their interpretation.",
});
if (hasFileBytes)
check(segment.offset, segment.file_size, ["segments", index]);
}
for (const [index, symbol] of value.symbols.entries()) {
checkLocation(symbol.location, ["symbols", index, "location"]);
checkName(symbol.name, ["symbols", index, "name"]);
}
for (const [index, relocation] of value.relocations.entries())
checkLocation(relocation.location, ["relocations", index, "location"]);
validateRelocationReferences(value, context);
validatePackedRelativeTables(value, context, checkLocation);
for (const facet of ["needed_libraries", "interpreters"] as const)
for (const [index, reported] of value.linkage[facet].entries())
checkName(reported, ["linkage", facet, index]);
},
);
export type InspectBinaryLayoutInput = z.infer<
typeof inspectBinaryLayoutInputSchema
>;
export type BinaryLayout = z.infer<typeof binaryLayoutSchema>;
const validateRelocationReferences = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
): void => {
const symbols = new Set(
value.symbols.map(
(symbol) => `${symbol.table_index}:${symbol.entry_index}`,
),
);
for (const [index, relocation] of value.relocations.entries()) {
const owner = value.sections[relocation.section_index];
const target = relocation.target;
const targetMatches =
value.image_type === "ET_REL"
? target.kind === "section-offset"
? target.section_index !== 0 &&
target.section_index === owner?.info &&
value.sections[target.section_index] !== undefined &&
value.sections[target.section_index]?.type !== "SHT_NULL" &&
target.offset === relocation.reported_offset
: target.kind === "unknown-section" &&
target.reported_section_index === owner?.info &&
target.offset === relocation.reported_offset &&
(target.reported_section_index === 0
? target.unknown_reason === "undefined-section-reference"
: value.sections[target.reported_section_index]?.type ===
"SHT_NULL" &&
target.unknown_reason === "inactive-section-header")
: target.kind === "linked-virtual-address" &&
target.address === relocation.reported_offset;
if (!targetMatches)
context.addIssue({
code: "custom",
path: ["relocations", index, "target"],
message:
"Relocation target must preserve its reported offset and owner reference; SHN_UNDEF and inactive headers remain unknown rather than resolved sections.",
});
const table = value.sections[relocation.symbol_table_index];
const tableExists =
relocation.symbol_table_index !== 0 &&
(table?.type === "SHT_SYMTAB" || table?.type === "SHT_DYNSYM");
const positiveReferenceExists =
tableExists &&
BigInt(table.entry_size) >= 24n &&
BigInt(relocation.symbol_index) <
BigInt(table.size) / BigInt(table.entry_size) &&
symbols.has(
`${relocation.symbol_table_index}:${relocation.symbol_index}`,
);
if (
(owner?.type !== "SHT_REL" && owner?.type !== "SHT_RELA") ||
owner.link !== relocation.symbol_table_index ||
(relocation.symbol_table_index !== 0 && !tableExists) ||
(relocation.symbol_index !== 0 && !positiveReferenceExists) ||
relocation.symbol_reference_meaning !==
(relocation.symbol_index === 0
? "zero-symbol-value"
: "symbol-table-entry")
)
context.addIssue({
code: "custom",
path: ["relocations", index],
message:
"Relocation must preserve its REL/RELA owner and resolve positive symbol indices through the linked symbol table; index zero uses a zero symbol value.",
});
}
};
const validatePackedRelativeTables = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
checkLocation: (
location: z.output<typeof range>,
path: (string | number)[],
) => void,
): void => {
for (const [
tableIndex,
table,
] of value.packed_relative_relocations.entries()) {
checkLocation(table.location, [
"packed_relative_relocations",
tableIndex,
"location",
]);
const encodedBytes =
(table.encoded_bytes_base64.length * 3) / 4 -
(table.encoded_bytes_base64.endsWith("==")
? 2
: table.encoded_bytes_base64.endsWith("=")
? 1
: 0);
if (
!Number.isInteger(encodedBytes) ||
BigInt(encodedBytes) !== BigInt(table.location.bytes)
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex],
message:
"Complete packed table bytes must match its original file range.",
});
const section = value.sections[table.section_index];
if (
section?.type !== "SHT_RELR" ||
section.offset !== table.location.offset ||
section.size !== table.location.bytes
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "section_index"],
message:
"Packed relative evidence must retain its original RELR section identity and range.",
});
for (const [decoded, entry] of table.entries.entries())
if (entry.decoded_index !== decoded)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "entries", decoded],
message: "Decoded offsets must preserve upstream iterator order.",
});
}
};
+198
View File
@@ -0,0 +1,198 @@
import { z } from "zod";
const hexSchema = z.string().regex(/^0x[0-9a-f]+$/u);
/** Objective-C class names and selectors never contain spaces or brackets. */
const objcName = z
.string()
.min(1)
.regex(/^[^\s[\]]+$/u, "Use the bare name without spaces or brackets");
const functionBreakpoint = {
kind: z.literal("function"),
name: z
.string()
.min(1)
.describe(
"Exact symbol name, such as `open`, a C++ or mangled Swift symbol, or `-[NSString length]`.",
),
};
const objcMethodBreakpoint = {
kind: z.literal("objc-method"),
selector: objcName.describe(
"Selector such as `dataTaskWithRequest:completionHandler:`.",
),
};
/** One function or Objective-C method whose entries are observed. */
export const nativeCallBreakpointSchema = z.discriminatedUnion("kind", [
z.strictObject({
...functionBreakpoint,
module: z
.string()
.min(1)
.optional()
.describe(
"Image file name that defines the symbol, such as `libsystem_kernel.dylib`; omit to match every image.",
),
}),
z.strictObject({
...objcMethodBreakpoint,
class_name: objcName
.optional()
.describe("Implementing class; omit to match every class."),
method_type: z.enum(["instance", "class", "any"]).default("any"),
}),
]);
/**
* Launch the active Mach-O as an owned process under LLDB and observe calls.
* Duration and event bounds keep runtime observation finite.
*/
export const nativeCallObservationInputSchema = z.strictObject({
breakpoints: z.array(nativeCallBreakpointSchema).min(1),
arguments: z.array(z.string()).default([]),
environment: z
.record(
z
.string()
.min(1)
.regex(/^[^=\0]+$/u, "Environment names cannot contain '=' or NUL"),
z.string().regex(/^[^\0]*$/u, "Environment values cannot contain NUL"),
)
.default({})
.describe("Overrides on top of the environment REA runs with."),
working_directory: z.string().min(1).optional(),
duration_ms: z
.number()
.int()
.min(100)
.max(600_000)
.default(10_000)
.describe(
"Observation window; the process is killed if it is still running.",
),
max_events: z
.number()
.int()
.min(1)
.max(100_000)
.default(1_000)
.describe(
"Stop observing and kill the process after this many recorded entries.",
),
argument_registers: z
.number()
.int()
.min(0)
.max(8)
.default(4)
.describe(
"Integer argument registers to record per entry (arm64 has 8, x86_64 has 6).",
),
backtrace_frames: z
.number()
.int()
.min(0)
.max(64)
.default(0)
.describe("Caller frames to record per entry."),
});
export type NativeCallObservationInput = z.infer<
typeof nativeCallObservationInputSchema
>;
/** A code address with the image and symbol LLDB attributes to it. */
export const nativeCodeLocationSchema = z.strictObject({
load_address: hexSchema,
file_address: hexSchema.nullable(),
module: z.string().nullable(),
module_path: z.string().nullable(),
symbol: z.string().nullable(),
});
/** One observed entry into a requested function or method. */
export const nativeCallEventSchema = z.strictObject({
sequence: z.number().int().nonnegative(),
elapsed_ms: z.number().nonnegative(),
thread_id: z.number().int().nonnegative(),
breakpoint_index: z.number().int().nonnegative(),
...nativeCodeLocationSchema.shape,
/** Dynamic class of an instance-method receiver, read without running code. */
receiver_class: z.string().nullable(),
/** Selector string read from the `_cmd` register of an Objective-C method. */
selector: z.string().nullable(),
registers: z.array(z.strictObject({ name: z.string(), value: hexSchema })),
backtrace: z.array(nativeCodeLocationSchema),
});
const capturedOutputSchema = z.strictObject({
text: z.string(),
bytes: z.number().int().nonnegative(),
truncated: z.boolean(),
});
/** Observed calls, the process lifecycle, and breakpoint resolution. */
export const nativeCallObservationResultSchema = z.strictObject({
target: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
architecture: z.string(),
arguments: z.array(z.string()),
working_directory: z.string().nullable(),
}),
debugger: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
version: z.string().nullable(),
}),
process: z.strictObject({
pid: z.number().int().positive(),
outcome: z.enum([
"exited",
"duration-elapsed",
"event-limit",
"stop-limit",
]),
exit_status: z.number().int().nullable(),
exit_description: z.string().nullable(),
/** REA confirmed the process is gone when observation ended. */
terminated: z.boolean(),
elapsed_ms: z.number().nonnegative(),
stdout: capturedOutputSchema,
stderr: capturedOutputSchema,
/** Signal and exception stops LLDB reported; the process continued past each. */
other_stops: z.array(z.string()),
}),
breakpoints: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
request: z.discriminatedUnion("kind", [
z.strictObject({
...functionBreakpoint,
module: z.string().nullable(),
}),
z.strictObject({
...objcMethodBreakpoint,
class_name: z.string().nullable(),
method_type: z.enum(["instance", "class", "any"]),
}),
]),
location_count: z.number().int().nonnegative(),
locations: z.array(nativeCodeLocationSchema),
}),
),
events: z.array(nativeCallEventSchema),
coverage: z.strictObject({
status: z.enum(["complete", "partial"]),
event_limit_reached: z.boolean(),
/** Requests that matched no code in any image loaded while observing. */
unresolved_breakpoints: z.array(z.number().int().nonnegative()),
}),
limitations: z.array(z.string()),
});
export type NativeCallObservationResult = z.infer<
typeof nativeCallObservationResultSchema
>;
+21 -5
View File
@@ -60,10 +60,26 @@ export const nativeUiScenarioInputSchema = z.strictObject({
const nativeUiScreenshotSchema = z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string().min(4),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
width: z.number().int().positive(),
height: z.number().int().positive(),
base64: z
.string()
.min(4)
.describe(
"Canonical base64 encoding of PNG bytes; the decoded bytes must have a PNG signature and IHDR chunk.",
),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.describe("SHA-256 digest of the decoded PNG bytes."),
width: z
.number()
.int()
.positive()
.describe("Must equal the width encoded in the PNG IHDR chunk."),
height: z
.number()
.int()
.positive()
.describe("Must equal the height encoded in the PNG IHDR chunk."),
})
.superRefine((screenshot, context) => {
const bytes = decodeCanonicalBase64(screenshot.base64);
@@ -117,7 +133,7 @@ export const nativeUiSnapshotSchema = z.strictObject({
title: z.string().nullable(),
value: z.string().nullable(),
actions: z.array(z.string()),
children_count: z.number().int().nonnegative(),
children_count: z.number().int().nonnegative().nullable(),
}),
),
truncated: z.boolean(),
+1 -143
View File
@@ -1,150 +1,8 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
countMethodsByType,
isDbSaveComplete,
isGetterSelector,
isSetterSelector,
inspectNativeDispatchMetadata,
propertyNameFromSelector,
swiftDeclsByKind,
type ObjcMethod,
type SwiftDecl,
type DbSaveResult,
} from "./objcSwiftMetadata.js";
import { inspectNativeDispatchMetadata } from "./objcSwiftMetadata.js";
describe("ObjC/Swift metadata", () => {
it("identifies getter selectors", () => {
expect(isGetterSelector("name")).toBe(true);
expect(isGetterSelector("setName:")).toBe(false);
expect(isGetterSelector("set")).toBe(true);
});
it("identifies setter selectors", () => {
expect(isSetterSelector("setName:")).toBe(true);
expect(isSetterSelector("name")).toBe(false);
});
it("extracts property name from selector", () => {
expect(propertyNameFromSelector("name")).toBe("name");
expect(propertyNameFromSelector("setName:")).toBe("name");
expect(propertyNameFromSelector("set")).toBe("set");
});
it("counts methods by type", () => {
const methods: ObjcMethod[] = [
{
selector: "init",
method_type: "instance",
address: 0x1000,
is_required: false,
is_optional: false,
},
{
selector: "alloc",
method_type: "class",
address: 0x2000,
is_required: false,
is_optional: false,
},
];
const counts = countMethodsByType(methods);
expect(counts.instance).toBe(1);
expect(counts.class).toBe(1);
expect(counts.ivar_getter).toBe(0);
expect(counts.ivar_setter).toBe(0);
});
it("filters Swift declarations by kind", () => {
const decls: SwiftDecl[] = [
{
kind: "class",
name: "Foo",
module: null,
access_level: "public",
super_class: null,
protocols: [],
is_final: false,
is_required: false,
is_convenience_init: false,
is_override: false,
},
];
const classes = swiftDeclsByKind(decls, "class");
expect(classes).toHaveLength(1);
expect(classes[0]!.name).toBe("Foo");
});
it("checks database save completeness", () => {
const result: DbSaveResult = {
operation: "save",
succeeded: true,
preserved_names: 10,
preserved_comments: 5,
preserved_bookmarks: 3,
database_path: "/tmp/db.hop",
error: null,
};
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
});
it("is monotone in every expected count and total at the observed count", () => {
fc.assert(
fc.property(
fc.record({
operation: fc.constantFrom(
"save",
"readback",
"open_database",
"close_database",
"export",
"import",
),
succeeded: fc.boolean(),
preserved_names: fc.nat({ max: 50 }),
preserved_comments: fc.nat({ max: 50 }),
preserved_bookmarks: fc.nat({ max: 50 }),
database_path: fc.option(fc.string(), { nil: null }),
error: fc.option(fc.string(), { nil: null }),
}),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
(result, names, comments, bookmarks) => {
// Completeness is downward closed: if demanding more was met,
// demanding less must also be met.
if (isDbSaveComplete(result, names + 1, comments, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments + 1, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments, bookmarks + 1)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
// Expecting exactly what was preserved is complete iff the save worked.
expect(
isDbSaveComplete(
result,
result.preserved_names,
result.preserved_comments,
result.preserved_bookmarks,
),
).toBe(result.succeeded);
},
),
{ numRuns: 200 },
);
});
it("bounds symbol projections and labels symbol-only metadata as partial", () => {
const result = inspectNativeDispatchMetadata(
[
+4 -65
View File
@@ -7,7 +7,6 @@ export const objcMethodTypeSchema = z.enum([
"ivar_getter",
"ivar_setter",
]);
export type ObjcMethodType = z.infer<typeof objcMethodTypeSchema>;
/** Objective-C property attribute. */
export const objcPropertyAttributeSchema = z.strictObject({
@@ -27,7 +26,7 @@ export const objcMethodSchema = z.strictObject({
is_required: z.boolean().default(false),
is_optional: z.boolean().default(false),
});
export type ObjcMethod = z.infer<typeof objcMethodSchema>;
type ObjcMethod = z.infer<typeof objcMethodSchema>;
/** Objective-C property metadata. */
export const objcPropertySchema = z.strictObject({
@@ -87,7 +86,7 @@ export const objcClassSchema = z.strictObject({
)
.optional(),
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
type ObjcClass = z.infer<typeof objcClassSchema>;
/** Exact location of a decoded native metadata value when the provider knows it. */
export const nativeMetadataLocationSchema = z.strictObject({
@@ -162,7 +161,7 @@ export const objcDispatchImplementationSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcDispatchImplementation = z.infer<
type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
@@ -224,7 +223,7 @@ export const swiftSymbolSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
/** Per-facet coverage; empty arrays are meaningful only with this record. */
export const nativeMetadataCoverageSchema = z.strictObject({
@@ -246,7 +245,6 @@ export const swiftDeclKindSchema = z.enum([
"global_var",
"global_func",
]);
export type SwiftDeclKind = z.infer<typeof swiftDeclKindSchema>;
/** Swift access level. */
export const swiftAccessLevelSchema = z.enum([
@@ -269,7 +267,6 @@ export const swiftDeclSchema = z.strictObject({
is_convenience_init: z.boolean().default(false),
is_override: z.boolean().default(false),
});
export type SwiftDecl = z.infer<typeof swiftDeclSchema>;
/** Database save/read operation type. */
export const dbOperationSchema = z.enum([
@@ -290,7 +287,6 @@ export const dbSaveResultSchema = z.strictObject({
database_path: z.string().nullable(),
error: z.string().nullable(),
});
export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
/** Result of deeper ObjC/Swift metadata extraction. */
export const objcSwiftMetadataSchema = z.strictObject({
@@ -479,60 +475,3 @@ const parseMetadataAddress = (address: string | null): number | null => {
const value = Number.parseInt(match[1], 16);
return Number.isSafeInteger(value) ? value : null;
};
/** Check if a selector name looks like a getter. */
export function isGetterSelector(selector: string): boolean {
return /^[a-z][a-zA-Z0-9_]*$/u.test(selector) && !selector.includes(":");
}
/** Check if a selector name looks like a setter. */
export function isSetterSelector(selector: string): boolean {
return selector.startsWith("set") && selector.endsWith(":");
}
/** Extract property name from a getter/setter selector. */
export function propertyNameFromSelector(selector: string): string | null {
if (isSetterSelector(selector)) {
const inner = selector.slice(3, -1);
return inner.charAt(0).toLowerCase() + inner.slice(1);
}
if (isGetterSelector(selector)) {
return selector;
}
return null;
}
/** Count ObjC methods by type. */
export function countMethodsByType(
methods: readonly ObjcMethod[],
): Record<ObjcMethodType, number> {
return {
instance: methods.filter((m) => m.method_type === "instance").length,
class: methods.filter((m) => m.method_type === "class").length,
ivar_getter: methods.filter((m) => m.method_type === "ivar_getter").length,
ivar_setter: methods.filter((m) => m.method_type === "ivar_setter").length,
};
}
/** Get all Swift declarations of a specific kind. */
export function swiftDeclsByKind(
decls: readonly SwiftDecl[],
kind: SwiftDeclKind,
): SwiftDecl[] {
return decls.filter((d) => d.kind === kind);
}
/** Check if a database save preserved all expected items. */
export function isDbSaveComplete(
result: DbSaveResult,
expectedNames: number,
expectedComments: number,
expectedBookmarks: number,
): boolean {
return (
result.succeeded &&
result.preserved_names >= expectedNames &&
result.preserved_comments >= expectedComments &&
result.preserved_bookmarks >= expectedBookmarks
);
}
+284
View File
@@ -0,0 +1,284 @@
import { expect, it } from "vitest";
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
} from "./recordedCrash.js";
import {
recordedCrashFixture,
recordedCrashSignalFixture,
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
it("preserves high uint64 registers and historical thread identity", () => {
const value = recordedCrashSchema.parse(recordedCrashFixture());
expect(
value.threads[0]?.registers.find(({ name }) => name === "rdi")?.value,
).toBe("0x1122334455667788");
expect(value.live_process_identity).toBe("unknown");
expect(
inspectRecordedCrashInputSchema.parse({ path: "/selected.core" })
.include_debugger_context,
).toBe(false);
});
it("preserves a short zero-filled note-segment tail", () => {
const value = recordedCrashSignalFixture();
value.segments = value.segments.map((segment) => ({
...segment,
file_size: "0x19b",
}));
value.note_padding.push({
segment_index: 0,
location: { offset: "0x218", bytes: "0x3" },
bytes_base64: "AAAA",
});
expect(recordedCrashSchema.safeParse(value).success).toBe(true);
});
it.each([
"missing-thread",
"duplicate-thread",
"missing-signal",
"duplicate-signal",
"missing-register",
"unknown-register",
"duplicated-physical-thread",
"duplicated-physical-signal",
"omitted-physical-note",
"expanded-note-span",
"forged-padding",
])("rejects an incomplete or duplicate interpretation: %s", (scenario) => {
const value = recordedCrashSignalFixture();
if (
scenario === "duplicated-physical-thread" ||
scenario === "duplicated-physical-signal"
) {
const noteIndex = scenario === "duplicated-physical-thread" ? 0 : 1;
const note = value.notes[noteIndex];
if (note === undefined) throw new Error("missing fixture note");
value.notes.push({ ...note, index: 2 });
if (noteIndex === 0)
value.threads.push(
...value.threads.map((thread) => ({ ...thread, note_index: 2 })),
);
else
value.signals.push(
...value.signals.map((signal) => ({ ...signal, note_index: 2 })),
);
}
if (
["omitted-physical-note", "expanded-note-span", "forged-padding"].includes(
scenario,
)
) {
value.notes = value.notes.filter((note) => note.index === 0);
value.signals = [];
}
if (scenario === "expanded-note-span")
value.notes = value.notes.map((note) => ({
...note,
location: { ...note.location, bytes: "0x198" },
}));
if (scenario === "forged-padding")
value.note_padding.push({
segment_index: 0,
location: { offset: "0x1e4", bytes: "0x34" },
bytes_base64: Buffer.alloc(52).toString("base64"),
});
if (scenario === "missing-thread") value.threads = [];
if (scenario === "duplicate-thread")
value.threads = [...value.threads, ...value.threads];
if (scenario === "missing-signal") value.signals = [];
if (scenario === "duplicate-signal")
value.signals = [...value.signals, ...value.signals];
if (scenario === "missing-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.slice(1),
}));
if (scenario === "unknown-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register) =>
register.name === "rdi"
? { ...register, name: "unrecognized" }
: register,
),
}));
expect(recordedCrashSchema.safeParse(value).success).toBe(false);
});
it.each([
[
"unsafe register number",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: 9007199254740992,
location: { offset: "0x104", bytes: "0x8" },
},
],
},
],
}),
],
[
"source outside artifact",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
artifact: { ...v.artifact, bytes: 120 },
}),
],
[
"invalid note reference",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [{ ...v.threads[0], note_index: 1 }],
}),
],
[
"register outside descriptor",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: "0x0",
location: { offset: "0x1e4", bytes: "0x8" },
},
],
},
],
}),
],
[
"raw descriptor length",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, descriptor_bytes_base64: "AA==" })),
}),
],
[
"different owner ABI",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, owner_display: "OTHER" })),
}),
],
[
"raw owner ABI hidden by a CORE display label",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({
...n,
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
}),
],
[
"duplicate register",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: v.threads.map((t) => ({
...t,
registers: [...t.registers, ...t.registers],
})),
}),
],
] as const)("rejects %s before Evidence serialization", (_name, change) =>
expect(
recordedCrashSchema.safeParse(change(recordedCrashFixture())).success,
).toBe(false),
);
it("does not interpret a signal through a mislabeled raw owner ABI", () => {
const value = recordedCrashFixture();
expect(
recordedCrashSchema.safeParse({
...value,
threads: [],
notes: value.notes.map((note) => ({
...note,
type: "NT_SIGINFO",
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
signals: [
{
note_index: 0,
number: 11,
code: 1,
errno: 0,
fault_address: "0x123",
fault_address_meaning: "recorded-sigsegv-address",
thread_association: "unknown",
},
],
}).success,
).toBe(false);
});
it("keeps absent map flags unknown and validates reported permission bits", () => {
const value = recordedCrashFixture();
const context = {
status: "available",
gdb_version: "fixture",
pwndbg_version: "fixture",
connection: "core",
executable: null,
historical_pid: 123,
reported_limits: {
address_space_bytes: 3221225472,
cpu_seconds: 30,
file_size_bytes: 67108864,
},
maps: [
{
start: "0x1000",
end: "0x2000",
offset: "0x0",
reported_flags: 0,
permissions: null,
pathname_display: "recorded pathname",
current_file_identity: "unknown",
},
],
confidence: "derived",
completeness: "unknown",
diagnostics: value.diagnostics,
} as const;
expect(
recordedCrashSchema.safeParse({ ...value, debugger: context }).success,
).toBe(true);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
reported_flags: 4,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
});
+362
View File
@@ -0,0 +1,362 @@
import { z } from "zod";
import { recordedNoteCoverageIssues } from "./recordedCrashNoteCoverage.js";
const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const signed32 = z.number().int().min(-2147483648).max(2147483647);
const base64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const range = z.strictObject({ offset: hex, bytes: hex });
const diagnostics = z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
});
// Exact b"CORE\0"; a lossy display label cannot establish the Linux note ABI.
const LINUX_CORE_OWNER_BASE64 = "Q09SRQA=";
/** Complete register identities in the supported Linux amd64 PRSTATUS ABI order. */
export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
"r15",
"r14",
"r13",
"r12",
"rbp",
"rbx",
"r11",
"r10",
"r9",
"r8",
"rax",
"rcx",
"rdx",
"rsi",
"rdi",
"orig_rax",
"rip",
"cs",
"eflags",
"rsp",
"ss",
"fs_base",
"gs_base",
"ds",
"es",
"fs",
"gs",
];
const supportedRegisters = new Set(RECORDED_LINUX_AMD64_REGISTERS);
/** Select an explicit recording and optionally request debugger-derived mapping context. */
export const inspectRecordedCrashInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to a supplied Linux ELF core"),
include_debugger_context: z
.boolean()
.default(false)
.describe(
"Add core-only mapping candidates through caller-supplied GDB/pwndbg",
),
});
/** Debugger map candidates preserve reported flags; zero does not establish absent permissions. */
export const recordedCrashDebuggerSchema = z.discriminatedUnion("status", [
z.strictObject({ status: z.literal("not-requested") }),
z.strictObject({
status: z.literal("available"),
gdb_version: z.string().min(1),
pwndbg_version: z.string().min(1),
connection: z.literal("core"),
executable: z.null(),
historical_pid: signed32,
reported_limits: z.strictObject({
address_space_bytes: index,
cpu_seconds: index,
file_size_bytes: index,
}),
maps: z.array(
z.strictObject({
start: hex,
end: hex,
offset: hex,
reported_flags: index,
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
pathname_display: z.string(),
current_file_identity: z.literal("unknown"),
}),
),
confidence: z.literal("derived"),
completeness: z.literal("unknown"),
diagnostics,
}),
]);
/** Portable recorded observations; registers and source coordinates remain lossless. */
const recordedCrashObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf-core"),
architecture: z.literal("x86_64-little-endian"),
target_execution: z.literal("not-performed"),
live_process_identity: z.literal("unknown"),
segments: z.array(
z.strictObject({
index,
type: z.union([z.string(), index]),
header_location: range,
offset: hex,
file_size: hex,
memory_size: hex,
virtual_address: hex,
physical_address: hex,
alignment: hex,
flags: hex,
file_backing: z.enum(["file", "none"]),
}),
),
notes: z.array(
z.strictObject({
index,
segment_index: index,
type: z.union([z.string(), index]),
location: range,
owner_location: range,
owner_bytes_base64: base64,
owner_display: z.string().nullable(),
descriptor_location: range,
descriptor_bytes_base64: base64,
}),
),
note_padding: z.array(
z.strictObject({
segment_index: index,
location: range,
bytes_base64: base64,
}),
),
threads: z.array(
z.strictObject({
note_index: index,
historical_pid: signed32,
recorded_current_signal: z.number().int().min(-32768).max(32767),
registers: z.array(
z.strictObject({
name: z.string().min(1),
value: hex,
location: range,
}),
),
}),
),
signals: z.array(
z.strictObject({
note_index: index,
number: signed32,
code: signed32,
errno: signed32,
fault_address: hex.nullable(),
fault_address_meaning: z.enum(["recorded-sigsegv-address", "unknown"]),
thread_association: z.literal("unknown"),
}),
),
debugger: recordedCrashDebuggerSchema,
note_interpretation_completeness: z.literal("unknown"),
decoder_diagnostics: diagnostics,
diagnostics,
limitations: z.array(z.string()),
});
/** Provider payload excludes identity and diagnostics bound by the owned snapshot boundary. */
export const recordedCrashPayloadSchema = recordedCrashObjectSchema.omit({
artifact: true,
diagnostics: true,
debugger: true,
decoder_diagnostics: true,
});
/** Validate the next consumer's file ranges, note links and register representations. */
export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
(value, context) => {
const fail = (message: string) =>
context.addIssue({ code: "custom", message });
const within = (
item: z.output<typeof range>,
start = 0n,
end = BigInt(value.artifact.bytes),
) => {
const offset = BigInt(item.offset);
const bytes = BigInt(item.bytes);
return offset >= start && offset <= end && bytes <= end - offset;
};
for (const issue of recordedNoteCoverageIssues(
value.segments,
value.notes,
value.note_padding,
))
fail(issue);
for (const [position, segment] of value.segments.entries()) {
if (position !== segment.index || !within(segment.header_location))
fail("Invalid original segment identity or header range.");
if (
segment.file_backing === "file" &&
!within({ offset: segment.offset, bytes: segment.file_size })
)
fail("Recorded segment exceeds artifact bytes.");
if (
segment.type === "PT_LOAD" &&
BigInt(segment.file_size) > BigInt(segment.memory_size)
)
fail("Recorded PT_LOAD file size exceeds memory size.");
}
for (const [position, note] of value.notes.entries()) {
const segment = value.segments[note.segment_index];
if (position !== note.index || segment?.type !== "PT_NOTE") {
fail("Invalid original note identity or segment reference.");
continue;
}
const decodedLength = (raw: string) =>
BigInt(
(raw.length / 4) * 3 -
(raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0),
);
if (
decodedLength(note.owner_bytes_base64) !==
BigInt(note.owner_location.bytes) ||
decodedLength(note.descriptor_bytes_base64) !==
BigInt(note.descriptor_location.bytes)
)
fail("Raw note lengths differ from their source ranges.");
const start = BigInt(segment.offset);
const end = start + BigInt(segment.file_size);
if (
!within(note.location, start, end) ||
!within(
note.owner_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
) ||
!within(
note.descriptor_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
)
)
fail("Note source ranges exceed their recorded segment.");
}
for (const padding of value.note_padding) {
const segment = value.segments[padding.segment_index];
if (
segment?.type !== "PT_NOTE" ||
!within(
padding.location,
BigInt(segment.offset),
BigInt(segment.offset) + BigInt(segment.file_size),
)
)
fail("Invalid recorded note padding range.");
}
for (const [kind, rows] of [
["NT_PRSTATUS", value.threads],
["NT_SIGINFO", value.signals],
] as const) {
const matchingNotes = value.notes.filter(
(note) =>
note.type === kind &&
note.owner_bytes_base64 === LINUX_CORE_OWNER_BASE64,
);
if (
rows.length !== matchingNotes.length ||
new Set(rows.map(({ note_index }) => note_index)).size !== rows.length
)
fail(
"Each supported raw note requires exactly one corresponding interpretation.",
);
}
for (const thread of value.threads) {
const note = value.notes[thread.note_index];
if (
note?.type !== "NT_PRSTATUS" ||
note.owner_display !== "CORE" ||
note.owner_bytes_base64 !== LINUX_CORE_OWNER_BASE64
) {
fail("Thread references a different note kind.");
continue;
}
if (
thread.registers.length !== RECORDED_LINUX_AMD64_REGISTERS.length ||
!thread.registers.every(({ name }) => supportedRegisters.has(name)) ||
new Set(thread.registers.map(({ name }) => name)).size !==
thread.registers.length
)
fail(
"Each recorded thread requires every supported register exactly once.",
);
for (const register of thread.registers)
if (
BigInt(register.location.bytes) !== 8n ||
!within(
register.location,
BigInt(note.descriptor_location.offset),
BigInt(note.descriptor_location.offset) +
BigInt(note.descriptor_location.bytes),
)
)
fail("Register source exceeds its descriptor.");
}
for (const signal of value.signals) {
if (
value.notes[signal.note_index]?.type !== "NT_SIGINFO" ||
value.notes[signal.note_index]?.owner_display !== "CORE" ||
value.notes[signal.note_index]?.owner_bytes_base64 !==
LINUX_CORE_OWNER_BASE64
)
fail("Signal references a different note kind.");
const known =
signal.number === 11 && (signal.code === 1 || signal.code === 2);
if (
known !== (signal.fault_address !== null) ||
(signal.fault_address !== null) !==
(signal.fault_address_meaning === "recorded-sigsegv-address")
)
fail("Signal union meaning does not match recorded SIGSEGV code.");
}
if (value.debugger.status === "available")
for (const map of value.debugger.maps) {
if (BigInt(map.end) < BigInt(map.start))
fail("Debugger mapping end precedes its start.");
if (
map.permissions !== null &&
(map.permissions.read !== Boolean(map.reported_flags & 4) ||
map.permissions.write !== Boolean(map.reported_flags & 2) ||
map.permissions.execute !== Boolean(map.reported_flags & 1))
)
fail("Mapping permissions differ from reported flags.");
if (
(map.reported_flags === 0 || map.reported_flags > 7) !==
(map.permissions === null)
)
fail(
"Unreported or unfamiliar map flags require unknown permissions.",
);
}
},
);
export type InspectRecordedCrashInput = z.output<
typeof inspectRecordedCrashInputSchema
>;
export type RecordedCrash = z.output<typeof recordedCrashSchema>;
@@ -0,0 +1,111 @@
type Range = { readonly offset: string; readonly bytes: string };
type Segment = {
readonly index: number;
readonly type: string | number;
readonly offset: string;
readonly file_size: string;
};
type Note = {
readonly segment_index: number;
readonly location: Range;
readonly owner_location: Range;
readonly descriptor_location: Range;
};
type Padding = {
readonly segment_index: number;
readonly location: Range;
readonly bytes_base64: string;
};
const align = (size: bigint) => ((size + 3n) / 4n) * 4n;
const layoutMatches = (note: Note): boolean => {
const start = BigInt(note.location.offset);
const owner = BigInt(note.owner_location.bytes);
const descriptor = BigInt(note.descriptor_location.bytes);
return (
BigInt(note.owner_location.offset) === start + 12n &&
BigInt(note.descriptor_location.offset) === start + 12n + align(owner) &&
BigInt(note.location.bytes) === 12n + align(owner) + align(descriptor)
);
};
const paddingMatches = (
item: Padding,
segment: Segment | undefined,
): boolean => {
const bytes = BigInt(item.location.bytes);
const decodedLength =
(item.bytes_base64.length / 4) * 3 -
(item.bytes_base64.endsWith("==")
? 2
: item.bytes_base64.endsWith("=")
? 1
: 0);
return (
bytes > 0n &&
bytes < 12n &&
BigInt(decodedLength) === bytes &&
/^A*={0,2}$/.test(item.bytes_base64) &&
segment !== undefined &&
BigInt(item.location.offset) + bytes ===
BigInt(segment.offset) + BigInt(segment.file_size)
);
};
/** Require exact aligned note layouts and one complete, nonoverlapping physical coverage. */
export function recordedNoteCoverageIssues(
segments: readonly Segment[],
notes: readonly Note[],
padding: readonly Padding[],
): readonly string[] {
const issues: string[] = [];
const bySegment = new Map<number, Range[]>();
const all: Range[] = [];
const add = (segment: number, range: Range) => {
const ranges = bySegment.get(segment) ?? [];
ranges.push(range);
bySegment.set(segment, ranges);
all.push(range);
};
for (const note of notes) {
if (!layoutMatches(note))
issues.push(
"Recorded note layout differs from its aligned header/owner/descriptor ranges.",
);
add(note.segment_index, note.location);
}
for (const item of padding) {
if (!paddingMatches(item, segments[item.segment_index]))
issues.push(
"Recorded note padding must be a short zero-filled segment tail.",
);
add(item.segment_index, item.location);
}
const compare = (left: Range, right: Range) =>
BigInt(left.offset) < BigInt(right.offset)
? -1
: BigInt(left.offset) > BigInt(right.offset)
? 1
: 0;
let end = 0n;
for (const range of all.sort(compare)) {
const start = BigInt(range.offset);
if (start < end)
issues.push("Physical recorded note/padding ranges overlap or repeat.");
if (start + BigInt(range.bytes) > end) end = start + BigInt(range.bytes);
}
for (const segment of segments) {
if (segment.type !== "PT_NOTE") continue;
let cursor = BigInt(segment.offset);
for (const range of (bySegment.get(segment.index) ?? []).sort(compare)) {
if (BigInt(range.offset) !== cursor)
issues.push(
"Recorded note/padding ranges leave a gap or overlap in their segment.",
);
cursor = BigInt(range.offset) + BigInt(range.bytes);
}
if (cursor !== BigInt(segment.offset) + BigInt(segment.file_size))
issues.push(
"Recorded note/padding ranges do not completely cover their segment.",
);
}
return issues;
}
-95
View File
@@ -1,95 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyResource,
detectPackageFormat,
hasValidSignature,
isConfigurationResource,
isManifestResource,
resourcesByType,
totalResourceSize,
type PackageManifest,
} from "./packageAnalysis.js";
describe("package analysis", () => {
it("detects package format from extension", () => {
expect(detectPackageFormat("app.msix")).toBe("msix");
expect(detectPackageFormat("installer.msi")).toBe("msi");
expect(detectPackageFormat("app.appx")).toBe("appx");
expect(detectPackageFormat("app.zip")).toBeNull();
});
it("identifies manifest resources", () => {
expect(isManifestResource("AppXManifest.xml")).toBe(true);
expect(isManifestResource("resources.pri")).toBe(false);
});
it("identifies configuration resources", () => {
expect(isConfigurationResource("settings.xml")).toBe(true);
expect(isConfigurationResource("config.json")).toBe(true);
expect(isConfigurationResource("app.exe")).toBe(false);
});
it("classifies resources by path", () => {
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
expect(classifyResource("icon.png")).toBe("icon");
expect(classifyResource("settings.xml")).toBe("configuration");
expect(classifyResource("cert.cer")).toBe("certificate");
expect(classifyResource("app.exe")).toBe("executable");
expect(classifyResource("lib.dll")).toBe("library");
expect(classifyResource("data.bin")).toBe("other");
});
const validManifest: PackageManifest = {
format: "msix",
name: "TestApp",
publisher: "CN=TestPublisher",
version: "1.0.0.0",
architecture: "x64",
resources: [
{
path: "AppXManifest.xml",
type: "manifest",
size: 1000,
digest: "a".repeat(64),
},
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
{
path: "app.exe",
type: "executable",
size: 50000,
digest: "c".repeat(64),
},
],
signature: {
is_signed: true,
signer_subject: "CN=TestPublisher",
certificate_thumbprint: "abc123",
is_valid: true,
is_timestamped: true,
timestamp_signer: "CN=Timestamp",
},
is_framework: false,
dependencies: ["Microsoft.VCLibs.14.00"],
capabilities: ["internetClient", "localNetwork"],
};
it("filters resources by type", () => {
const icons = resourcesByType(validManifest, "icon");
expect(icons).toHaveLength(1);
expect(icons[0]!.path).toBe("icon.png");
});
it("computes total resource size", () => {
expect(totalResourceSize(validManifest)).toBe(56000);
});
it("checks valid signature", () => {
expect(hasValidSignature(validManifest)).toBe(true);
const unsigned: PackageManifest = {
...validManifest,
signature: { ...validManifest.signature, is_valid: false },
};
expect(hasValidSignature(unsigned)).toBe(false);
});
});
-143
View File
@@ -1,143 +0,0 @@
import { z } from "zod";
/** Supported Windows package formats. */
export const packageFormatSchema = z.enum(["msix", "msi", "appx"]);
export type PackageFormat = z.infer<typeof packageFormatSchema>;
/** A resource entry within a package. */
export const packageResourceSchema = z.strictObject({
/** Resource path within the package. */
path: z.string().min(1),
/** Resource type. */
type: z.enum([
"manifest",
"icon",
"configuration",
"certificate",
"executable",
"library",
"data",
"other",
]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type PackageResource = z.infer<typeof packageResourceSchema>;
/** Digital signature information. */
export const digitalSignatureSchema = z.strictObject({
/** Whether the package is signed. */
is_signed: z.boolean(),
/** Signer subject name. */
signer_subject: z.string().nullable(),
/** Certificate thumbprint. */
certificate_thumbprint: z.string().nullable(),
/** Whether the signature is valid. */
is_valid: z.boolean().default(false),
/** Whether the signature is timestamped. */
is_timestamped: z.boolean().default(false),
/** Timestamp signer if present. */
timestamp_signer: z.string().nullable(),
});
/** A Windows package manifest for static analysis. */
export const packageManifestSchema = z.strictObject({
/** Package format. */
format: packageFormatSchema,
/** Package identity name. */
name: z.string().min(1),
/** Package publisher. */
publisher: z.string().nullable(),
/** Package version. */
version: z.string().nullable(),
/** Architecture. */
architecture: z.enum(["x86", "x64", "arm", "arm64", "neutral", "unknown"]),
/** Package resources. */
resources: z.array(packageResourceSchema).default([]),
/** Digital signature. */
signature: digitalSignatureSchema,
/** Whether the package is a framework. */
is_framework: z.boolean().default(false),
/** Package dependencies. */
dependencies: z.array(z.string()).default([]),
/** Capabilities declared in the manifest. */
capabilities: z.array(z.string()).default([]),
});
export type PackageManifest = z.infer<typeof packageManifestSchema>;
/** Detect package format from file extension. */
export function detectPackageFormat(path: string): PackageFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".msix")) return "msix";
if (lower.endsWith(".msi")) return "msi";
if (lower.endsWith(".appx")) return "appx";
return null;
}
/** Check if a resource path looks like a manifest. */
export function isManifestResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.includes("appxmanifest.xml") ||
lower.includes("appxmanifest") ||
lower.includes("manifest.xml") ||
lower.endsWith("_manifest.xml")
);
}
/** Check if a resource path looks like a configuration file. */
export function isConfigurationResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.endsWith(".xml") ||
lower.endsWith(".json") ||
lower.endsWith(".ini") ||
lower.endsWith(".config")
);
}
/** Classify a resource by its path. */
export function classifyResource(path: string): PackageResource["type"] {
if (isManifestResource(path)) return "manifest";
const lower = path.toLowerCase();
if (
lower.endsWith(".ico") ||
lower.endsWith(".png") ||
lower.endsWith(".jpg") ||
lower.endsWith(".jpeg")
)
return "icon";
if (isConfigurationResource(path)) return "configuration";
if (
lower.endsWith(".cer") ||
lower.endsWith(".pfx") ||
lower.endsWith(".p12")
)
return "certificate";
if (lower.endsWith(".exe") || lower.endsWith(".dll"))
return lower.endsWith(".exe") ? "executable" : "library";
return "other";
}
/** Get all resources of a specific type. */
export function resourcesByType(
manifest: PackageManifest,
type: PackageResource["type"],
): PackageResource[] {
return manifest.resources.filter((r) => r.type === type);
}
/** Get the total size of all resources. */
export function totalResourceSize(manifest: PackageManifest): number {
return manifest.resources.reduce((sum, r) => sum + r.size, 0);
}
/** Check if a package has a valid signature. */
export function hasValidSignature(manifest: PackageManifest): boolean {
return manifest.signature.is_signed && manifest.signature.is_valid;
}
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
countExecutableSections,
getExportedFunctions,
getImportedDlls,
hasPdbInfo,
parseDebugType,
parseImageCharacteristics,
parseMachineType,
parseSectionCharacteristics,
peManifestSchema,
type PeManifest,
} from "./peInspection.js";
const validManifest: PeManifest = {
dos_magic: 0x5a4d,
pe_signature: 0x00004550,
machine: "x64",
number_of_sections: 3,
timestamp: 0x12345678,
is_dll: false,
is_executable: true,
is_console: true,
entry_point: 0x1000,
image_base: 0x400000,
section_alignment: 0x1000,
subsystem_version: "10.0",
sections: [
{
name: ".text",
virtual_size: 0x1000,
virtual_address: 0x1000,
raw_size: 0x1000,
raw_offset: 0x400,
characteristics: {
has_code: true,
has_initialized_data: false,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: true,
},
},
{
name: ".data",
virtual_size: 0x500,
virtual_address: 0x2000,
raw_size: 0x500,
raw_offset: 0x1400,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: true,
executable: false,
},
},
{
name: ".rdata",
virtual_size: 0x200,
virtual_address: 0x3000,
raw_size: 0x200,
raw_offset: 0x1900,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: false,
},
},
],
imports: [
{
dll: "KERNEL32.DLL",
function_name: "CreateFileW",
ordinal: null,
is_delay_import: false,
},
{
dll: "KERNEL32.DLL",
function_name: "WriteFile",
ordinal: null,
is_delay_import: false,
},
{
dll: "USER32.DLL",
function_name: "MessageBoxW",
ordinal: 100,
is_delay_import: false,
},
],
exports: [
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
],
resources: [
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
],
debug_entries: [
{
type: "CODEVIEW",
rva: 0x5000,
size: 100,
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
pdb_age: 1,
pdb_path: "C:\\src\\app.pdb",
},
],
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
relocations_count: 50,
image_characteristics: ["Executable", "Console"],
};
describe("PE/COFF static inspection", () => {
it("parses machine types", () => {
expect(parseMachineType(0x014c)).toBe("x86");
expect(parseMachineType(0x8664)).toBe("x64");
expect(parseMachineType(0x01c0)).toBe("arm");
expect(parseMachineType(0xaa64)).toBe("arm64");
expect(parseMachineType(0x0200)).toBe("ia64");
expect(parseMachineType(0xffff)).toBe("unknown");
});
it("parses section characteristics", () => {
const CODE = 0x00000020;
const READ = 0x40000000;
const EXECUTE = 0x20000000;
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
expect(result.has_code).toBe(true);
expect(result.readable).toBe(true);
expect(result.executable).toBe(true);
expect(result.writable).toBe(false);
});
it("parses image characteristics", () => {
const DLL = 0x2000;
const EXEC = 0x0002;
const flags = parseImageCharacteristics(DLL | EXEC);
expect(flags).toContain("DLL");
expect(flags).toContain("Executable");
});
it("parses debug types", () => {
expect(parseDebugType(2)).toBe("CODEVIEW");
expect(parseDebugType(1)).toBe("COFF");
expect(parseDebugType(99)).toBe("UNKNOWN");
});
it("rejects a manifest whose section table is malformed", () => {
const malformed = {
...validManifest,
sections: [{ ...validManifest.sections[0]!, name: 7 }],
};
const result = peManifestSchema.safeParse(malformed);
expect(result.success).toBe(false);
});
it("accepts static manifests with more than 96 PE sections", () => {
const section = validManifest.sections[0];
if (section === undefined) throw new Error("Expected PE section fixture");
const sections = Array.from({ length: 97 }, (_, index) => ({
...section,
name: `section-${String(index)}`,
}));
expect(
peManifestSchema.parse({
...validManifest,
number_of_sections: sections.length,
sections,
}).sections,
).toHaveLength(97);
});
it("detects PDB info", () => {
expect(hasPdbInfo(validManifest)).toBe(true);
const withoutPdb: PeManifest = {
...validManifest,
debug_entries: [
{
type: "COFF",
rva: 0x5000,
size: 100,
pdb_guid: null,
pdb_age: null,
pdb_path: null,
},
],
};
expect(hasPdbInfo(withoutPdb)).toBe(false);
});
it("gets imported DLLs", () => {
const dlls = getImportedDlls(validManifest);
expect(dlls).toHaveLength(2);
expect(dlls).toContain("KERNEL32.DLL");
expect(dlls).toContain("USER32.DLL");
});
it("gets exported functions", () => {
const exports = getExportedFunctions(validManifest);
expect(exports).toHaveLength(2);
expect(exports).toContain("DllMain");
expect(exports).toContain("MyFunction");
});
it("counts executable sections", () => {
expect(countExecutableSections(validManifest)).toBe(1);
});
});
-220
View File
@@ -1,220 +0,0 @@
import { z } from "zod";
/** PE/COFF section characteristics flags. */
export const sectionCharacteristicsSchema = z.object({
/** Section contains executable code. */
has_code: z.boolean().default(false),
/** Section contains initialized data. */
has_initialized_data: z.boolean().default(false),
/** Section contains uninitialized data. */
has_uninitialized_data: z.boolean().default(false),
/** Section can be read. */
readable: z.boolean().default(false),
/** Section can be written. */
writable: z.boolean().default(false),
/** Section can be executed. */
executable: z.boolean().default(false),
});
/** PE/COFF section header. */
export const peSectionSchema = z.strictObject({
name: z.string().min(1),
virtual_size: z.number().int().nonnegative(),
virtual_address: z.number().int().nonnegative(),
raw_size: z.number().int().nonnegative(),
raw_offset: z.number().int().nonnegative(),
characteristics: sectionCharacteristicsSchema,
});
/** PE import entry. */
export const peImportSchema = z.strictObject({
dll: z.string().min(1),
function_name: z.string().min(1),
ordinal: z.number().int().nullable(),
is_delay_import: z.boolean().default(false),
});
/** PE export entry. */
export const peExportSchema = z.strictObject({
name: z.string().min(1),
ordinal: z.number().int().nonnegative(),
rva: z.number().int().nonnegative(),
forwarder: z.string().nullable(),
});
/** PE/COFF resource entry. */
export const peResourceSchema = z.strictObject({
type: z.string().min(1),
name: z.string().nullable(),
language: z.number().int().nullable(),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
});
/** PE debug directory entry. */
export const peDebugEntrySchema = z.strictObject({
type: z.string().min(1),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
/** PDB GUID if this is a CodeView entry. */
pdb_guid: z.string().nullable(),
/** PDB age if this is a CodeView entry. */
pdb_age: z.number().int().nullable(),
/** PDB path if this is a CodeView entry. */
pdb_path: z.string().nullable(),
});
/** TLS callback entry. */
export const peTlsCallbackSchema = z.strictObject({
callback_rva: z.number().int().nonnegative(),
index: z.number().int().nonnegative(),
});
/** Architecture/machine type. */
export const peMachineTypeSchema = z.enum([
"x86",
"x64",
"arm",
"arm64",
"ia64",
"unknown",
]);
export type PeMachineType = z.infer<typeof peMachineTypeSchema>;
/** PE/COFF manifest for static inspection. */
export const peManifestSchema = z.strictObject({
/** DOS header magic. */
dos_magic: z.literal(0x5a4d),
/** PE signature. */
pe_signature: z.literal(0x00004550),
/** Machine type. */
machine: peMachineTypeSchema,
/** Number of sections. */
number_of_sections: z.number().int().positive(),
/** Timestamp from the COFF header. */
timestamp: z.number().int().nullable(),
/** PE characteristics flags. */
is_dll: z.boolean().default(false),
is_executable: z.boolean().default(false),
is_console: z.boolean().default(true),
/** Entry point RVA. */
entry_point: z.number().int().nonnegative(),
/** Image base. */
image_base: z.number().int().nonnegative(),
/** Section alignment. */
section_alignment: z.number().int().positive(),
/** Subsystem version. */
subsystem_version: z.string().nullable(),
/** Sections. */
sections: z.array(peSectionSchema),
/** Imports. */
imports: z.array(peImportSchema).default([]),
/** Exports. */
exports: z.array(peExportSchema).default([]),
/** Resources. */
resources: z.array(peResourceSchema).default([]),
/** Debug directory entries. */
debug_entries: z.array(peDebugEntrySchema).default([]),
/** TLS callbacks. */
tls_callbacks: z.array(peTlsCallbackSchema).default([]),
/** Relocations count (not all entries). */
relocations_count: z.number().int().nonnegative().default(0),
/** Image file characteristics. */
image_characteristics: z.array(z.string()).default([]),
});
export type PeManifest = z.infer<typeof peManifestSchema>;
/** Parse machine type from COFF machine field. */
export function parseMachineType(machine: number): PeMachineType {
switch (machine) {
case 0x014c:
return "x86";
case 0x8664:
return "x64";
case 0x01c0:
case 0x01c2:
case 0x01c4:
return "arm";
case 0xaa64:
return "arm64";
case 0x0200:
return "ia64";
default:
return "unknown";
}
}
/** Parse section characteristics flags. */
export function parseSectionCharacteristics(
characteristics: number,
): z.infer<typeof sectionCharacteristicsSchema> {
const IMAGE_SCN_CNT_CODE = 0x00000020;
const IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040;
const IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080;
const IMAGE_SCN_MEM_READ = 0x40000000;
const IMAGE_SCN_MEM_WRITE = 0x80000000;
const IMAGE_SCN_MEM_EXECUTE = 0x20000000;
return {
has_code: (characteristics & IMAGE_SCN_CNT_CODE) !== 0,
has_initialized_data:
(characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) !== 0,
has_uninitialized_data:
(characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) !== 0,
readable: (characteristics & IMAGE_SCN_MEM_READ) !== 0,
writable: (characteristics & IMAGE_SCN_MEM_WRITE) !== 0,
executable: (characteristics & IMAGE_SCN_MEM_EXECUTE) !== 0,
};
}
/** Parse image characteristics flags. */
export function parseImageCharacteristics(characteristics: number): string[] {
const IMAGE_DLL = 0x2000;
const IMAGE_EXECUTABLE = 0x0002;
const IMAGE_CONSOLE = 0x0003;
const flags: string[] = [];
if (characteristics & IMAGE_DLL) flags.push("DLL");
if (characteristics & IMAGE_EXECUTABLE) flags.push("Executable");
if ((characteristics & 0x0000000f) === IMAGE_CONSOLE) flags.push("Console");
return flags;
}
/** Parse a PE debug directory type. */
export function parseDebugType(type: number): string {
switch (type) {
case 0:
return "UNKNOWN";
case 1:
return "COFF";
case 2:
return "CODEVIEW";
case 3:
return "POGO";
case 4:
return "MISC";
default:
return "UNKNOWN";
}
}
/** Check if a PE manifest has PDB debug info. */
export function hasPdbInfo(manifest: PeManifest): boolean {
return manifest.debug_entries.some(
(e) => e.pdb_guid !== null && e.pdb_path !== null,
);
}
/** Get all imported DLLs from a PE manifest. */
export function getImportedDlls(manifest: PeManifest): string[] {
return [...new Set(manifest.imports.map((i) => i.dll))];
}
/** Get all exported function names from a PE manifest. */
export function getExportedFunctions(manifest: PeManifest): string[] {
return manifest.exports.map((e) => e.name);
}
/** Count executable sections. */
export function countExecutableSections(manifest: PeManifest): number {
return manifest.sections.filter((s) => s.characteristics.executable).length;
}
@@ -0,0 +1,160 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("distinguishes added evidence from unknown observations", () => {
const capture = emptyCapture();
const added = compareProcessCaptures(capture, {
...capture,
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
rendered_frames: [
{
sequence: 0,
at_ms: 0,
columns: 3,
rows: 1,
cursor_x: 3,
cursor_y: 0,
active_buffer: "normal",
lines: ["new"],
serialized_state: "new",
},
],
});
expect(added).toMatchObject({ terminal: "added", status: "changed" });
for (const [scope, dimension] of [
["process", "process"],
["interaction", "interaction"],
] as const) {
expect(
compareProcessCaptures(
{
...capture,
residual_unknowns: [{ scope, reason: "observation was partial" }],
},
capture,
),
).toMatchObject({
status: "unknown",
[dimension]: "unknown",
terminal: "unchanged",
});
}
});
it("compares raw terminal and process observations while honoring normalization shape", () => {
const capture = emptyCapture();
expect(
compareProcessCaptures(capture, {
...capture,
normalization: {
patterns: [],
time_bucket_ms: 10,
ports: true,
pids: true,
paths: true,
},
}),
).toMatchObject({
status: "unchanged",
first_divergence: { status: "none" },
});
const terminal = compareProcessCaptures(
{ ...capture, frames: [{ sequence: 0, at_ms: 0, data: "bar" }] },
{ ...capture, frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }] },
);
expect(terminal).toMatchObject({
terminal: "changed",
first_divergence: { status: "found", dimension: "terminal" },
});
expect(
compareProcessCaptures(
{
...capture,
process_samples: [
{
at_ms: 10,
pid: 1,
parent_pid: 0,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
},
{
...capture,
process_samples: [
{
at_ms: 20,
pid: 1,
parent_pid: 2,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
},
),
).toMatchObject({ process: "changed", status: "changed" });
});
it("keeps filesystem comparison unknown without coverage and reports observed changes", () => {
const capture = emptyCapture();
const incomplete = {
...capture,
residual_unknowns: [
{ scope: "filesystem" as const, reason: "watcher unavailable" },
],
};
expect(compareProcessCaptures(incomplete, incomplete)).toMatchObject({
filesystem: "unknown",
status: "unknown",
});
const finalFile = {
path: "root_0:created.txt",
type: "file" as const,
mode: 0o644,
size: 4,
sha256: "a".repeat(64),
symlink_target: null,
};
expect(
compareProcessCaptures(capture, {
...capture,
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "after_settlement",
at_ms: 10,
files: [finalFile],
effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
truncated: false,
},
],
files_after: [finalFile],
filesystem_effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
}),
).toMatchObject({ filesystem: "changed", status: "changed" });
});

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