Merge origin/main for artifact admission and evidence fixes

This commit is contained in:
64579525
2026-10-13 14:32:52 +08:00
188 changed files with 8882 additions and 937 deletions
+47 -1
View File
@@ -96,6 +96,7 @@ const decodeStub = (
readonly withStrings?: boolean;
readonly withGerman?: boolean;
readonly failDecode?: boolean;
readonly ymlFile?: string;
readonly manifestFile?: string;
readonly stringsFile?: string;
readonly stringsXml?: string;
@@ -104,6 +105,10 @@ const decodeStub = (
const withStrings = options.withStrings ?? true;
const withGerman = options.withGerman ?? true;
const stringsXml = options.stringsXml ?? REAL_STRINGS;
const ymlWrite =
options.ymlFile === undefined
? `printf '%s\\n' '${REAL_YML.replace(/'/gu, "'\\''")}' > "$5/apktool.yml"`
: `cp '${options.ymlFile}' "$5/apktool.yml"`;
const manifestWrite =
options.manifestFile === undefined
? `printf '%s\\n' '${REAL_MANIFEST.replace(/'/gu, "'\\''")}' > "$5/AndroidManifest.xml"`
@@ -117,7 +122,7 @@ if [ "$1" = "d" ]; then
${
options.failDecode === true
? `printf 'Exception in thread "main" brut.androlib.AndrolibException: Could not decode the APK\\n' >&2; exit 1;`
: `printf '%s\\n' '${REAL_YML.replace(/'/gu, "'\\''")}' > "$5/apktool.yml"
: `${ymlWrite}
${manifestWrite}
mkdir -p "$5/res/values"${withGerman ? ' "$5/res/values-de"' : ""}
${withStrings ? stringsWrite : ""}
@@ -192,6 +197,47 @@ it("decodes resources with target identity, metadata, and strings", async () =>
expect(result.coverage).toBe("complete");
});
it.each([
{
name: "malformed UTF-8",
bytes: Buffer.concat([
Buffer.from("versionInfo:\n versionName: com."),
Buffer.from([0xff]),
Buffer.from(".app\n"),
]),
valid: false,
},
{
name: "a literal replacement character",
bytes: Buffer.from("versionInfo:\n versionName: com.�.app\n", "utf8"),
valid: true,
},
])("handles $name in producer metadata", async ({ bytes, valid }) => {
const { command, root } = await writeApktoolStub((root) =>
decodeStub({ ymlFile: join(root, "malformed-apktool.yml") })(root),
);
await writeFile(join(root, "malformed-apktool.yml"), bytes);
const apk = await apkFixture(root);
if (valid) {
const result = await evidenceResult(providerOver(command), {
operation: "decode_android_resources",
input: { path: apk.path, include_strings: false },
});
expect(result.metadata).toMatchObject({ version_name: "com.�.app" });
expect(result.coverage).toBe("complete");
return;
}
const result = await providerOver(command).execute({
operation: "decode_android_resources",
input: { path: apk.path, include_strings: false },
});
if (result.ok) throw new Error("expected invalid producer output");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({ code: "unreadable_output" });
expect(result.error.message).toContain("invalid UTF-8");
expect(result.error.message).toContain("apktool.yml");
});
it("preserves empty resource strings and reports markup omissions as partial", async () => {
const stringsXml =
'<resources><string name="empty"/><string name="raw"> A &amp; B </string><string name="styled">Hello <b>world</b></string></resources>';
+14 -7
View File
@@ -117,13 +117,20 @@ const readBoundedText = async (
throwIfCancelled(operation, signal);
const truncated = length > budget;
// A prefix may end within a UTF-8 character; omit those trailing bytes.
const decoder = new TextDecoder("utf-8");
return {
text: decoder.decode(bytes.subarray(0, Math.min(length, budget)), {
stream: truncated,
}),
truncated,
};
try {
const decoder = new TextDecoder("utf-8", { fatal: true });
return {
text: decoder.decode(bytes.subarray(0, Math.min(length, budget)), {
stream: truncated,
}),
truncated,
};
} catch (cause: unknown) {
throw new AnalysisProtocolError(
`apktool produced invalid UTF-8 in ${path}`,
{ cause },
);
}
} finally {
await file.close();
}
+44 -30
View File
@@ -54,6 +54,15 @@ export interface AnalysisExecution {
readonly subject: EvidenceSubjectTarget | null;
}
interface CreateAnalysisExecutionOptions {
readonly rawResult?: unknown;
readonly analysisProfile?: AnalysisProfileCommitment;
readonly limitations?: readonly string[];
readonly relationshipCoverage?: RelationshipCoverage;
readonly locations?: readonly EvidenceLocation[];
readonly subject?: EvidenceSubjectTarget;
}
/**
* Build a validated atomic provider observation at an adapter boundary.
*
@@ -61,38 +70,43 @@ export interface AnalysisExecution {
* `result`. Omitting it records `null` rather than a second complete copy of
* the normalized result in every Evidence record and tool response.
*/
export const createAnalysisExecution = (
export function createAnalysisExecution<Subject extends EvidenceSubjectTarget>(
result: unknown,
provider: ProviderIdentity,
options: {
readonly rawResult?: unknown;
readonly analysisProfile?: AnalysisProfileCommitment;
readonly limitations?: readonly string[];
readonly relationshipCoverage?: RelationshipCoverage;
readonly locations?: readonly EvidenceLocation[];
readonly subject?: EvidenceSubjectTarget;
} = {},
): AnalysisExecution => ({
result: jsonValueSchema.parse(result),
rawResult:
options.rawResult === undefined
? null
: jsonValueSchema.parse(options.rawResult),
provider,
...(options.analysisProfile === undefined
? {}
: { analysisProfile: structuredClone(options.analysisProfile) }),
limitations: [...(options.limitations ?? [])],
...(options.relationshipCoverage === undefined
? {}
: {
relationshipCoverage: relationshipCoverageSchema.parse(
options.relationshipCoverage,
),
}),
locations: [...(options.locations ?? [])],
subject: options.subject ?? null,
});
options: CreateAnalysisExecutionOptions & { readonly subject: Subject },
): Omit<AnalysisExecution, "subject"> & { readonly subject: Subject };
export function createAnalysisExecution(
result: unknown,
provider: ProviderIdentity,
options?: CreateAnalysisExecutionOptions,
): AnalysisExecution;
export function createAnalysisExecution(
result: unknown,
provider: ProviderIdentity,
options: CreateAnalysisExecutionOptions = {},
): AnalysisExecution {
return {
result: jsonValueSchema.parse(result),
rawResult:
options.rawResult === undefined
? null
: jsonValueSchema.parse(options.rawResult),
provider,
...(options.analysisProfile === undefined
? {}
: { analysisProfile: structuredClone(options.analysisProfile) }),
limitations: [...(options.limitations ?? [])],
...(options.relationshipCoverage === undefined
? {}
: {
relationshipCoverage: relationshipCoverageSchema.parse(
options.relationshipCoverage,
),
}),
locations: [...(options.locations ?? [])],
subject: options.subject ?? null,
};
}
/** Provider-neutral application capability for one analysis operation. */
export interface AnalysisOperationPort {
+1 -1
View File
@@ -481,7 +481,7 @@ const workflowAvailabilityFor = ({
remediation: "Run process capture on a supported Linux or macOS host.",
};
if (kind === "application") return { reason: "available", remediation: null };
if (kind === "flutter-provider")
if (kind === "pcap-provider" || kind === "flutter-provider")
return { reason: "available", remediation: null };
const electron = electronProviderAvailability(name, kind, policy);
if (electron !== null) return electron;
+65 -41
View File
@@ -7,6 +7,7 @@ import {
clientServerForcedEnabled,
clientServerListedDisabled,
effectiveClientServer,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import { access } from "node:fs/promises";
import { resolve } from "node:path";
@@ -74,24 +75,48 @@ const registrationSchema = z
})
.passthrough();
/** Inspect supported client registrations without reading their environment. */
interface ClientRegistrationReadOptions {
readonly platform?: NodeJS.Platform;
readonly environment?: NodeJS.ProcessEnv;
readonly resources?: ArtifactResourceScope;
}
/** Registration facts shared by diagnostics and update maintenance. */
export interface ClientRegistrationInspection {
readonly status: ClientRegistrationStatus;
readonly activation: "enabled" | "disabled" | "unknown";
}
/** Project diagnostics from the same inspection used to select maintenance. */
export const readClientRegistrationStatuses = async (
home: string,
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
options: {
readonly platform?: NodeJS.Platform;
readonly environment?: NodeJS.ProcessEnv;
readonly resources?: ArtifactResourceScope;
} = {},
): Promise<readonly ClientRegistrationStatus[]> => {
const statuses: ClientRegistrationStatus[] = [];
options: ClientRegistrationReadOptions = {},
): Promise<readonly ClientRegistrationStatus[]> =>
(
await readClientRegistrationInspections(home, currentCommandPath, options)
).map(({ status }) => status);
/** Parse effective registrations and their client-specific activation once. */
export const readClientRegistrationInspections = async (
home: string,
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
options: ClientRegistrationReadOptions = {},
): Promise<readonly ClientRegistrationInspection[]> => {
const inspections: ClientRegistrationInspection[] = [];
const record = (
status: ClientRegistrationStatus,
activation: ClientRegistrationInspection["activation"] = "unknown",
): void => {
inspections.push({ status, activation });
};
for (const client of supportedClients(
home,
options.platform,
options.environment,
)) {
if (client.configPathError !== undefined) {
statuses.push({
record({
client: client.name,
config_path: client.configPath,
command: [],
@@ -104,7 +129,7 @@ export const readClientRegistrationStatuses = async (
const manualRemediation = manualRegistrationRemediation(client.name);
if (client.format === "unsupported") {
if (manualRemediation !== undefined)
statuses.push({
record({
client: client.name,
config_path: client.markerPath ?? client.configPath,
command: [],
@@ -119,7 +144,7 @@ export const readClientRegistrationStatuses = async (
options.resources,
);
if (!files.ok) {
statuses.push({
record({
client: client.name,
config_path: client.configPath,
command: [],
@@ -130,9 +155,7 @@ export const readClientRegistrationStatuses = async (
}
const parsed = effectiveClientConfiguration(files.value);
if (parsed === undefined) {
statuses.push(
unavailableStatus(client.name, client.configPath, "missing"),
);
record(unavailableStatus(client.name, client.configPath, "missing"));
continue;
}
const policy = await readClientPolicyBlock(
@@ -142,7 +165,7 @@ export const readClientRegistrationStatuses = async (
options.resources,
);
if (!policy.ok) {
statuses.push({
record({
client: client.name,
config_path: client.configPath,
command: [],
@@ -159,7 +182,7 @@ export const readClientRegistrationStatuses = async (
? dshDocument(parsed.document).editabilityError
: undefined;
if (editabilityError !== undefined) {
statuses.push({
record({
client: client.name,
config_path: client.configPath,
command: [],
@@ -168,9 +191,7 @@ export const readClientRegistrationStatuses = async (
});
continue;
}
statuses.push(
unavailableStatus(client.name, client.configPath, "missing"),
);
record(unavailableStatus(client.name, client.configPath, "missing"));
continue;
}
const registration = parseRegistration(raw, client);
@@ -178,21 +199,18 @@ export const readClientRegistrationStatuses = async (
registration.command,
...registration.args,
];
statuses.push(
const activation = registrationActivation(registration, client, parsed);
record(
configuredStatus(
client.name,
client.configPath,
command,
registrationAligned(
registration,
client,
currentCommandPath,
options.platform ?? process.platform,
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey),
) &&
!clientServerListedDisabled(
parsed,
PRODUCT_IDENTITY.mcpServerKey,
activation === "enabled" &&
registrationAligned(
registration,
client,
currentCommandPath,
options.platform ?? process.platform,
) &&
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
policyBlock === undefined
@@ -200,9 +218,10 @@ export const readClientRegistrationStatuses = async (
: "stale",
policyBlock,
),
activation,
);
} catch (cause: unknown) {
statuses.push(
record(
unavailableStatus(
client.name,
client.configPath,
@@ -211,26 +230,31 @@ export const readClientRegistrationStatuses = async (
);
}
}
return statuses.sort((left, right) =>
compareUnicodeCodePoints(left.client, right.client),
return inspections.sort((left, right) =>
compareUnicodeCodePoints(left.status.client, right.status.client),
);
};
const registrationActivation = (
registration: z.output<typeof registrationSchema>,
client: SetupClient,
parsed: ClientConfigurationDocument,
): "enabled" | "disabled" =>
(client.format !== "grok" && registration.disabled === true) ||
(registration.enabled === false &&
!clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) ||
(client.format === "zcode" && registration.enable === false) ||
clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
? "disabled"
: "enabled";
const registrationAligned = (
registration: z.output<typeof registrationSchema>,
client: SetupClient,
currentCommandPath: string,
platform: NodeJS.Platform,
forcedEnabled = false,
): boolean => {
const command = [registration.command, ...registration.args];
if (
(client.format !== "grok" && registration.disabled === true) ||
(registration.enabled === false && !forcedEnabled) ||
// ZCode's native flag is `enable`; other dialects leave that field opaque.
(client.format === "zcode" && registration.enable === false)
)
return false;
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
return false;
if (
+12 -39
View File
@@ -1,19 +1,10 @@
import { z } from "zod";
import { PRODUCT_IDENTITY } from "../identity.js";
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { readClientRegistrationStatuses } from "./ClientRegistrationStatus.js";
import {
clientServerForcedEnabled,
clientServerListedDisabled,
effectiveClientServer,
parseClientConfiguration,
} from "./ClientConfigurationDocument.js";
import { supportedClients } from "./SupportedClients.js";
import { readClientRegistrationInspections } from "./ClientRegistrationStatus.js";
import { existingSkillDestinations } from "./SetupSkill.js";
import type { SetupAction } from "./SetupTypes.js";
import type { Result } from "../domain/result.js";
import { readRegularFileText } from "./RegularFileRead.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
/** Existing REA integrations selected for maintenance, without discovering new targets. */
@@ -61,41 +52,23 @@ export const existingMaintenanceScope = async (
environment: Readonly<NodeJS.ProcessEnv>,
resources?: ArtifactResourceScope,
): Promise<MaintenanceScope> => {
const registrations = await readClientRegistrationStatuses(home, entryPoint, {
environment,
...(resources === undefined ? {} : { resources }),
});
const supported = supportedClients(home, process.platform, environment);
const registrations = await readClientRegistrationInspections(
home,
entryPoint,
{
environment,
...(resources === undefined ? {} : { resources }),
},
);
const clients: string[] = [];
for (const registration of registrations) {
for (const { status: registration, activation } of registrations) {
if (
activation !== "enabled" ||
(registration.state !== "aligned" && registration.state !== "stale") ||
!isOwnedClientRegistrationCommand(registration.command, entryPoint)
)
continue;
const client = supported.find(({ name }) => name === registration.client);
if (client === undefined) continue;
const parsed = parseClientConfiguration(
await readRegularFileText(
client.configPath,
resources === undefined ? {} : { resources },
),
client.format,
);
const enabled = z
.object({
enabled: z.boolean().optional(),
disabled: z.boolean().optional(),
})
.parse(effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey));
// Root disable lists override enabled entries and OMP's force-on allowlist.
if (
(enabled.enabled !== false ||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) &&
enabled.disabled !== true &&
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
)
clients.push(client.name);
clients.push(registration.client);
}
const skillDestinations = await existingSkillDestinations(
home,
+7 -1
View File
@@ -4,13 +4,19 @@ import type {
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectEvmInterfaceInput } from "../../domain/evm/evmInterface.js";
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
import type { Result } from "../../domain/result.js";
/** Successful EVM interface recovery must identify the selected local file. */
export type EvmInterfaceExecution = Omit<AnalysisExecution, "subject"> & {
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
};
/** Replaceable offline interface-recovery engine, independent of wallets and chain clients. */
export interface EvmInterfacePort {
close?(): Promise<void>;
inspect(
input: InspectEvmInterfaceInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
): Promise<Result<EvmInterfaceExecution, AnalysisError>>;
}
@@ -1,5 +1,6 @@
import { expect, it } from "vitest";
import { EvmInterfaceService } from "./EvmInterfaceService.js";
import type { EvmInterfaceExecution } from "./EvmInterfacePort.js";
import {
evmInterfaceExecution,
evmInterfaceFixture,
@@ -43,7 +44,8 @@ it.each(["carrier", "encoding", "digest", "no-subject"])(
},
};
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(ok(execution)),
inspect: () =>
Promise.resolve(ok(execution as unknown as EvmInterfaceExecution)),
});
expect(
await service.inspect({
@@ -67,6 +67,7 @@ export class EvmInterfaceService {
!report.success ||
report.data.artifact.path !== input.data.path ||
report.data.artifact.encoding !== input.data.encoding ||
execution.subject?.format !== "file" ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256
)
@@ -78,6 +78,51 @@ const update = (
});
describe("residual unknown registry reads and identity", () => {
it("seals mutation Evidence without freezing caller-owned inputs", () => {
const store = ledger();
const recordMutation = mutation("mutable-record-mutation");
const recorded = store.recordUnknown(
input("Does record mutation evidence stay stable?"),
recordMutation,
);
if (!recorded.ok) throw recorded.error;
const updateMutation = mutation("mutable-update-mutation");
const updated = store.updateUnknown(update(recorded.value), updateMutation);
if (!updated.ok) throw updated.error;
const atomicEvidence = evidence("mutable-atomic-evidence");
const atomicMutation = mutation("mutable-atomic-mutation");
const atomicallyRecorded = store.recordWithUnknown(
atomicEvidence,
input("Does atomic evidence stay stable?"),
atomicMutation,
);
if (!atomicallyRecorded.ok) throw atomicallyRecorded.error;
for (const callerEvidence of [
recordMutation,
updateMutation,
atomicEvidence,
atomicMutation,
]) {
expect(Object.isFrozen(callerEvidence)).toBe(false);
const retained = store.forAnalysis(callerEvidence.evidence_id);
if (retained === undefined) throw new Error("Missing retained Evidence");
const originalResult = structuredClone(retained.normalized_result);
expect(Object.isFrozen(retained)).toBe(true);
Reflect.set(callerEvidence, "operation", "caller mutation");
expect(
Reflect.set(
callerEvidence.normalized_result as object,
"label",
"caller nested mutation",
),
).toBe(true);
expect(retained.operation).not.toBe("caller mutation");
expect(retained.normalized_result).toEqual(originalResult);
}
});
it("merges record-only bundles without changing retained unknown history", () => {
const store = ledger();
const created = store.recordUnknown(
@@ -11,11 +11,7 @@ import {
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import {
immutableEvidence,
parseEvidence,
type Evidence,
} from "../../domain/evidence.js";
import { immutableEvidence, type Evidence } from "../../domain/evidence.js";
import {
createResidualUnknown,
updateResidualUnknown,
@@ -220,7 +216,7 @@ export class EvidenceLedger {
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
let parsedMutation: Evidence;
try {
parsedMutation = parseEvidence(mutationEvidence);
parsedMutation = immutableEvidence(mutationEvidence);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
@@ -255,8 +251,8 @@ export class EvidenceLedger {
let evidence: Evidence;
let mutation: Evidence;
try {
evidence = parseEvidence(evidenceInput);
mutation = parseEvidence(mutationInput);
evidence = immutableEvidence(evidenceInput);
mutation = immutableEvidence(mutationInput);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError("Atomic Evidence validation failed", {
@@ -394,7 +390,7 @@ export class EvidenceLedger {
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
let mutationEvidence: Evidence;
try {
mutationEvidence = parseEvidence(mutationEvidenceInput);
mutationEvidence = immutableEvidence(mutationEvidenceInput);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
@@ -0,0 +1,71 @@
import { expect, it } from "vitest";
import { TraceMap } from "@jridgewell/trace-mapping";
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
const HASH = "a".repeat(64);
it("retains batched TraceMap-resolved paths and null source positions", () => {
const sourceMapText = JSON.stringify({
version: 3,
file: "main.js",
sourceRoot: "../src/",
sources: ["cafe\u0301.ts", null, "other.ts"],
sourcesContent: ["export const value = 1;", null, "export {};"],
names: [],
mappings: "",
});
const analysis = analyzeJavaScriptArtifactFiles({
files: [
{
path: "dist/main.js.map",
container_sha256: HASH,
sha256: HASH,
bytes: Buffer.byteLength(sourceMapText),
inventory_artifact_id: "artifact_test",
kind: "source-map",
unpacked: false,
text: { included: true, value: sourceMapText },
},
],
containers: [],
text_bytes_read: Buffer.byteLength(sourceMapText),
invalid_utf8_files: 0,
});
const originals = analysis.source_maps[0]?.sources;
const original = originals?.[0];
const producerPath = new TraceMap(
{
version: 3,
file: "main.js",
sourceRoot: "../src/",
sources: ["cafe\u0301.ts", "", "other.ts"],
names: [],
mappings: "",
},
"file:///artifact/dist/main.js.map",
).resolvedSources[0];
if (producerPath === undefined)
throw new Error("TraceMap should resolve its single source declaration");
expect(originals?.[1]?.reference).toBeNull();
expect(originals?.[2]?.reference?.resolution).toEqual({
kind: "artifact-relative",
path: "src/other.ts",
});
expect(original?.reference).toMatchObject({
source_name: "cafe\u0301.ts",
source_root: "../src/",
map_path: "dist/main.js.map",
resolution: {
kind: "artifact-relative",
path: "src/cafe\u0301.ts",
},
});
expect(original?.reference?.resolution).toEqual({
kind: "artifact-relative",
path: decodeURIComponent(
new URL(producerPath).pathname.slice("/artifact/".length),
),
});
});
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
import { setImmediate } from "node:timers/promises";
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
import { resolveJavaScriptSourceMapReferences } from "../../domain/javascript/javascriptSourceMapPaths.js";
import { analyzeParsedJavaScriptStaticSourceSteps } from "../../domain/javascript/javascriptStaticAnalysis.js";
import {
analyzeParsedJavaScriptSemanticsSteps,
@@ -561,21 +561,27 @@ const collectSourceMapOriginals = (
"Source map sourceRoot must be a string or null.",
);
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : null;
for (const [index, raw] of names.entries()) {
const sourceNames: (string | null)[] = [];
for (const raw of names) {
if (raw !== null && typeof raw !== "string")
return invalidSourceMap(
file,
"Source map contains a non-string source name.",
);
sourceNames.push(raw);
}
const references = resolveJavaScriptSourceMapReferences(
sourceNames,
root,
file.path,
);
for (const [index, reference] of references.entries()) {
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
const content = typeof rawContent === "string" ? rawContent : null;
sources.push({
source_index: index,
declaration_index: declarationIndex++,
reference:
typeof raw === "string"
? resolveJavaScriptSourceMapReference(raw, root, file.path)
: null,
reference,
content,
content_sha256: content === null ? null : sha256(content),
});
@@ -22,6 +22,26 @@ const exampleMethod = () => {
};
describe("managed decompiler reconstruction import", () => {
it("reports UTF-8 byte totals while preserving UTF-16 text lengths", () => {
const text = 'return "é"; // 😀';
const method = exampleMethod();
const result = importManagedReconstructionEvidence({
...MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
methods: [
{
...method,
reconstruction: { ...method.reconstruction, text },
},
],
});
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
summary: { total_text_bytes: 20 },
methods: [{ reconstruction: { text, text_length: 17 } }],
});
});
it("rejects reconstruction text hash drift", () => {
expect(() =>
importManagedReconstruction({
+23
View File
@@ -0,0 +1,23 @@
import type {
AnalysisExecution,
ExecutionOptions,
ProviderAvailability,
} from "../AnalysisProvider.js";
import type { PcapRequest } from "../../domain/pcap/pcapAnalysis.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Result } from "../../domain/result.js";
/**
* Packet-capture analysis boundary over caller-supplied tshark/capinfos.
* Implementation details belong to the provider adapter.
*/
export interface PcapAnalysisPort {
/** Probe both tools without reading any capture file. */
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
/** Retry cleanup of retained owned commands and capture snapshots. */
close(): Promise<void>;
execute(
request: PcapRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,36 @@
import type { PcapAnalysisPort } from "./PcapAnalysisPort.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
pcapRequestSchema,
type PcapOperation,
} from "../../domain/pcap/pcapAnalysis.js";
import {
AnalysisCancelledError,
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { createPcapEvidence } from "../../domain/pcap/pcapEvidence.js";
import { err, ok, type Result } from "../../domain/result.js";
/** Shared CLI/MCP admission, execution, and Evidence composition for pcap. */
export class PcapAnalysisService {
constructor(readonly provider: PcapAnalysisPort) {}
/** Run one caller-selected pcap request and retain capture identity inline. */
async execute(
operation: PcapOperation,
input: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const request = pcapRequestSchema.safeParse({ operation, input });
if (!request.success)
return err(new AnalysisInputError(operation, { cause: request.error }));
const executed = await this.provider.execute(request.data, options);
if (!executed.ok) return executed;
const execution = executed.value;
return ok(createPcapEvidence(request.data, execution));
}
}
+7 -1
View File
@@ -4,8 +4,14 @@ import type {
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectWasmArtifactInput } from "../../domain/wasm/wasmArtifact.js";
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
import type { Result } from "../../domain/result.js";
/** Successful WASM inspection must identify the selected local file. */
export type WasmArtifactExecution = Omit<AnalysisExecution, "subject"> & {
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
};
/** Replaceable offline WASM inspection engine, independent of target execution and network clients. */
export interface WasmArtifactPort {
/** Retry removal of retained workspaces; failures preserve ownership for another attempt. */
@@ -13,5 +19,5 @@ export interface WasmArtifactPort {
inspect(
input: InspectWasmArtifactInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
): Promise<Result<WasmArtifactExecution, AnalysisError>>;
}
+83 -28
View File
@@ -22,6 +22,7 @@ import {
type NativeDmgInfo,
} from "./NativeDmgOwnership.js";
const HDIUTIL_COMMAND_TIMEOUT_MS = 120_000;
const VERIFY_SETTLE_DELAYS_MS = [250, 500] as const;
// APFS ejects and busy reporting can lag a detach attempt.
const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const;
const delay = (milliseconds: number): Promise<void> =>
@@ -44,22 +45,30 @@ export interface NativeDmgHost {
class NativeDmgCommandFailure extends ArtifactReaderFailure {
readonly processNotStarted: boolean;
readonly verifyDiagnostic: string | undefined;
readonly exitCode: number | null;
constructor(
reason: ArtifactReaderFailure["reason"],
failure: {
readonly reason: ArtifactReaderFailure["reason"];
readonly verifyDiagnostic?: string;
},
message: string,
readonly stdout: string,
options?: {
readonly cause?: unknown;
readonly processNotStarted?: boolean;
readonly exitCode?: number;
},
) {
super(
reason,
failure.reason,
message,
options?.cause === undefined ? undefined : { cause: options.cause },
);
this.processNotStarted = options?.processNotStarted ?? false;
this.verifyDiagnostic = failure.verifyDiagnostic;
this.exitCode = options?.exitCode ?? null;
}
}
@@ -84,7 +93,7 @@ const createSystemHost = (
const output = execFileOutputFailure(cause);
if (cause instanceof Error && cause.name === "AbortError")
throw new NativeDmgCommandFailure(
"cancelled",
{ reason: "cancelled" },
"DMG operation cancelled",
output?.stdout ?? "",
{ cause },
@@ -99,7 +108,7 @@ const createSystemHost = (
cause,
};
throw new NativeDmgCommandFailure(
commandFailureReason(cause, arguments_[0]),
classifyCommandFailure(cause, arguments_[0]),
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`,
output?.stdout ?? "",
{ cause, processNotStarted: processNotStarted(cause) },
@@ -348,8 +357,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
}
async #attach(signal?: AbortSignal): Promise<void> {
await runChecked(this.host, ["verify", this.path], signal);
this.#provenance.push(command(["verify", this.path], ["read"]));
await this.#verify(signal);
const baseline = await this.#readInfo();
this.#baselineDevices = new Set(
baseline.images.flatMap((image) =>
@@ -431,6 +439,40 @@ export class NativeDmgArtifactReader implements ArtifactReader {
}
}
async #verify(signal?: AbortSignal): Promise<void> {
const arguments_ = ["verify", this.path];
const deadline = performance.now() + HDIUTIL_COMMAND_TIMEOUT_MS;
for (let attempt = 0; ; attempt += 1) {
if (signal?.aborted === true)
throw new NativeDmgCommandFailure(
{ reason: "cancelled" },
"DMG operation cancelled",
"",
{ cause: signal.reason },
);
try {
await runChecked(this.host, arguments_, signal, {
timeoutMs: Math.max(1, Math.ceil(deadline - performance.now())),
});
this.#provenance.push(command(arguments_, ["read"]));
return;
} catch (cause: unknown) {
if (!(cause instanceof NativeDmgCommandFailure)) throw cause;
this.#provenance.push(command(arguments_, ["read"], cause.exitCode));
const delayMs = VERIFY_SETTLE_DELAYS_MS[attempt];
// Retry only the producer's explicit transient diagnostic, before any mount.
if (
cause.verifyDiagnostic !== "Resource temporarily unavailable" ||
delayMs === undefined ||
deadline - performance.now() <= delayMs
)
throw cause;
await (this.host.delay ?? delay)(delayMs);
if (performance.now() >= deadline) throw cause;
}
}
}
async #readInfo(): Promise<NativeDmgInfo> {
const info = await runChecked(this.host, ["info", "-plist"], undefined, {
timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS,
@@ -501,14 +543,14 @@ const runChecked = async (
if (cause instanceof ArtifactReaderFailure) throw cause;
if (cause instanceof Error && cause.name === "AbortError")
throw new NativeDmgCommandFailure(
"cancelled",
{ reason: "cancelled" },
"DMG operation cancelled",
execFileOutputFailure(cause)?.stdout ?? "",
{ cause },
);
const output = execFileOutputFailure(cause);
throw new NativeDmgCommandFailure(
commandFailureReason(cause, arguments_[0]),
classifyCommandFailure(cause, arguments_[0]),
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(
cause,
arguments_,
@@ -527,17 +569,17 @@ const runChecked = async (
stdout: result.stdout,
...(result.stderr === undefined ? {} : { stderr: result.stderr }),
};
const reason = commandFailureReason(failure, arguments_[0]);
const classification = classifyCommandFailure(failure, arguments_[0]);
const details = describeCommandFailure(failure, arguments_);
const unknownVerifyFailure =
arguments_[0] === "verify" && reason === "unavailable";
arguments_[0] === "verify" && classification.reason === "unavailable";
throw new NativeDmgCommandFailure(
reason,
classification,
unknownVerifyFailure
? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}`
: `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`,
result.stdout,
{ cause: result.cause ?? failure },
{ cause: result.cause ?? failure, exitCode: result.exitCode },
);
}
return { stdout: result.stdout, exitCode: 0 };
@@ -587,20 +629,36 @@ const processOutput = (cause: unknown, field: "stdout" | "stderr"): string => {
return typeof value === "string" ? value : "";
};
const commandFailureReason = (
const classifyCommandFailure = (
cause: unknown,
operation: string | undefined,
): ArtifactReaderFailure["reason"] => {
if (typeof cause !== "object" || cause === null) return "unavailable";
): {
readonly reason: ArtifactReaderFailure["reason"];
readonly verifyDiagnostic?: string;
} => {
if (typeof cause !== "object" || cause === null)
return { reason: "unavailable" };
const code = Reflect.get(cause, "code");
const exitCode = Reflect.get(cause, "exitCode");
if (typeof code === "number" || typeof exitCode === "number")
return operation === "verify" ? verifyFailureReason(cause) : "unavailable";
if (typeof code === "number" || typeof exitCode === "number") {
if (operation !== "verify") return { reason: "unavailable" };
const diagnostic = verifyFailureDiagnostic(
processOutput(cause, "stdout"),
processOutput(cause, "stderr"),
);
return {
reason: verifyFailureReason(diagnostic),
...(diagnostic === undefined ? {} : { verifyDiagnostic: diagnostic }),
};
}
if (code === "ENOENT") {
const syscall = Reflect.get(cause, "syscall");
return typeof syscall === "string" && syscall.startsWith("spawn")
? "unavailable"
: "io";
return {
reason:
typeof syscall === "string" && syscall.startsWith("spawn")
? "unavailable"
: "io",
};
}
if (
code === "EACCES" ||
@@ -613,17 +671,13 @@ const commandFailureReason = (
code === "EMFILE" ||
code === "ENFILE"
)
return "io";
return "unavailable";
return { reason: "io" };
return { reason: "unavailable" };
};
const verifyFailureReason = (
cause: unknown,
diagnostic: string | undefined,
): ArtifactReaderFailure["reason"] => {
const diagnostic = verifyFailureDiagnostic(
processOutput(cause, "stdout"),
processOutput(cause, "stderr"),
);
switch (diagnostic) {
// hdiutil follows AppleLanguages, so en-GB and en-AU spell it "recognised".
case "image not recognized":
@@ -656,11 +710,12 @@ const verifyFailureDiagnostic = (
const command = (
arguments_: readonly string[],
effects: ArtifactCommand["effects"],
exitCode: number | null = 0,
): ArtifactCommand => ({
tool: "/usr/bin/hdiutil",
arguments: [...arguments_],
tool_version: null,
executable_sha256: null,
exit_code: 0,
exit_code: exitCode,
effects,
});
+6 -2
View File
@@ -2,7 +2,6 @@ import * as t from "@babel/types";
import {
decodeValidatedSourceMapLeaves,
isBeforeSourceMapLeafStop,
resolveSourceMapSource,
} from "../javascript/sourceMaps/DecodedSourceMap.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
@@ -21,6 +20,7 @@ import { webSourceMapsSchema } from "../domain/webBundleAnalysis.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
import { safeParseJson } from "../domain/safeJson.js";
import { sourceMapJsonText } from "../domain/sourceMapEnvelope.js";
import { resolveJavaScriptSourceMapUrl } from "../domain/javascript/javascriptSourceMapPaths.js";
import { jsonParts } from "../domain/jsonSerialization.js";
import {
inspectSourceMapValue,
@@ -867,7 +867,11 @@ const preflightResolvedSourceBytes = (
const sourceKey = source;
let resolved = sourcesForRoot.get(sourceKey);
if (resolved === undefined)
resolved = resolveSourceMapSource(source, map.sourceRoot, mapUrl);
resolved = resolveJavaScriptSourceMapUrl(
source,
map.sourceRoot,
mapUrl,
);
const bytes = Buffer.byteLength(resolved, "utf8");
if (bytes > SOURCE_MAP_RESPONSE_BYTES - resolvedBytes)
throw resolvedSourceLimitFailure();
+2
View File
@@ -24,6 +24,7 @@ import { registerManagedCommands } from "./cli/managedCommands.js";
import { registerFirmwareCommands } from "./cli/firmwareCommands.js";
import { registerAndroidCommands } from "./cli/androidCommands.js";
import { registerApktoolCommands } from "./cli/apktoolCommands.js";
import { registerPcapCommands } from "./cli/pcapCommands.js";
import { registerFlutterCommands } from "./cli/flutterCommands.js";
import { registerJebCommands } from "./cli/jebCommands.js";
import { registerAdbCommands } from "./cli/adbCommands.js";
@@ -105,6 +106,7 @@ export const createCli = (
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
registerAndroidCommands(cli, logger, environment);
registerApktoolCommands(cli, logger, environment);
registerPcapCommands(cli, logger, environment);
registerFlutterCommands(cli, logger);
registerJebCommands(cli, logger, environment);
registerAdbCommands(cli, logger, environment);
+69
View File
@@ -0,0 +1,69 @@
import { z } from "incur";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { createPcapAnalysisProvider } from "../composition/pcap.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { PcapOperation } from "../domain/pcap/pcapAnalysis.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Expose the same explicit pcap requests through one-shot CLI commands. */
export const registerPcapCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
provider: PcapAnalysisPort = createPcapAnalysisProvider(environment),
): void => {
const service = new PcapAnalysisService(provider);
const execute = (name: string, operation: PcapOperation, input: unknown) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, async () => {
const result = await service.execute(operation, input, { signal });
try {
await provider.close();
} catch (cause) {
if (cause instanceof AnalysisError) {
if (result.ok) cause.retainPartialObservation(result.value);
return projectAnalysisError(
result.ok
? cause
: analysisErrorWithCleanupFailure(
result.error,
cause,
operation,
),
);
}
throw cause;
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
);
cli.command(CLI_COMMANDS.inspectPcapClient, {
description:
"Inspect the caller-selected tshark and capinfos binaries without reading a capture",
args: z.object({}),
run: () =>
execute(CLI_COMMANDS.inspectPcapClient, "inspect_pcap_client", {}),
});
cli.command(CLI_COMMANDS.inspectPcapCapture, {
description:
"Inspect one pcap/pcapng capture: endpoints, DNS, TLS SNI, and protocol distribution",
args: z.object({
path: z
.string()
.min(1)
.describe("Local pcap or pcapng capture file to inspect"),
}),
run: ({ args }) =>
execute(CLI_COMMANDS.inspectPcapCapture, "inspect_pcap_capture", {
path: args.path,
}),
});
};
+2
View File
@@ -55,6 +55,8 @@ export const CLI_COMMANDS = Object.freeze({
inspectFirmwareRegions: "inspect-firmware-regions",
extractFirmware: "extract-firmware",
inspectAndroidPackage: "inspect-android-package",
inspectPcapClient: "inspect-pcap-client",
inspectPcapCapture: "inspect-pcap-capture",
identifyFlutterBuild: "identify-flutter-build",
inspectDartAot: "inspect-dart-aot",
inspectApktoolClient: "inspect-apktool-client",
+7
View File
@@ -0,0 +1,7 @@
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { PcapProvider } from "../pcap/PcapProvider.js";
/** Construct one pcap provider bound to the caller-selected tools. */
export const createPcapAnalysisProvider = (
environment: Readonly<Record<string, string | undefined>> = process.env,
): PcapAnalysisPort => new PcapProvider({ environment });
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -218,7 +218,7 @@ export const APPLICATION_TOOL_CONTRACTS = [
name: "evaluate_reconstruction_coverage",
...toolContractMetadata("evaluate_reconstruction_coverage"),
description:
"Evaluate inline evidence-backed reconstruction coverage against one named boundary. Missing ownership or inventory is partial; stale, weak, truncated, skipped, or unresolved proof is unknown; contradictions, failed proof, missing owners, and authority routing fail closed.",
"Evaluate inline evidence-backed reconstruction coverage against one named boundary. Missing ownership or inventory is partial; stale, weak, truncated, skipped, unresolved, or conflicting tied verifier proof is unknown; contradictions, failed proof, missing owners, and authority routing fail closed.",
kind: "application",
inputSchema: reconstructionCoverageEvaluationInputSchema,
outputSchema: reconstructionClosureResultSchema,
+46
View File
@@ -0,0 +1,46 @@
import {
pcapInputSchemas,
pcapResultSchemas,
} from "../../domain/pcap/pcapAnalysis.js";
import type { ToolContract } from "../toolContractTypes.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "../toolEffects.js";
import {
analysisDetailSchema,
analysisDetailOutputSchemaOf,
} from "../analysisDetail.js";
import { pcapCaptureSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
/** Packet-capture analysis served by caller-supplied tshark and capinfos. */
export const PCAP_TOOL_CONTRACTS = [
{
name: "inspect_pcap_client",
...toolContractMetadata("inspect_pcap_client"),
description:
"Inspect the caller-selected tshark and capinfos binaries: selected commands, selection sources, and versions. Both tools must be usable. Reads no capture file. REA never installs the Wireshark suite; select binaries with REA_TSHARK_COMMAND and REA_CAPINFOS_COMMAND (absolute) or from PATH.",
kind: "pcap-provider",
inputSchema: pcapInputSchemas.inspect_pcap_client,
outputSchema: evidenceResultOf(pcapResultSchemas.inspect_pcap_client),
examples: [{ title: "Check the analysis tools", input: {} }],
},
{
name: "inspect_pcap_capture",
...toolContractMetadata("inspect_pcap_capture"),
description:
"Request detail summary for capture identity/counts, then page retained facts with inspect_analysis_view kind pcap. Default detail complete preserves inline delivery. Inspect one saved pcap or pcapng capture through an owned snapshot: metadata, exact packet count, SHA-256, IPv4/IPv6 address counts, DNS questions and address values from the same single-question response, TLS SNI, protocol distribution and HTTP URIs. All derived inventories are retained within declared resource budgets; unknown DNS attribution and excluded credentials remain explicit. Linux requires util-linux prlimit; Windows uses owned Job Objects. Requires caller-supplied capinfos and tshark; REA never captures traffic.",
kind: "pcap-provider",
inputSchema: pcapInputSchemas.inspect_pcap_capture.extend({
detail: analysisDetailSchema,
}),
outputSchema: analysisDetailOutputSchemaOf(
pcapResultSchemas.inspect_pcap_capture,
pcapCaptureSummaryViewResultSchema,
),
examples: [
{
title: "Inspect a capture file",
input: { path: "/captures/session.pcap" },
},
],
},
] as const satisfies readonly ToolContract[];
+1
View File
@@ -33,6 +33,7 @@ export const TOOL_KINDS = [
"browser-provider",
"electron-provider",
"runtime-provider",
"pcap-provider",
"application",
"session",
] as const;
+2
View File
@@ -12,6 +12,7 @@ import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
import { APKTOOL_TOOL_CONTRACTS } from "./apktool/apktoolToolContracts.js";
import { PCAP_TOOL_CONTRACTS } from "./pcap/pcapToolContracts.js";
import { FLUTTER_TOOL_CONTRACTS } from "./flutter/flutterToolContracts.js";
import { JEB_TOOL_CONTRACTS } from "./jeb/jebToolContracts.js";
import { ADB_TOOL_CONTRACTS } from "./adb/adbToolContracts.js";
@@ -46,6 +47,7 @@ export const TOOL_CONTRACTS = [
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...APKTOOL_TOOL_CONTRACTS,
...PCAP_TOOL_CONTRACTS,
...FLUTTER_TOOL_CONTRACTS,
...JEB_TOOL_CONTRACTS,
...ADB_TOOL_CONTRACTS,
+2
View File
@@ -45,6 +45,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
search_android_classes: "states it does not execute the APK",
inspect_apktool_client:
"inspects the operator-selected apktool launcher; never installs it",
inspect_pcap_client:
"probes the operator-selected tshark and capinfos; never installs them",
inspect_jeb_client: "talks to a caller-started JEB; never launches it",
open_jeb_project: "the engine analyzes the file; REA does not execute it",
inspect_adb_client:
+10
View File
@@ -182,6 +182,16 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
writesFilesystem: true,
}),
inspect_pcap_client: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
inspect_pcap_capture: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
identify_flutter_build: effects({
mutatesSession: true,
writesFilesystem: true,
+7
View File
@@ -65,4 +65,11 @@ describe("analysis profile commitments", () => {
analysisProfileSchema.parse({ ...profile, digest: "0".repeat(64) }),
).toThrow(/digest/u);
});
it("projects known provider identity fields at construction", () => {
const liveProvider = { ...PROVIDER, transient_status: "starting" };
const profile = createAnalysisProfile(liveProvider, { loader: "default" });
expect(profile.provider).toEqual(PROVIDER);
expect(analysisProfileSchema.parse(profile)).toEqual(profile);
});
});
+7 -3
View File
@@ -7,13 +7,13 @@ import { jsonObjectSchema, type JsonValue } from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
/** Concrete provider identity committed by an analysis profile. */
export const committedProviderSchema = z.object({
export const committedProviderSchema = z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().min(1),
});
const unsignedAnalysisProfileSchema = z.object({
const unsignedAnalysisProfileSchema = z.strictObject({
provider: committedProviderSchema,
parameters: jsonObjectSchema,
});
@@ -40,7 +40,11 @@ export const createAnalysisProfile = (
parameters: Readonly<Record<string, JsonValue>>,
): AnalysisProfileCommitment => {
const unsigned = unsignedAnalysisProfileSchema.parse({
provider,
provider: {
id: provider.id,
name: provider.name,
version: provider.version,
},
parameters,
});
return analysisProfileSchema.parse({
+3 -3
View File
@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { resolveJavaScriptSourceMapReference } from "../javascript/javascriptSourceMapPaths.js";
import { functionDossierSchema } from "../hopperValues.js";
import { ghidraFunctionDossier } from "../ghidraValues.fixture.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
@@ -24,13 +23,14 @@ import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
import { sourceMapReference } from "../javascript/javascriptApplicationGraph.fixture.js";
import { javascriptModulePath } from "./javascriptApplicationView.js";
import {
inspectAnalysisViewInputSchema,
projectAnalysisView,
type AnalysisViewParent,
} from "./analysisView.js";
const layoutParent = (): AnalysisViewParent => {
const evidence = analysisViewLayoutEvidence();
return {
@@ -532,7 +532,7 @@ it("pages actual modules, including unknown and empty paths, without unrelated r
observations: original.observations.map((observation) => ({
...(kind === "source-module"
? {
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"",
null,
"renderer.js",
+28
View File
@@ -62,6 +62,12 @@ import {
captureSummarySchema,
} from "./webNetworkCaptureView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
pcapViewRequestSchema,
pcapViewPageSchema,
pcapSummarySchema,
projectPcapCaptureView,
} from "./pcapCaptureView.js";
import {
qlogViewRequestSchema,
qlogViewPageSchema,
@@ -196,6 +202,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
apiSurfaceViewSchema,
captureViewRequestSchema,
qlogViewRequestSchema,
pcapViewRequestSchema,
dartAotViewRequestSchema,
]);
@@ -312,6 +319,7 @@ const viewResultBase = {
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
"inspect_pcap_capture",
"inspect_dart_aot",
]),
parent_digest: digestSchema,
@@ -384,6 +392,12 @@ export const androidPackageSummaryViewResultSchema = z.strictObject({
summary: androidPackageSummarySchema,
});
export const pcapCaptureSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
summary: pcapSummarySchema,
});
/** Exact snapshot and pool-coverage carrier for selected AOT delivery. */
export const dartAotSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -415,6 +429,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
pcapSummarySchema,
dartAotSummarySchema,
]),
}),
@@ -433,6 +448,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("pcap"),
view: pcapViewRequestSchema,
page: pcapViewPageSchema,
source_coverage: z.enum(["complete", "partial"]),
...viewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
}),
z.strictObject({
kind: z.literal("facet"),
view: facetViewSchema,
@@ -562,6 +585,7 @@ export type UnsignedAnalysisView =
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "capture" }>,
"view_digest"
@@ -686,6 +710,10 @@ export const projectAnalysisView = (
const projected = projectWebNetworkCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_pcap_capture") {
const projected = projectPcapCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_binary_layout") {
const layout = binaryLayoutSchema.safeParse(parent.normalizedResult);
if (!layout.success)
@@ -76,6 +76,7 @@ export const projectEvmInterfaceView = (
const report = parsed.data;
if (
parent.subject == null ||
parent.subject.format !== "file" ||
parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256
)
+327
View File
@@ -0,0 +1,327 @@
import { z } from "zod";
import { pcapResultSchemas } from "../pcap/pcapAnalysis.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const captureSchema = pcapResultSchemas.inspect_pcap_capture;
const fields = captureSchema.shape;
const pageShape = {
kind: z.literal("pcap"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
};
export const pcapViewRequestSchema = z.discriminatedUnion("facet", [
z.strictObject({
...pageShape,
facet: z.enum([
"endpoints",
"dns-queries",
"tls-sni",
"protocols",
"http-uris",
"unattributed-addresses",
]),
}),
z.strictObject({
...pageShape,
facet: z.literal("dns-addresses"),
query: z.string().min(1),
}),
z.strictObject({
...pageShape,
facet: z.literal("diagnostics"),
stream: z.enum(["tshark", "capinfos"]),
}),
]);
export const pcapViewPageSchema = z.discriminatedUnion("facet", [
z.strictObject({ facet: z.literal("endpoints"), items: fields.endpoints }),
z.strictObject({
facet: z.literal("dns-queries"),
items: z.array(
fields.dns_queries.element.omit({ response_addresses: true }).extend({
retained_response_address_count: z.number().int().nonnegative(),
}),
),
}),
z.strictObject({ facet: z.literal("tls-sni"), items: fields.tls_sni_values }),
z.strictObject({
facet: z.literal("protocols"),
items: fields.protocol_distribution,
}),
z.strictObject({
facet: z.literal("http-uris"),
items: fields.http_request_uris,
}),
z.strictObject({
facet: z.literal("unattributed-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("dns-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("diagnostics"),
text: z.string(),
status: z.enum(["retained", "unknown"]),
}),
]);
export const pcapSummarySchema = captureSchema
.omit({
endpoints: true,
dns_queries: true,
tls_sni_values: true,
protocol_distribution: true,
http_request_uris: true,
unattributed_dns_addresses: true,
diagnostics: true,
})
.extend({
retained_counts: z.strictObject({
endpoints: z.number().int().nonnegative(),
dns_queries: z.number().int().nonnegative(),
tls_sni_values: z.number().int().nonnegative(),
protocol_distribution: z.number().int().nonnegative(),
http_request_uris: z.number().int().nonnegative(),
unattributed_dns_addresses: z.number().int().nonnegative(),
}),
diagnostics_code_units: z
.strictObject({
tshark: z.number().int().nonnegative(),
capinfos: z.number().int().nonnegative(),
})
.nullable(),
});
type Capture = z.output<typeof captureSchema>;
type PcapView = z.output<typeof pcapViewRequestSchema>;
type Page = z.output<typeof pcapViewPageSchema>;
const parseParent = (
parent: AnalysisViewParent,
): Result<Capture, AnalysisError> => {
const parsed = captureSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues,
parent.normalizedResult,
{ cause: parsed.error },
),
);
if (
parent.subject?.local_path !== parsed.data.target.path ||
parent.subject.digest.sha256 !== parsed.data.target.sha256
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Packet parent subject must identify the report's exact path and SHA-256.",
},
]),
);
return ok(parsed.data);
};
const summarize = ({
endpoints,
dns_queries,
tls_sni_values,
protocol_distribution,
http_request_uris,
unattributed_dns_addresses,
diagnostics,
...metadata
}: Capture) => ({
...metadata,
retained_counts: {
endpoints: endpoints.length,
dns_queries: dns_queries.length,
tls_sni_values: tls_sni_values.length,
protocol_distribution: protocol_distribution.length,
http_request_uris: http_request_uris.length,
unattributed_dns_addresses: unattributed_dns_addresses.length,
},
diagnostics_code_units:
diagnostics === undefined
? null
: {
tshark: diagnostics.tshark_stderr.length,
capinfos: diagnostics.capinfos_stderr.length,
},
});
const selectRows = (
capture: Capture,
view: Exclude<PcapView, { facet: "diagnostics" }>,
): Result<
{ page: Exclude<Page, { facet: "diagnostics" }>; total: number },
AnalysisError
> => {
const slice = <T>(items: readonly T[]) =>
items.slice(view.offset, view.offset + view.limit);
switch (view.facet) {
case "endpoints":
return ok({
page: { facet: view.facet, items: slice(capture.endpoints) },
total: capture.endpoints.length,
});
case "dns-queries":
return ok({
page: {
facet: view.facet,
items: slice(capture.dns_queries).map(
({ response_addresses, ...query }) => ({
...query,
retained_response_address_count: response_addresses.length,
}),
),
},
total: capture.dns_queries.length,
});
case "tls-sni":
return ok({
page: { facet: view.facet, items: slice(capture.tls_sni_values) },
total: capture.tls_sni_values.length,
});
case "protocols":
return ok({
page: {
facet: view.facet,
items: slice(capture.protocol_distribution),
},
total: capture.protocol_distribution.length,
});
case "http-uris":
return ok({
page: { facet: view.facet, items: slice(capture.http_request_uris) },
total: capture.http_request_uris.length,
});
case "unattributed-addresses":
return ok({
page: {
facet: view.facet,
items: slice(capture.unattributed_dns_addresses),
},
total: capture.unattributed_dns_addresses.length,
});
case "dns-addresses": {
const matches = capture.dns_queries.filter(
(query) => query.query === view.query,
);
if (matches.length !== 1)
return err(
analysisViewInputError([
{
path: ["view", "query"],
reason: "invalid_value",
message: "Select one unambiguous exact retained DNS question.",
},
]),
);
return ok({
page: {
facet: view.facet,
items: slice(matches[0]!.response_addresses),
},
total: matches[0]!.response_addresses.length,
});
}
}
};
/** Historical packet facts are paged without reopening the source or rerunning Wireshark. */
export const projectPcapCaptureView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "pcap")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Packet summary parents support summary and pcap fact pages.",
},
]),
);
const parsed = parseParent(parent);
if (!parsed.ok) return parsed;
const capture = parsed.value;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_pcap_capture" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: capture.target.path, sha256: capture.target.sha256 },
limitations: [
...parent.limitations,
"Page totals count retained rows or UTF-16 diagnostic code units. Exhaustion does not prove whole-network completeness; source coverage and examined counts remain separate.",
],
unknowns: [
"Saved packet observations do not establish process identity, causality, encrypted payload contents or traffic missing from the recording.",
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: summarize(capture),
coverage: completeWithinViewCoverage(1, 1),
});
if (view.facet === "diagnostics") {
const value =
view.stream === "tshark"
? capture.diagnostics?.tshark_stderr
: capture.diagnostics?.capinfos_stderr;
const text = value?.slice(view.offset, view.offset + view.limit) ?? "";
return ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: {
facet: "diagnostics",
text,
status: value === undefined ? "unknown" : "retained",
},
coverage: pageViewCoverage(view.offset, text.length, value?.length ?? 0),
unknowns:
value === undefined
? [
...shared.unknowns,
"The parent did not retain diagnostics; an empty text page does not establish their absence.",
]
: shared.unknowns,
});
}
const selected = selectRows(capture, view);
return selected.ok
? ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: selected.value.page,
coverage: pageViewCoverage(
view.offset,
selected.value.page.items.length,
selected.value.total,
),
})
: selected;
};
@@ -103,6 +103,7 @@ export const projectWasmArtifactView = (
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
format: parent.subject.format,
},
)
)
+24
View File
@@ -52,6 +52,30 @@ it("preserves omitted relationship diagnostics and authenticates reported diagno
).toThrow("semantic identifier");
});
it("projects known provider fields and preserves open JSON payloads", () => {
const liveProvider = { ...PROVIDER, transient_status: "starting" };
const evidence = createEvidence(TARGET, liveProvider, {
operation: "inspect",
parameters: { caller_metadata: { note: "kept" } },
result: { producer_extension: { value: "kept" } },
analysisProfile: PROFILE,
environment: {
id: "fixture",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
locations: [{ kind: "address", address: "0x1000" }],
});
expect(evidence.provider).toEqual(PROVIDER);
expect(evidence.parameters).toEqual({ caller_metadata: { note: "kept" } });
expect(evidence.normalized_result).toEqual({
producer_extension: { value: "kept" },
});
expect(parseEvidence(evidence)).toEqual(evidence);
});
it("preserves identity and bytes when reusing an owned immutable result", () => {
const value = { nested: { values: ["observed", 1] } };
const mutable = createEvidence(TARGET, PROVIDER, {
+12 -9
View File
@@ -33,14 +33,14 @@ import {
} from "./relationshipCoverage.js";
/** Provider identity schema shared by evidence-bearing persistence formats. */
export const providerSchema = z.object({
export const providerSchema = z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.object({
const subjectSchema = z.strictObject({
name: z.string().min(1),
digest: z.object({ sha256: digestSchema }),
digest: z.strictObject({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
@@ -78,15 +78,18 @@ const subjectSchema = z.object({
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("address"), address: z.string().min(1) }),
z.object({
z.strictObject({ kind: z.literal("address"), address: z.string().min(1) }),
z.strictObject({
kind: z.literal("address-range"),
start: z.string().min(1),
end: z.string().min(1),
}),
z.object({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
z.object({ kind: z.literal("file-offset"), offset: z.number().int().min(0) }),
z.object({
z.strictObject({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
z.strictObject({
kind: z.literal("file-offset"),
offset: z.number().int().min(0),
}),
z.strictObject({
kind: z.literal("file-offset-range"),
start: z.number().int().min(0),
end: z.number().int().min(0),
@@ -101,7 +104,7 @@ const evidenceAuthoritySchema = z.enum([
"analyst-inference",
]);
const executionEnvironmentSchema = z.object({
const executionEnvironmentSchema = z.strictObject({
id: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
+11 -8
View File
@@ -16,24 +16,27 @@ import {
} from "./residualUnknown.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
const artifactManifestSchema = evidenceSchema.shape.subject.unwrap().pick({
digest: true,
format: true,
architecture: true,
});
const artifactManifestSchema = evidenceSchema.shape.subject
.unwrap()
.pick({
digest: true,
format: true,
architecture: true,
})
.strict();
const providerManifestSchema = providerSchema;
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
const scenarioManifestSchema = z.object({
const scenarioManifestSchema = z.strictObject({
evidence_id: evidenceSchema.shape.evidence_id,
operation: z.string().min(1),
authority: z.literal("controlled-replay"),
});
const captureManifestSchema = z.object({
const captureManifestSchema = z.strictObject({
evidence_id: evidenceSchema.shape.evidence_id,
predicate_type: z.string().min(1),
});
export const evidenceBundleSchema = z.object({
export const evidenceBundleSchema = z.strictObject({
artifacts: z.array(artifactManifestSchema),
providers: z.array(providerManifestSchema),
environments: z.array(environmentManifestSchema),
+28
View File
@@ -119,6 +119,34 @@ const observe = (
);
describe("function comparison normalized identity", () => {
it("keeps differing generated names ambiguous and stable names mismatched", () => {
const named = (base: "0x1000" | "0x2000", name: string) =>
functionDossierSchema.parse({
...dossier("return 0;", base),
procedure: {
...procedure(base, name),
signature: "int helper(void)",
locals: [],
},
});
const generated = compareFunctions(
observe("1", named("0x1000", "sub_1000")),
observe("2", named("0x2000", "sub_2000")),
);
expect(generated.function_match.status).toBe("ambiguous");
expect(generated.status).toBe("unknown");
expect(
generated.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
const stable = compareFunctions(
observe("3", named("0x1000", "firstFunction")),
observe("4", named("0x2000", "secondFunction")),
);
expect(stable.function_match.status).toBe("mismatched");
expect(stable.status).toBe("changed");
});
it.each(["sub_deallocate", "sub_deadbeef_handler", "fcn.dispatch"])(
"recognizes the explicit symbol %s without a generated-name prefix false positive",
(name) => {
+9 -12
View File
@@ -16,24 +16,21 @@ export const functionMatch = (
left: FunctionSnapshot,
right: FunctionSnapshot,
): FunctionComparisonResult["function_match"] => {
if (
!isAutoName(left.dossier.procedure.name) &&
left.dossier.procedure.name === right.dossier.procedure.name
)
const leftName = left.dossier.procedure.name;
const rightName = right.dossier.procedure.name;
const stableNames = !isAutoName(leftName) && !isAutoName(rightName);
if (stableNames && leftName === rightName)
return {
status: "matched",
method: "symbol",
left_name: left.dossier.procedure.name,
right_name: right.dossier.procedure.name,
left_name: leftName,
right_name: rightName,
};
return {
status:
left.dossier.procedure.name === right.dossier.procedure.name
? "ambiguous"
: "mismatched",
status: stableNames ? "mismatched" : "ambiguous",
method: "explicit",
left_name: left.dossier.procedure.name,
right_name: right.dossier.procedure.name,
left_name: leftName,
right_name: rightName,
};
};
@@ -6,6 +6,7 @@ import {
} from "./javascriptApplicationGraph.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
import { resolveJavaScriptSourceMapReferences } from "./javascriptSourceMapPaths.js";
export const APPLICATION_GRAPH_DIGESTS = {
package: "1".repeat(64),
@@ -22,6 +23,20 @@ export const completeCoverage = {
limits: [],
} satisfies ApplicationGraphEvidence["coverage"];
export const sourceMapReference = (
sourceName: string,
sourceRoot: string | null,
mapPath: string,
) => {
const reference = resolveJavaScriptSourceMapReferences(
[sourceName],
sourceRoot,
mapPath,
)[0];
if (reference == null) throw new TypeError("Expected a source-map reference");
return reference;
};
const extractor = (operation: string) => ({
name: "rea-test-fixture",
version: "1.0.0",
@@ -20,10 +20,9 @@ import {
inferredArtifactEvidence,
nodeByLabel,
runtimeEvidence,
sourceMapReference,
unknownEvidence,
} from "./javascriptApplicationGraph.fixture.js";
import { resolveJavaScriptSourceMapReference } from "./javascriptSourceMapPaths.js";
const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
const properties = Object.fromEntries(
Array.from({ length: 1_001 }, (_, index) => [
@@ -438,7 +437,7 @@ describe("JavaScript Application Graph: source maps and observations", () => {
observations: [
{
label: "src/editor.ts",
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"webpack:///src/editor.ts",
null,
"dist/app.js.map",
@@ -535,7 +534,7 @@ describe("JavaScript Application Graph: source-map digest consistency", () => {
observations: [
{
label: null,
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"src/editor.ts",
null,
"dist/app.js.map",
@@ -1,5 +1,6 @@
import { posix } from "node:path";
import { domainToASCII, fileURLToPath, pathToFileURL } from "node:url";
import { TraceMap } from "@jridgewell/trace-mapping";
import { z } from "zod";
@@ -25,22 +26,64 @@ export type JavaScriptSourceMapReference = z.infer<
typeof javascriptSourceMapReferenceSchema
>;
/** Interpret a declaration once at the source-map ingestion boundary. */
export const resolveJavaScriptSourceMapReference = (
sourceName: string,
/** Interpret declarations together once at their source-map ingestion boundary. */
export const resolveJavaScriptSourceMapReferences = (
sourceNames: readonly (string | null)[],
sourceRoot: string | null,
mapPath: string,
): JavaScriptSourceMapReference => {
// TraceMap's producer prefixes sourceRoot before resolving the URL reference.
const reference = `${sourceRoot ? `${sourceRoot}/` : ""}${sourceName}`;
return {
source_name: sourceName,
source_root: sourceRoot,
map_path: mapPath,
resolution: resolveJavaScriptSourceMapPath(reference, mapPath),
};
): (JavaScriptSourceMapReference | null)[] => {
if (sourceNames.length === 0) return [];
const resolvedSources = resolveSourceMapUrls(
sourceNames.map((sourceName) => sourceName ?? ""),
sourceRoot,
"",
);
return sourceNames.map((sourceName, index) => {
if (sourceName === null) return null;
const reference = resolvedSources[index];
if (reference === undefined)
throw new TypeError(
`TraceMap did not resolve source declaration ${String(index)}`,
);
return {
source_name: sourceName,
source_root: sourceRoot,
map_path: mapPath,
resolution: resolveJavaScriptSourceMapPath(reference, mapPath),
};
});
};
/** Resolve a source declaration using the same pinned format implementation as map consumers. */
export const resolveJavaScriptSourceMapUrl = (
source: string | null,
sourceRoot: string | null | undefined,
mapUrl: string,
): string => {
const resolved = resolveSourceMapUrls([source ?? ""], sourceRoot, mapUrl)[0];
if (resolved === undefined)
throw new TypeError(
"TraceMap did not resolve its single source declaration",
);
return resolved;
};
const resolveSourceMapUrls = (
sources: string[],
sourceRoot: string | null | undefined,
mapUrl: string,
): readonly string[] =>
new TraceMap(
{
version: 3,
names: [],
sources,
...(sourceRoot == null ? {} : { sourceRoot }),
mappings: "",
},
mapUrl,
).resolvedSources;
/** Resolve a source-map URL reference without changing its recorded identity. */
const resolveJavaScriptSourceMapPath = (
source: string,
@@ -1,10 +1,11 @@
import { describe, expect, it } from "vitest";
import { TraceMap } from "@jridgewell/trace-mapping";
import { resolveJavaScriptSourceMapReference } from "./javascriptSourceMapPaths.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "./javascriptApplicationGraph.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import { createHistoricalSourceGraph } from "../referenceSourceGraph.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { compareSourceToBundle } from "./sourceToBundleComparison.js";
@@ -12,7 +13,10 @@ import {
SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS,
sourceToBundleComparisonResultSchema,
} from "./sourceToBundleComparisonSchemas.js";
import { artifactEvidence } from "./javascriptApplicationGraph.fixture.js";
import {
artifactEvidence,
sourceMapReference,
} from "./javascriptApplicationGraph.fixture.js";
const HASH = {
artifact: "1".repeat(64),
@@ -42,9 +46,6 @@ describe("historical source to bundle comparison", () => {
const second = compareSourceToBundle(input);
expect(first).toEqual(second);
expect(() =>
sourceToBundleComparisonResultSchema.parse(first),
).not.toThrow();
expect(first.summary).toEqual({
unchanged: 1,
modified: 0,
@@ -153,7 +154,7 @@ describe("source to bundle digest changes", () => {
observations: [
{
label: "display label",
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"webpack://fixture/./src/modified.ts",
null,
"dist/main.js.map",
@@ -202,6 +203,90 @@ describe("source to bundle digest changes", () => {
});
});
describe("source to bundle Unicode path collisions", () => {
it("keeps colliding canonical-equivalent current paths ambiguous", () => {
const historicalPath = "src/a\u0301\u0323.ts";
const currentPaths = ["src/a\u0323\u0301.ts", "src/\u1ea1\u0301.ts"];
const nodes = currentPaths.map((path, index) =>
moduleNode(`unicode-${index}`, { path }),
);
const result = comparePathToNodes(historicalPath, nodes);
const mapping = item(result, historicalPath);
expect(mapping).toMatchObject({
status: "unknown",
confidence: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({ kind: "unicode-equivalent-path" }),
]),
}),
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({ kind: "unicode-equivalent-path" }),
]),
}),
],
limitations: [
expect.stringContaining(
"filesystem paths with distinct Unicode spellings",
),
],
});
});
it("prefers a raw source-map path over canonically equivalent alternatives", () => {
const historicalPath = "src/cafe\u0301.ts";
const exact = sourceMapNode(
"exact",
"cafe\u0301.ts",
"../src/",
HASH.modified,
);
const equivalent = sourceMapNode(
"equivalent",
"caf\u00e9.ts",
"../src/",
HASH.removed,
);
const result = comparePathToNodes(historicalPath, [exact, equivalent]);
expect(item(result, historicalPath)).toMatchObject({
status: "modified",
current_node_ids: [exact.node_id],
});
});
it("finds Unicode-equivalent suffixes of absolute source-map URLs", () => {
const historicalPath = "src/caf\u00e9.ts";
const node = sourceMapNode(
"remote",
"cafe\u0301.ts",
"https://cdn.example/src/",
HASH.modified,
);
const result = comparePathToNodes(historicalPath, [node]);
expect(item(result, historicalPath)).toMatchObject({
status: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
current_node_id: node.node_id,
signals: expect.arrayContaining([
expect.objectContaining({
kind: "unicode-equivalent-path",
current_values: ["cdn.example/src/cafe\u0301.ts"],
}),
]),
}),
],
});
});
});
describe("source to bundle path syntax", () => {
it.each([
"src/modified#part.ts",
@@ -282,9 +367,60 @@ describe("source to bundle path syntax", () => {
}),
],
});
expect(
item(result, "src/modified.ts").candidates.flatMap(
({ signals }) => signals,
),
).not.toContainEqual(
expect.objectContaining({ kind: "unicode-equivalent-path" }),
);
});
});
describe("source-map resolver equivalence", () => {
it.each([
{
sourceRoot: "https://cdn.example/src/",
expectedSource: "https://cdn.example/src/a.js",
expectedResolution: { kind: "suffix", path: "cdn.example/src/a.js" },
},
{
sourceRoot: "https://cdn.example/src//",
expectedSource: "https://cdn.example/src/a.js",
expectedResolution: { kind: "suffix", path: "cdn.example/src/a.js" },
},
{
sourceRoot: "webpack://",
expectedSource: "webpack:///a.js",
expectedResolution: { kind: "suffix", path: "a.js" },
},
])(
"matches TraceMap for sourceRoot $sourceRoot",
({ sourceRoot, expectedSource, expectedResolution }) => {
const producerSource = new TraceMap(
{
version: 3,
file: "main.js",
sourceRoot,
sources: ["a.js"],
names: [],
mappings: "",
},
"file:///artifact/dist/main.js.map",
).resolvedSources[0];
const reference = sourceMapReference(
"a.js",
sourceRoot,
"dist/main.js.map",
);
expect(producerSource).toBe(expectedSource);
expect(reference.source_root).toBe(sourceRoot);
expect(reference.resolution).toEqual(expectedResolution);
},
);
});
describe("source to bundle complete metadata", () => {
it("accepts long source metadata and all reported limitations", () => {
const result = compareSourceToBundle({
@@ -328,6 +464,61 @@ describe("source to bundle complete metadata", () => {
});
});
const sourceMapNode = (
key: string,
sourceName: string,
sourceRoot: string,
digest: string,
) =>
createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
source_root: sourceRoot,
stability: "source-map-exact",
source_map_sha256: HASH.artifact,
original_source: sourceName,
source_sha256: digest,
},
observations: [
{
label: `${key} source-map spelling`,
source_map_reference: sourceMapReference(
sourceName,
sourceRoot,
`dist/${key}.map`,
),
properties: { content_available: true, content_sha256: digest },
evidence: artifactEvidence(HASH.artifact, `dist/${key}.map`),
},
],
});
const comparePathToNodes = (
sourcePath: string,
nodes: readonly ApplicationNode[],
) =>
compareSourceToBundle({
reference: historicalGraph("complete", [sourcePath]),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: nodes.map(({ node_id: nodeId }) => nodeId),
nodes,
edges: [],
coverage: {
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
},
limitations: [],
}),
},
});
const historicalGraph = (
inventoryState: "complete" | "partial",
paths = [
@@ -258,7 +258,11 @@ const classifyMapping = (
confidence: "unknown",
currentNodeIds: [],
limitations: [
"Only weak basename or extension signals were available; no mapping was forced.",
candidates.some((candidate) =>
hasSignal(candidate, "unicode-equivalent-path"),
)
? "Unicode-equivalent paths are inferred candidates only; filesystem paths with distinct Unicode spellings may identify different files, so no mapping was forced."
: "Only weak basename or extension signals were available; no mapping was forced.",
],
};
return absenceComplete
@@ -15,6 +15,7 @@ export const SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS = [
["source-map-original-path", 70],
["current-path-exact", 60],
["current-path-suffix", 40],
["unicode-equivalent-path", 20],
["basename-match", 20],
["language-extension", 5],
] as const;
@@ -24,6 +25,7 @@ const sourceToBundleSignalKindSchema = z.enum([
"source-map-original-path",
"current-path-exact",
"current-path-suffix",
"unicode-equivalent-path",
"basename-match",
"language-extension",
]);
+38 -1
View File
@@ -102,8 +102,12 @@ export const buildSourceToBundleCandidateIndex = (
for (const path of projection.paths) {
for (const suffix of path.allowSuffix
? pathSuffixes(path.value)
: [path.value])
: [path.value]) {
addIndexValue(byPathSuffix, suffix, projection.node.node_id);
const canonical = suffix.normalize("NFC");
if (canonical !== suffix)
addIndexValue(byPathSuffix, canonical, projection.node.node_id);
}
addIndexValue(
byBasename,
posix.basename(path.value),
@@ -126,9 +130,13 @@ export const candidateIdsForSource = (
source: SourceFile,
index: SourceToBundleCandidateIndex,
): string[] => {
const canonicalPath = source.path.normalize("NFC");
const groups = [
source.sha256 === null ? undefined : index.byDigest.get(source.sha256),
index.byPathSuffix.get(source.path),
canonicalPath === source.path
? undefined
: index.byPathSuffix.get(canonicalPath),
index.byBasename.get(posix.basename(source.path)),
];
const seen = new Set<string>();
@@ -220,6 +228,14 @@ const candidateSignals = (
signals.push(
signal("source-map-original-path", source.path, sourceMapPaths),
);
const unicodeEquivalentPaths = matchingUnicodePaths(
source.path,
current.paths,
);
if (unicodeEquivalentPaths.length > 0)
signals.push(
signal("unicode-equivalent-path", source.path, unicodeEquivalentPaths),
);
const otherPaths = current.paths.filter(
({ kind }) => kind !== "source-map-original",
);
@@ -286,6 +302,27 @@ const matchingPaths = (
)
.map(({ value }) => value);
const matchingUnicodePaths = (
sourcePath: string,
currentPaths: readonly CurrentPath[],
): string[] => {
const canonicalSource = sourcePath.normalize("NFC");
return currentPaths
.filter(({ value, allowSuffix }) => {
if (
value === sourcePath ||
(allowSuffix && value.endsWith(`/${sourcePath}`))
)
return false;
const canonicalValue = value.normalize("NFC");
return (
canonicalValue === canonicalSource ||
(allowSuffix && canonicalValue.endsWith(`/${canonicalSource}`))
);
})
.map(({ value }) => value);
};
const addJsonPath = (paths: CurrentPath[], value: unknown): void => {
if (typeof value === "string") addPath(paths, "observation-path", value);
};
+2 -1
View File
@@ -204,7 +204,8 @@ const buildReconstructionSummary = (
({ reconstruction }) => reconstruction.kind === "semantic-pseudocode",
).length,
total_text_bytes: methods.reduce(
(total, { reconstruction }) => total + reconstruction.text_length,
(total, { reconstruction }) =>
total + Buffer.byteLength(reconstruction.text, "utf8"),
0,
),
});
+83
View File
@@ -1,5 +1,11 @@
import { z } from "zod";
export interface OffsetDateTimeInstant {
readonly epochSecond: number;
/** Exact fractional second with insignificant trailing zeroes removed. */
readonly fraction: string;
}
/**
* ISO-8601 date-time that requires an explicit UTC offset.
*
@@ -19,3 +25,80 @@ export const offsetDateTimeSchema = z
/^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|(?:[+\x2d](?:[01]\d|2[0-3]):[0-5]\d)))$/u,
"Use an ISO-8601 date-time with an explicit UTC offset",
);
/** Parse an already validated offset timestamp without losing sub-millisecond precision. */
export const parseOffsetDateTimeInstant = (
value: string,
): OffsetDateTimeInstant => {
const match = /^(.*?)(?:\.(\d+))?(Z|[+\x2d]\d{2}:\d{2})$/u.exec(value);
if (match === null)
throw new TypeError("Expected a validated offset date-time.");
const [, dateTime, fractionalDigits, offset] = match;
if (dateTime === undefined || offset === undefined)
throw new TypeError("Expected a validated offset date-time.");
const wholeSecondMilliseconds = Date.parse(`${dateTime}${offset}`);
if (
!Number.isSafeInteger(wholeSecondMilliseconds) ||
wholeSecondMilliseconds % 1000 !== 0
)
throw new TypeError(
"Offset date-time is outside the supported time range.",
);
return {
epochSecond: wholeSecondMilliseconds / 1000,
fraction: fractionalDigits?.replace(/0+$/u, "") ?? "",
};
};
/** Convert a Date.now-style integer into the same exact comparison shape. */
export const offsetDateTimeInstantFromEpochMilliseconds = (
epochMilliseconds: number,
): OffsetDateTimeInstant => {
if (!Number.isFinite(epochMilliseconds))
throw new TypeError("Expected finite epoch milliseconds.");
if (Math.abs(epochMilliseconds) > Number.MAX_SAFE_INTEGER)
return { epochSecond: epochMilliseconds / 1000, fraction: "" };
const epochSecond = Math.floor(epochMilliseconds / 1000);
const millisecondsWithinSecond = epochMilliseconds - epochSecond * 1000;
return {
epochSecond,
fraction: fractionalSecondFromMilliseconds(millisecondsWithinSecond),
};
};
const fractionalSecondFromMilliseconds = (milliseconds: number): string => {
if (milliseconds === 0) return "";
const [coefficient = "", exponentText] = String(milliseconds)
.toLowerCase()
.split("e");
const exponent = exponentText === undefined ? 0 : Number(exponentText);
const point = coefficient.indexOf(".");
const decimalPosition =
(point < 0 ? coefficient.length : point) + exponent - 3;
const digits = coefficient.replace(".", "");
const fraction =
decimalPosition <= 0
? `0.${"0".repeat(-decimalPosition)}${digits}`
: decimalPosition < digits.length
? `${digits.slice(0, decimalPosition)}.${digits.slice(decimalPosition)}`
: `${digits}${"0".repeat(decimalPosition - digits.length)}`;
return (
fraction.includes(".") ? fraction.slice(fraction.indexOf(".") + 1) : ""
).replace(/0+$/u, "");
};
/** Compare instants exactly while treating absent fraction digits as zeroes. */
export const compareOffsetDateTimeInstants = (
left: OffsetDateTimeInstant,
right: OffsetDateTimeInstant,
): number => {
if (left.epochSecond !== right.epochSecond)
return left.epochSecond < right.epochSecond ? -1 : 1;
const length = Math.max(left.fraction.length, right.fraction.length);
for (let index = 0; index < length; index += 1) {
const leftDigit = left.fraction.charCodeAt(index) || 48;
const rightDigit = right.fraction.charCodeAt(index) || 48;
if (leftDigit !== rightDigit) return leftDigit < rightDigit ? -1 : 1;
}
return 0;
};
+110
View File
@@ -0,0 +1,110 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { digestSchema } from "../digests.js";
/**
* Caller intent for packet-capture analysis through caller-supplied tshark
* and capinfos. REA never installs Wireshark or its tools.
*/
export const pcapInputSchemas = {
inspect_pcap_client: z.strictObject({}),
inspect_pcap_capture: z.strictObject({
path: localPathStringSchema.describe(
"Local pcap or pcapng capture file to inspect",
),
}),
} as const;
/** Supported pcap-backed operations. */
export type PcapOperation = keyof typeof pcapInputSchemas;
/** Validated pcap requests carry their selected operation. */
export type PcapRequest = {
[Name in PcapOperation]: {
operation: Name;
input: z.infer<(typeof pcapInputSchemas)[Name]>;
};
}[PcapOperation];
/** Validate operation and input together so their types remain correlated. */
export const pcapRequestSchema = z.discriminatedUnion("operation", [
z.strictObject({
operation: z.literal("inspect_pcap_client"),
input: pcapInputSchemas.inspect_pcap_client,
}),
z.strictObject({
operation: z.literal("inspect_pcap_capture"),
input: pcapInputSchemas.inspect_pcap_capture,
}),
]);
const client = z.strictObject({
tshark_command: z.string().min(1),
tshark_source: z.enum(["environment", "path"]),
tshark_version: z.string().min(1).nullable(),
capinfos_command: z.string().min(1),
capinfos_source: z.enum(["environment", "path"]),
capinfos_version: z.string().min(1).nullable(),
});
const endpoint = z.strictObject({
address: z.string().min(1),
port: z.number().int().positive().nullable(),
packet_count: z.number().int().positive(),
});
const dnsQuery = z.strictObject({
query: z.string().min(1),
response_addresses: z.array(z.string().min(1)),
response_address_count: z.number().int().nonnegative(),
});
const protocolCount = z.strictObject({
protocol: z.string().min(1),
packet_count: z.number().int().positive(),
});
/** Portable pcap observations with explicit coverage limitations. */
export const pcapResultSchemas = {
inspect_pcap_client: z.strictObject({
client,
}),
inspect_pcap_capture: z.strictObject({
client,
target: z.strictObject({
path: localPathStringSchema,
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
}),
/** File format as capinfos reports it (pcap vs pcapng). */
file_type: z.string().min(1).nullable(),
encapsulation: z.string().min(1).nullable(),
packet_count: z.number().int().nonnegative().nullable(),
capture_start: z.string().nullable(),
capture_end: z.string().nullable(),
capture_duration_seconds: z.number().nonnegative().nullable(),
snapshot_length: z.number().int().positive().nullable(),
/** Distinct endpoints with packet counts, bounded. */
endpoints: z.array(endpoint),
endpoint_count: z.number().int().nonnegative(),
/** DNS queries with resolved addresses, bounded. */
dns_queries: z.array(dnsQuery),
dns_query_count: z.number().int().nonnegative(),
/** TLS Server Name Indication values observed in handshakes. */
tls_sni_values: z.array(z.string().min(1)),
tls_sni_count: z.number().int().nonnegative(),
/** Protocol distribution (frame.protocols column counts). */
protocol_distribution: z.array(protocolCount),
protocol_count: z.number().int().nonnegative(),
/** HTTP request URIs seen on plain-text ports, bounded. */
http_request_uris: z.array(z.string().min(1)),
http_request_uri_count: z.number().int().nonnegative(),
http_uri_redaction_count: z.number().int().nonnegative(),
unattributed_dns_addresses: z.array(z.string().min(1)),
unattributed_dns_address_count: z.number().int().nonnegative(),
unattributed_dns_packet_count: z.number().int().nonnegative(),
coverage: z.enum(["complete", "partial"]),
diagnostics: z
.strictObject({ capinfos_stderr: z.string(), tshark_stderr: z.string() })
.optional(),
}),
} as const;
+34
View File
@@ -0,0 +1,34 @@
import { createEvidence } from "../evidence.js";
import { jsonObjectSchema, type JsonValue } from "../jsonValue.js";
import type { PcapRequest } from "./pcapAnalysis.js";
/** Domain facts needed by both successful and retained partial observations. */
interface PcapObservation {
readonly subject: Parameters<typeof createEvidence>[0] | null;
readonly provider: Parameters<typeof createEvidence>[1];
readonly result: JsonValue;
readonly rawResult: JsonValue | null;
readonly limitations: readonly string[];
readonly locations: NonNullable<
Parameters<typeof createEvidence>[2]["locations"]
>;
}
/** One owner commits packet aggregation provenance and caller intent into Evidence. */
export const createPcapEvidence = (
request: PcapRequest,
observation: PcapObservation,
) =>
createEvidence(observation.subject ?? undefined, observation.provider, {
operation: request.operation,
parameters: jsonObjectSchema.parse(request.input),
result: observation.result,
rawResult: observation.rawResult,
limitations: observation.limitations,
locations: observation.locations,
confidence:
request.operation === "inspect_pcap_capture" ? "derived" : "observed",
...(request.operation === "inspect_pcap_capture"
? { authority: "historical-reference" as const }
: {}),
});
@@ -39,30 +39,110 @@ const specification = (): ProcessTraceSpecification => ({
});
describe("process trace specification", () => {
it("summarizes an incomplete language with its exact missing pair count", () => {
const events = Array.from({ length: 200 }, (_, index) => ({
id: `e${String(index)}`,
it("reports independent declaration errors alongside a cycle", () => {
const base = specification();
const result = processTraceSpecificationSchema.safeParse({
...base,
language: {
...base.language,
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
not_before: [{ event: "missing", anchor: "ready" }],
unordered_groups: [{ events: ["missing", "missing"] }],
prefix: ["missing"],
suffix: ["missing"],
},
});
if (result.success) throw new Error("Expected invalid trace declarations");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: "happens-before graph must be acyclic",
}),
expect.objectContaining({
path: ["language", "not_before", 0, "event"],
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0, "events"],
}),
expect.objectContaining({ path: ["language", "prefix", 0] }),
expect.objectContaining({ path: ["language", "suffix", 0] }),
]),
);
});
it("accepts an acyclic order with shared successors and explicit unordered peers", () => {
const result = processTraceSpecificationSchema.parse({
events: ["a", "b", "c", "d"].map((id) => ({
id,
source: "lifecycle",
exact: { marker: id },
})),
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "a", after: "c" },
{ before: "b", after: "d" },
{ before: "c", after: "d" },
],
unordered_groups: [{ events: ["b", "c"] }],
prefix: ["a"],
suffix: ["d"],
},
});
expect(result.language.kind).toBe("partial_order");
});
});
describe("process trace ordering validation", () => {
it("uses a unique topological order for transitive declarations and conflicts", () => {
const events = ["a", "b", "c"].map((id) => ({
id,
source: "lifecycle" as const,
exact: { fixture: index },
exact: { marker: id },
cardinality: { kind: "optional" as const },
}));
const result = processTraceSpecificationSchema.safeParse({
const accepted = processTraceSpecificationSchema.safeParse({
events,
language: { kind: "partial_order" },
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "b", after: "c" },
],
},
});
expect(result.success).toBe(false);
if (result.success)
throw new Error("Expected incomplete pair declarations");
expect(result.error.issues).toEqual([
expect(accepted.success).toBe(true);
const rejected = processTraceSpecificationSchema.safeParse({
events,
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "b", after: "c" },
],
not_before: [{ event: "a", anchor: "c" }],
unordered_groups: [{ events: ["a", "b", "c"] }],
},
});
if (rejected.success) throw new Error("Expected ordered pair conflicts");
expect(rejected.error.issues).toEqual([
expect.objectContaining({
path: ["language"],
message:
"19900 event pairs must be explicitly ordered or unordered; first undeclared pair: e0/e1",
path: ["language", "not_before", 0],
message: "not-before constraint conflicts with happens-before order",
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0],
message: "ordered events cannot also be declared unordered",
}),
]);
});
it("counts only undeclared pairs after transitive, not-before and unordered relations", () => {
it("counts only undeclared pairs across transitive and disconnected relations", () => {
const events = ["a", "b", "c", "d"].map((id) => ({
id,
source: "lifecycle" as const,
@@ -91,7 +171,7 @@ describe("process trace specification", () => {
]);
});
it("retains duplicate unordered-pair diagnostics for reversed declarations", () => {
it("reports one duplicate-pair diagnostic per overlapping group", () => {
const result = processTraceSpecificationSchema.safeParse({
events: ["z", "a", "b"].map((id) => ({
id,
@@ -101,7 +181,10 @@ describe("process trace specification", () => {
})),
language: {
kind: "partial_order",
unordered_groups: [{ events: ["z", "a", "b"] }, { events: ["a", "z"] }],
unordered_groups: [
{ events: ["z", "a", "b"] },
{ events: ["b", "a", "z"] },
],
},
});
expect(result.success).toBe(false);
@@ -113,27 +196,84 @@ describe("process trace specification", () => {
}),
]);
});
});
it("rejects cycles, implicit ordering gaps, invalid ignores, and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
describe("malformed process trace declarations", () => {
it("preserves independent diagnostics when event ids are duplicated", () => {
const result = processTraceSpecificationSchema.safeParse({
events: [
{
id: "a",
source: "lifecycle",
exact: { fixture: "first" },
cardinality: { kind: "optional" },
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: { kind: "partial_order" },
}).success,
).toBe(false);
{
id: "a",
source: "lifecycle",
exact: { fixture: "second" },
cardinality: { kind: "optional" },
},
],
language: {
kind: "partial_order",
unordered_groups: [{ events: ["a", "b"] }],
},
});
expect(result.success).toBe(false);
if (result.success) throw new Error("Expected a duplicate event id");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: ["events", 1, "id"],
message: "event ids must be unique",
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0, "events", 1],
message: "unknown event id: b",
}),
]),
);
});
it("keeps reachability diagnostics for unknown referenced successors", () => {
const result = processTraceSpecificationSchema.safeParse({
events: ["a", "b"].map((id) => ({
id,
source: "lifecycle",
exact: { fixture: id },
cardinality: { kind: "optional" },
})),
language: {
kind: "partial_order",
happens_before: [{ before: "a", after: "missing" }],
not_before: [{ event: "a", anchor: "missing" }],
},
});
expect(result.success).toBe(false);
if (result.success) throw new Error("Expected an unknown event reference");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: ["language", "happens_before", 0, "after"],
message: "unknown event id: missing",
}),
expect.objectContaining({
path: ["language", "not_before", 0, "anchor"],
message: "unknown event id: missing",
}),
expect.objectContaining({
path: ["language", "not_before", 0],
message: "not-before constraint conflicts with happens-before order",
}),
]),
);
});
});
describe("finite trace specification validation", () => {
it("rejects invalid ignores and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
events: [
+252 -92
View File
@@ -106,6 +106,17 @@ export type ProcessTraceSpecification = z.infer<
>;
type PartialOrderLanguage = z.infer<typeof partialOrderLanguageSchema>;
type AcyclicGraphFacts =
| {
readonly kind: "total-order";
readonly rank: ReadonlyMap<string, number>;
}
| {
readonly kind: "partial-order";
readonly reverseAdjacency: ReadonlyMap<string, ReadonlySet<string>>;
};
type GraphFacts = { readonly kind: "cyclic" } | AcyclicGraphFacts;
export const canonicalTraceJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
@@ -170,7 +181,6 @@ const validateNotBefore = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
reachable: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlySet<string> => {
const pairs = new Set<string>();
for (const [index, constraint] of language.not_before.entries()) {
@@ -191,76 +201,101 @@ const validateNotBefore = (
path,
});
pairs.add(key);
if (reachable.get(constraint.event)?.has(constraint.anchor) === true)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path,
});
}
return pairs;
};
const graphHasCycle = (
const classifyGraph = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): boolean => {
const active = new Set<string>();
const complete = new Set<string>();
const visit = (current: string): boolean => {
if (active.has(current)) return true;
if (complete.has(current)) return false;
active.add(current);
const cyclic = [...(adjacency.get(current) ?? [])].some(visit);
active.delete(current);
complete.add(current);
return cyclic;
};
return ids.some(visit);
};
const computeReachability = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlyMap<string, ReadonlySet<string>> => {
const reachable = new Map<string, Set<string>>();
for (const origin of ids) {
const seen = new Set<string>();
const pending = [...(adjacency.get(origin) ?? [])];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || seen.has(current)) continue;
seen.add(current);
pending.push(...(adjacency.get(current) ?? []));
): GraphFacts => {
const incoming = new Map(ids.map((id) => [id, 0]));
let hasUnknownSuccessor = false;
for (const successors of adjacency.values())
for (const successor of successors) {
const count = incoming.get(successor);
if (count === undefined) hasUnknownSuccessor = true;
else incoming.set(successor, count + 1);
}
const ready = [...incoming].flatMap(([id, count]) =>
count === 0 ? [id] : [],
);
const order: string[] = [];
let unique = true;
while (ready.length > 0) {
if (ready.length !== 1) unique = false;
const current = ready.pop();
if (current === undefined) continue;
order.push(current);
for (const successor of adjacency.get(current) ?? []) {
const count = incoming.get(successor);
if (count === undefined) continue;
incoming.set(successor, count - 1);
if (count === 1) ready.push(successor);
}
reachable.set(origin, seen);
}
return reachable;
if (order.length !== incoming.size) return { kind: "cyclic" };
if (unique && order.length === ids.length && !hasUnknownSuccessor) {
return {
kind: "total-order",
rank: new Map(order.map((id, index) => [id, index])),
};
}
const reverseAdjacency = new Map(
[...incoming.keys()].map((id) => [id, new Set<string>()]),
);
for (const [before, successors] of adjacency)
for (const after of successors) reverseAdjacency.get(after)?.add(before);
return { kind: "partial-order", reverseAdjacency };
};
const isOrdered = (
reachable: ReadonlyMap<string, ReadonlySet<string>>,
left: string,
right: string,
): boolean =>
reachable.get(left)?.has(right) === true ||
reachable.get(right)?.has(left) === true;
type OrderingRelations = {
readonly reachable: ReadonlyMap<string, ReadonlySet<string>>;
readonly notBeforePairs: ReadonlySet<string>;
const collectReachable = (
origin: string,
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlySet<string> => {
const seen = new Set<string>();
const pending = [...(adjacency.get(origin) ?? [])];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || seen.has(current)) continue;
seen.add(current);
for (const successor of adjacency.get(current) ?? [])
pending.push(successor);
}
return seen;
};
const validateUnorderedGroups = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
relations: OrderingRelations,
): ReadonlySet<string> => {
const pairs = new Set<string>();
): {
readonly groups: readonly ReadonlySet<string>[];
hasPair(left: string, right: string): boolean;
markDeclaredPairConflicts(
pairs: ReadonlySet<string>,
conflicts: boolean[],
): void;
markSharedGroups(left: string, right: string, conflicts: boolean[]): void;
} => {
const memberships = new Map<string, Set<number>>();
const groups: Set<string>[] = [];
const repeatedMemberships = new Map<string, Set<number>>();
for (const [groupIndex, group] of language.unordered_groups.entries()) {
const path = ["language", "unordered_groups", groupIndex];
if (new Set(group.events).size !== group.events.length)
const uniqueIds = new Set<string>();
const repeatedIds = new Set<string>();
for (const id of group.events) {
if (uniqueIds.has(id)) repeatedIds.add(id);
else uniqueIds.add(id);
}
groups.push(uniqueIds);
for (const id of repeatedIds) {
const groupIndexes = repeatedMemberships.get(id) ?? new Set<number>();
groupIndexes.add(groupIndex);
repeatedMemberships.set(id, groupIndexes);
}
if (uniqueIds.size !== group.events.length)
context.addIssue({
code: "custom",
message: "unordered groups must not repeat event ids",
@@ -268,46 +303,136 @@ const validateUnorderedGroups = (
});
for (const [eventIndex, id] of group.events.entries())
addReferenceIssue(context, known, id, [...path, "events", eventIndex]);
for (const [leftIndex, leftId] of group.events.entries()) {
for (
let rightIndex = leftIndex + 1;
rightIndex < group.events.length;
rightIndex++
) {
const rightId = group.events[rightIndex];
if (rightId === undefined) continue;
const key = pairKey(leftId, rightId);
if (pairs.has(key))
context.addIssue({
code: "custom",
message: "unordered event pairs must be declared once",
path,
});
pairs.add(key);
if (
isOrdered(relations.reachable, leftId, rightId) ||
relations.notBeforePairs.has(key)
)
context.addIssue({
code: "custom",
message: "ordered events cannot also be declared unordered",
path,
});
}
const overlaps = new Map<number, number>();
for (const id of uniqueIds) {
const priorGroups = memberships.get(id) ?? new Set<number>();
for (const prior of priorGroups)
overlaps.set(prior, (overlaps.get(prior) ?? 0) + 1);
priorGroups.add(groupIndex);
memberships.set(id, priorGroups);
}
if ([...overlaps.values()].some((count) => count > 1))
context.addIssue({
code: "custom",
message: "unordered event pairs must be declared once",
path,
});
}
return pairs;
const markSharedGroups = (
left: string,
right: string,
conflicts: boolean[],
): void => {
if (left === right) {
for (const groupIndex of repeatedMemberships.get(left) ?? [])
conflicts[groupIndex] = true;
return;
}
const rightGroups = memberships.get(right);
for (const group of memberships.get(left) ?? [])
if (rightGroups?.has(group) === true) conflicts[group] = true;
};
return {
groups,
hasPair(left, right) {
if (left === right) return memberships.has(left);
const rightGroups = memberships.get(right);
for (const group of memberships.get(left) ?? [])
if (rightGroups?.has(group) === true) return true;
return false;
},
markDeclaredPairConflicts(pairs, conflicts) {
for (const key of pairs) {
const separator = key.indexOf("\0");
const left = key.slice(0, separator);
const right = key.slice(separator + 1);
markSharedGroups(left, right, conflicts);
}
},
markSharedGroups,
};
};
const validateCompletePairDeclarations = (
const validateTotalOrderRelations = (
language: PartialOrderLanguage,
graph: Extract<GraphFacts, { kind: "total-order" }>,
unorderedGroups: ReturnType<typeof validateUnorderedGroups>,
notBeforePairs: ReadonlySet<string>,
context: z.RefinementCtx,
): void => {
for (const [index, constraint] of language.not_before.entries()) {
const before = graph.rank.get(constraint.event);
const after = graph.rank.get(constraint.anchor);
if (before !== undefined && after !== undefined && before < after)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path: ["language", "not_before", index],
});
}
const conflicts = new Array<boolean>(language.unordered_groups.length).fill(
false,
);
for (const [groupIndex, group] of unorderedGroups.groups.entries()) {
let comparableEvents = 0;
for (const id of group)
if (graph.rank.has(id) && ++comparableEvents === 2) {
conflicts[groupIndex] = true;
break;
}
}
unorderedGroups.markDeclaredPairConflicts(notBeforePairs, conflicts);
addUnorderedConflictIssues(conflicts, context);
};
const addUnorderedConflictIssues = (
conflicts: readonly boolean[],
context: z.RefinementCtx,
): void => {
for (const [groupIndex, conflict] of conflicts.entries())
if (conflict)
context.addIssue({
code: "custom",
message: "ordered events cannot also be declared unordered",
path: ["language", "unordered_groups", groupIndex],
});
};
const validatePartialOrderRelations = (
ids: readonly string[],
relations: OrderingRelations,
unorderedPairs: ReadonlySet<string>,
language: PartialOrderLanguage,
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
graph: Extract<GraphFacts, { kind: "partial-order" }>,
unorderedGroups: ReturnType<typeof validateUnorderedGroups>,
notBeforePairs: ReadonlySet<string>,
context: z.RefinementCtx,
): void => {
let missingPairCount = 0;
let firstMissingPair = "";
const groupConflicts = new Array<boolean>(
language.unordered_groups.length,
).fill(false);
unorderedGroups.markDeclaredPairConflicts(notBeforePairs, groupConflicts);
const notBeforeConflictFlags = new Uint8Array(language.not_before.length);
const constraintsBySource = new Map<string, number[]>();
for (const [index, constraint] of language.not_before.entries()) {
const indexes = constraintsBySource.get(constraint.event) ?? [];
indexes.push(index);
constraintsBySource.set(constraint.event, indexes);
}
// Keep only one origin's forward and backward closure live at a time. Pair
// iteration stays in declaration order so the count and first missing pair
// retain the established diagnostic semantics.
for (const [leftIndex, leftId] of ids.entries()) {
const forward = collectReachable(leftId, adjacency);
const backward = collectReachable(leftId, graph.reverseAdjacency);
for (const constraintIndex of constraintsBySource.get(leftId) ?? []) {
const constraint = language.not_before[constraintIndex];
if (constraint !== undefined && forward.has(constraint.anchor))
notBeforeConflictFlags[constraintIndex] = 1;
}
for (
let rightIndex = leftIndex + 1;
rightIndex < ids.length;
@@ -315,14 +440,32 @@ const validateCompletePairDeclarations = (
) {
const rightId = ids[rightIndex];
if (rightId === undefined) continue;
if (isOrdered(relations.reachable, leftId, rightId)) continue;
const sameEvent = leftId === rightId;
const ordered =
!sameEvent && (forward.has(rightId) || backward.has(rightId));
const key = pairKey(leftId, rightId);
if (!relations.notBeforePairs.has(key) && !unorderedPairs.has(key)) {
const notBefore = notBeforePairs.has(key);
const unordered = unorderedGroups.hasPair(leftId, rightId);
if (ordered || notBefore) {
if (!sameEvent)
unorderedGroups.markSharedGroups(leftId, rightId, groupConflicts);
}
if (!ordered && !notBefore && !unordered) {
if (missingPairCount === 0) firstMissingPair = `${leftId}/${rightId}`;
missingPairCount++;
}
}
}
for (const [index, conflict] of notBeforeConflictFlags.entries())
if (conflict === 1)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path: ["language", "not_before", index],
});
addUnorderedConflictIssues(groupConflicts, context);
if (missingPairCount > 0)
context.addIssue({
code: "custom",
@@ -342,27 +485,44 @@ const validatePartialOrder = (
const ids = specification.events.map(({ id }) => id);
const known = new Set(ids);
const adjacency = buildAdjacency(specification.language, context, known);
if (graphHasCycle(ids, adjacency))
const graph = classifyGraph(ids, adjacency);
if (graph.kind === "cyclic")
context.addIssue({
code: "custom",
message: "happens-before graph must be acyclic",
path: ["language"],
});
const reachable = computeReachability(ids, adjacency);
const notBeforePairs = validateNotBefore(
specification.language,
context,
known,
reachable,
);
const relations = { reachable, notBeforePairs };
const unorderedPairs = validateUnorderedGroups(
const unorderedGroups = validateUnorderedGroups(
specification.language,
context,
known,
relations,
);
validateCompletePairDeclarations(ids, relations, unorderedPairs, context);
// Preserve independent declaration diagnostics on cyclic input. Computing
// all pair relations cannot establish a valid partial order in that case.
if (graph.kind === "total-order") {
validateTotalOrderRelations(
specification.language,
graph,
unorderedGroups,
notBeforePairs,
context,
);
} else if (graph.kind === "partial-order") {
validatePartialOrderRelations(
ids,
specification.language,
adjacency,
graph,
unorderedGroups,
notBeforePairs,
context,
);
}
for (const [kind, values] of [
["prefix", specification.language.prefix],
["suffix", specification.language.suffix],
+167 -15
View File
@@ -286,14 +286,18 @@ describe("reconstruction coverage verifier selection", () => {
});
});
describe("reconstruction coverage verifier result ordering", () => {
it("preserves the first input result when verifier timestamps tie", () => {
describe("reconstruction coverage conflicting latest verifier observations", () => {
it("keeps conflicting tied assessments unknown regardless of input order", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const failed = { ...result, status: "fail" as const };
const failed = {
...result,
status: "fail" as const,
evidence_ids: [reconstructionCoverageEvidenceId("1")],
};
const firstPass = createReconstructionCoverageData({
...workspace,
verifier_results: [result, failed],
@@ -303,23 +307,109 @@ describe("reconstruction coverage verifier result ordering", () => {
verifier_results: [failed, result],
});
const firstPassResult = evaluateReconstructionClosure(
firstPass,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
const firstFailResult = evaluateReconstructionClosure(
firstFail,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
expect(firstPassResult).toEqual(firstFailResult);
expect(firstPassResult).toMatchObject({
status: "unknown",
reasons: [
expect.objectContaining({
code: "verifier-result-ambiguous",
subject_id: "claim.cli.help",
}),
],
});
expect(firstPassResult.evidence_ids).toEqual(
expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
);
});
});
describe("reconstruction coverage equivalent latest verifier observations", () => {
it("coalesces equivalent equal-instant observations and retains all evidence", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const first = {
...result,
observed_at: "2026-07-16T11:00:00.123456789012345678900Z",
};
const equivalent = {
...first,
observed_at: "2026-07-16T06:00:00.1234567890123456789-05:00",
covered_claim_ids: [...result.covered_claim_ids].reverse(),
covered_dimensions: [...result.covered_dimensions].reverse(),
artifact_sha256s: [...result.artifact_sha256s].reverse(),
owner_sha256s: [...result.owner_sha256s].reverse(),
evidence_ids: [reconstructionCoverageEvidenceId("1")],
};
const forward = createReconstructionCoverageData({
...workspace,
verifier_results: [first, equivalent],
});
const reversed = createReconstructionCoverageData({
...workspace,
verifier_results: [equivalent, first],
});
const forwardResult = evaluateReconstructionClosure(
forward,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
const reversedResult = evaluateReconstructionClosure(
reversed,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
expect(forwardResult).toEqual(reversedResult);
expect(forwardResult.status).toBe("ready");
expect(forwardResult.evidence_ids).toEqual(
expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
);
});
});
describe("reconstruction coverage verifier timestamp selection", () => {
it("lets a later unambiguous observation supersede an older tie", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const failed = { ...result, status: "fail" as const };
const latestPass = {
...result,
observed_at: "2026-07-16T11:30:00.000Z",
};
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [result, failed, latestPass],
});
expect(
evaluateReconstructionClosure(
firstPass,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
).status,
).toBe("ready");
expect(
evaluateReconstructionClosure(
firstFail,
changed,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
),
).toMatchObject({
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
).toMatchObject({ status: "ready", reasons: [] });
});
it("orders offset-bearing verifier timestamps chronologically", () => {
@@ -352,6 +442,68 @@ describe("reconstruction coverage verifier result ordering", () => {
});
});
it("selects the later result when timestamps differ below millisecond precision", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
{ ...result, observed_at: "2026-07-16T11:00:00.1231Z" },
{
...result,
observed_at: "2026-07-16T11:00:00.1239Z",
status: "fail",
},
],
});
expect(
evaluateReconstructionClosure(
changed,
"replacement.cli",
RECONSTRUCTION_COVERAGE_NOW,
),
).toMatchObject({
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
});
});
describe("reconstruction coverage verifier future timestamps", () => {
it("treats an observation beyond millisecond-precision now as future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
{ ...result, observed_at: "2026-07-16T12:00:00.1239Z" },
],
});
expect(
evaluateReconstructionClosure(
changed,
"replacement.cli",
Date.parse("2026-07-16T12:00:00.123Z") + 0.5,
),
).toMatchObject({
status: "unknown",
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
});
});
it("rejects a non-finite evaluation clock", () => {
const workspace = completeReconstructionCoverageData();
expect(() =>
evaluateReconstructionClosure(workspace, "replacement.cli", Number.NaN),
).toThrow("Expected finite epoch milliseconds.");
});
it("rejects verifier observations from the future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
+8 -1
View File
@@ -19,7 +19,10 @@ import {
} from "./reconstructionCoverageEvaluation.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { offsetDateTimeSchema } from "./offsetDateTime.js";
import {
offsetDateTimeInstantFromEpochMilliseconds,
offsetDateTimeSchema,
} from "./offsetDateTime.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const stableIdSchema = z
@@ -213,6 +216,7 @@ const closureReasonSchema = z.strictObject({
"verifier-result-missing",
"verifier-result-stale",
"verifier-result-incompatible",
"verifier-result-ambiguous",
"verifier-failed",
"verifier-unknown",
"active-unknown",
@@ -274,10 +278,12 @@ export const evaluateReconstructionClosure = (
);
if (boundary === undefined)
throw new TypeError(`Unknown reconstruction boundary: ${boundaryId}`);
const nowInstant = offsetDateTimeInstantFromEpochMilliseconds(nowEpochMs);
const context: ReconstructionEvaluationContext = {
coverage,
boundary,
nowEpochMs,
nowInstant,
reasons: [],
evidenceIds: new Set<string>(),
};
@@ -394,6 +400,7 @@ const closureStatus = (
[
"verifier-result-stale",
"verifier-result-incompatible",
"verifier-result-ambiguous",
"verifier-unknown",
"active-unknown",
"owner-path-unknown",
+46 -22
View File
@@ -3,6 +3,16 @@ import type {
ReconstructionCoverageData,
ReconstructionVerifierContract,
} from "./reconstructionCoverage.js";
import {
compareOffsetDateTimeInstants,
offsetDateTimeInstantFromEpochMilliseconds,
type OffsetDateTimeInstant,
} from "./offsetDateTime.js";
import {
latestVerifierObservationsByVerifier,
sameVerifierAssessment,
type VerifierObservation,
} from "./reconstructionCoverageVerifierResults.js";
export const recommendedReconstructionProbes = (
reasons: readonly ClosureReason[],
@@ -29,6 +39,7 @@ export interface ReconstructionEvaluationContext {
readonly coverage: ReconstructionCoverageData;
readonly boundary: Boundary;
readonly nowEpochMs: number;
readonly nowInstant: OffsetDateTimeInstant;
readonly reasons: ClosureReason[];
readonly evidenceIds: Set<string>;
}
@@ -184,7 +195,7 @@ interface VerifierIndexes {
>;
readonly latestResultsByVerifier: ReadonlyMap<
string,
ReconstructionCoverageData["verifier_results"][number]
readonly VerifierObservation[]
>;
readonly artifactDigests: ReadonlySet<string>;
readonly ownerDigests: ReadonlySet<string>;
@@ -213,20 +224,6 @@ const createVerifierIndexes = (
contractsByClaim.set(claimId, contracts);
}
const latestResultsByVerifier = new Map<
string,
ReconstructionCoverageData["verifier_results"][number]
>();
for (const result of coverage.verifier_results) {
const latest = latestResultsByVerifier.get(result.verifier_id);
// Stable descending sort used to choose the first input record on ties.
if (
latest === undefined ||
Date.parse(result.observed_at) > Date.parse(latest.observed_at)
)
latestResultsByVerifier.set(result.verifier_id, result);
}
const ownersBySurface = new Map<
string,
ReconstructionCoverageData["owners"][number][]
@@ -239,7 +236,9 @@ const createVerifierIndexes = (
return {
contractsByClaim,
latestResultsByVerifier,
latestResultsByVerifier: latestVerifierObservationsByVerifier(
coverage.verifier_results,
),
artifactDigests: new Set(
coverage.artifacts.map(({ artifact_sha256: value }) => value),
),
@@ -260,8 +259,10 @@ const evaluateVerifierResult = (
contract: ReconstructionVerifierContract,
indexes: VerifierIndexes,
): void => {
const result = indexes.latestResultsByVerifier.get(contract.verifier_id);
if (result === undefined) {
const latestResults = indexes.latestResultsByVerifier.get(
contract.verifier_id,
);
if (latestResults === undefined) {
addReason(
context,
"verifier-result-missing",
@@ -270,7 +271,26 @@ const evaluateVerifierResult = (
);
return;
}
addEvidence(context, result.evidence_ids);
addEvidence(
context,
latestResults.flatMap(({ result }) => result.evidence_ids),
);
const latest = latestResults[0];
if (latest === undefined) return;
const { result } = latest;
if (
!latestResults.every((candidate) =>
sameVerifierAssessment(result, candidate.result),
)
) {
addReason(
context,
"verifier-result-ambiguous",
claim.claim_id,
"Latest verifier observations have conflicting assessment content.",
);
return;
}
if (!verifierResultIsCompatible(claim, contract, result, indexes)) {
addReason(
context,
@@ -280,10 +300,14 @@ const evaluateVerifierResult = (
);
return;
}
const observedAt = Date.parse(result.observed_at);
const cutoffEpochMs = context.nowEpochMs - contract.max_age_ms;
if (
observedAt > context.nowEpochMs ||
context.nowEpochMs - observedAt > contract.max_age_ms
compareOffsetDateTimeInstants(latest.instant, context.nowInstant) > 0 ||
(cutoffEpochMs >= -Number.MAX_SAFE_INTEGER &&
compareOffsetDateTimeInstants(
latest.instant,
offsetDateTimeInstantFromEpochMilliseconds(cutoffEpochMs),
) < 0)
) {
addReason(
context,
@@ -0,0 +1,57 @@
import type { ReconstructionCoverageData } from "./reconstructionCoverage.js";
import { uniqueSorted } from "./canonicalOrdering.js";
import {
compareOffsetDateTimeInstants,
parseOffsetDateTimeInstant,
type OffsetDateTimeInstant,
} from "./offsetDateTime.js";
type VerifierResult = ReconstructionCoverageData["verifier_results"][number];
export interface VerifierObservation {
readonly result: VerifierResult;
readonly instant: OffsetDateTimeInstant;
}
/** Index each verifier's latest timestamp group without relying on array order. */
export const latestVerifierObservationsByVerifier = (
results: readonly VerifierResult[],
): ReadonlyMap<string, readonly VerifierObservation[]> => {
const latestByVerifier = new Map<string, VerifierObservation[]>();
for (const result of results) {
const observation = {
result,
instant: parseOffsetDateTimeInstant(result.observed_at),
};
const latest = latestByVerifier.get(result.verifier_id);
const latestInstant = latest?.[0]?.instant;
const comparison =
latestInstant === undefined
? 1
: compareOffsetDateTimeInstants(observation.instant, latestInstant);
if (latest === undefined || comparison > 0)
latestByVerifier.set(result.verifier_id, [observation]);
else if (comparison === 0) latest.push(observation);
}
return latestByVerifier;
};
/** Compare assessment content while excluding timestamp spelling and provenance. */
export const sameVerifierAssessment = (
left: VerifierResult,
right: VerifierResult,
): boolean =>
verifierAssessmentIdentity(left) === verifierAssessmentIdentity(right);
const verifierAssessmentIdentity = (result: VerifierResult): string =>
JSON.stringify({
verifier_id: result.verifier_id,
contract_sha256: result.contract_sha256,
status: result.status,
covered_claim_ids: uniqueSorted(result.covered_claim_ids),
covered_dimensions: uniqueSorted(result.covered_dimensions),
artifact_sha256s: uniqueSorted(result.artifact_sha256s),
owner_sha256s: uniqueSorted(result.owner_sha256s),
normalization_sha256: result.normalization_sha256,
repeats: result.repeats,
});
+6 -6
View File
@@ -12,7 +12,7 @@ import { functionComparisonDimensionNameSchema } from "./functionComparisonSchem
const evidenceIdSchema = prefixedDigestSchema("ev");
const unknownIdSchema = prefixedDigestSchema("unk");
const text = z.string().trim().min(1);
const environmentRequirementSchema = z.object({
const environmentRequirementSchema = z.strictObject({
id: z.string().min(1).nullable(),
platform: z.string().min(1).nullable(),
architecture: z.string().min(1).nullable(),
@@ -39,7 +39,7 @@ const stableUnknownId = (
)
.digest("hex")}`;
const probeSchema = z.object({
const probeSchema = z.strictObject({
operation: z.string().min(1),
rationale: text,
});
@@ -60,17 +60,17 @@ const comparisonConclusionScopeSchema = z
message: "Comparison dimensions must be sorted and unique",
});
});
const relationshipSchema = z.object({
const relationshipSchema = z.strictObject({
type: z.enum(["depends-on", "related-to", "contradicts"]),
unknown_id: unknownIdSchema,
});
const resolutionSchema = z.discriminatedUnion("disposition", [
z.object({
z.strictObject({
disposition: z.literal("verified"),
rationale: text,
evidence_ids: z.array(evidenceIdSchema).min(1),
}),
z.object({
z.strictObject({
disposition: z.enum(["withdrawn", "out-of-scope"]),
rationale: text,
evidence_ids: z.array(evidenceIdSchema),
@@ -78,7 +78,7 @@ const resolutionSchema = z.discriminatedUnion("disposition", [
]);
/** Strict durable record for one unresolved or evidence-qualified question. */
const residualUnknownObjectSchema = z.object({
const residualUnknownObjectSchema = z.strictObject({
unknown_id: unknownIdSchema,
revision: z.number().int().min(1),
previous_revision_digest: z
+14 -4
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { createHash } from "node:crypto";
import type { EvidenceSubjectTarget } from "../evidence.js";
import { localPathStringSchema } from "../localPath.js";
@@ -137,11 +138,20 @@ export type InspectWasmArtifactInput = z.infer<
>;
export type WasmArtifact = z.infer<typeof wasmArtifactSchema>;
/** A WASM observation must identify the exact selected path and byte digest. */
/** A WASM observation must identify the selected file path and byte digest. */
export type WasmArtifactSubject = Pick<
EvidenceSubjectTarget,
"path" | "sha256" | "format"
>;
type WasmArtifactFileSubject = WasmArtifactSubject & {
readonly format: "file";
};
export const wasmArtifactMatchesSubject = (
artifact: WasmArtifact["artifact"],
subject: Pick<WasmArtifact["artifact"], "path" | "sha256"> | null | undefined,
): subject is Pick<WasmArtifact["artifact"], "path" | "sha256"> =>
subject: WasmArtifactSubject | null | undefined,
): subject is WasmArtifactFileSubject =>
subject != null &&
subject.path === artifact.path &&
subject.sha256 === artifact.sha256;
subject.sha256 === artifact.sha256 &&
subject.format === "file";
+26 -40
View File
@@ -1,10 +1,11 @@
import {
deliveredCodexEvidence,
evaluateKnownAnswers,
parseCodexToolCall,
type FixtureClaimExpectation,
type KnownAnswerAssessment,
type ParsedCodexToolCall,
} from "./KnownAnswerEvaluation.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
/** One REA MCP invocation observed in a Codex JSONL transcript. */
@@ -57,17 +58,6 @@ const textValue = (value: unknown): string | undefined =>
const numberValue = (value: unknown): number =>
typeof value === "number" && Number.isFinite(value) ? value : 0;
const canonicalValue = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(canonicalValue);
const object = record(value);
if (object === undefined) return value;
return Object.fromEntries(
Object.entries(object)
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([key, child]) => [key, canonicalValue(child)]),
);
};
const toolResultError = (
item: Record<string, unknown>,
): Record<string, unknown> | undefined => {
@@ -113,29 +103,18 @@ const toolResultFailed = (
);
};
const callFromEvent = (
event: Record<string, unknown>,
const callFromParsed = (
parsed: ParsedCodexToolCall | undefined,
): CodexMcpCall | undefined => {
const item = record(
event.type === "item.completed"
? event.item
: event.type === "mcp_tool_call"
? event
: undefined,
);
if (item?.type !== "mcp_tool_call") return undefined;
const tool = textValue(item.tool) ?? textValue(item.name);
if (tool === undefined) return undefined;
const error = toolResultError(item);
if (parsed === undefined) return undefined;
const error = toolResultError(parsed.item);
return {
id: textValue(item.id) ?? null,
server: textValue(item.server) ?? textValue(item.server_name) ?? null,
tool,
arguments: item.arguments ?? item.input ?? {},
evidenceIds: deliveredCodexEvidence(event).map(
({ evidence_id }) => evidence_id,
),
error: toolResultFailed(item, error),
id: parsed.id,
server: parsed.server,
tool: parsed.tool,
arguments: parsed.arguments,
evidenceIds: parsed.evidence.map(({ evidence_id }) => evidence_id),
error: toolResultFailed(parsed.item, error),
errorCode: textValue(error?.code) ?? null,
};
};
@@ -163,16 +142,20 @@ interface EvaluationState {
outputTokens: number;
}
const consumeEvent = (state: EvaluationState, value: unknown): void => {
const consumeEvent = (
state: EvaluationState,
value: unknown,
parsedCall: ParsedCodexToolCall | undefined,
): void => {
const event = record(value);
if (event === undefined) return;
const completedItem =
event.type === "item.completed" ? event.item : undefined;
const call = callFromEvent(event);
const call = callFromParsed(parsedCall);
if (call !== undefined) {
const identity =
call.id ??
`${call.server ?? ""}:${call.tool}:${JSON.stringify(canonicalValue(call.arguments))}`;
`${call.server ?? ""}:${call.tool}:${canonicalJson(call.arguments)}`;
if (!state.seenCallIds.has(identity)) {
state.seenCallIds.add(identity);
state.calls.push(call);
@@ -216,7 +199,10 @@ export const evaluateCodexEvents = (
cachedInputTokens: 0,
outputTokens: 0,
};
for (const event of events) consumeEvent(state, event);
const parsedCalls = events.map(parseCodexToolCall);
events.forEach((event, index) =>
consumeEvent(state, event, parsedCalls[index]),
);
const reaCalls = state.calls.filter(
({ server }) => server === null || server.toLowerCase() === "rea",
@@ -228,7 +214,7 @@ export const evaluateCodexEvents = (
// useful verification, not a duplicate analysis or unchanged failed retry.
const context =
call.tool === "binary_session" ? `${String(targetRevision)}:` : "";
const signature = `${context}${call.tool}:${JSON.stringify(canonicalValue(call.arguments))}`;
const signature = `${context}${call.tool}:${canonicalJson(call.arguments)}`;
signatures.set(signature, (signatures.get(signature) ?? 0) + 1);
if (
!call.error &&
@@ -271,7 +257,7 @@ export const evaluateCodexEvents = (
finalMessage,
);
const factualAssessment = evaluateKnownAnswers(
events,
parsedCalls,
finalMessage,
options.fixtureClaims,
);
+98 -50
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import { parseEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
/** One closed fixture assertion and the producer facts that must support it. */
export interface FixtureClaimExpectation {
@@ -104,23 +104,13 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const record = (value: unknown): Record<string, unknown> | undefined =>
isRecord(value) ? value : undefined;
const canonicalValue = (value: JsonValue): JsonValue => {
if (Array.isArray(value)) return value.map(canonicalValue);
if (value === null || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([key, child]) => [key, canonicalValue(child)]),
);
};
const sameJson = (left: unknown, right: unknown): boolean => {
const parsedLeft = jsonValueSchema.safeParse(left);
const parsedRight = jsonValueSchema.safeParse(right);
return (
parsedLeft.success &&
parsedRight.success &&
JSON.stringify(canonicalValue(parsedLeft.data)) ===
JSON.stringify(canonicalValue(parsedRight.data))
canonicalJson(parsedLeft.data) === canonicalJson(parsedRight.data)
);
};
@@ -168,6 +158,16 @@ interface DeliveredEvidence {
readonly conflicts: Set<string>;
}
/** One completed tool call, with aliases normalized and successful Evidence authenticated. */
export interface ParsedCodexToolCall {
readonly item: Record<string, unknown>;
readonly id: string | null;
readonly server: string | null;
readonly tool: string;
readonly arguments: JsonValue;
readonly evidence: readonly Evidence[];
}
const consistentAliases = (
value: Record<string, unknown>,
left: string,
@@ -177,30 +177,14 @@ const consistentAliases = (
value[right] === undefined ||
value[left] === value[right];
const completedCall = (event: unknown): Record<string, unknown> | undefined => {
const value = record(event);
const item =
value?.type === "item.completed"
? record(value.item)
: value?.type === "mcp_tool_call" && value.status === "completed"
? value
: undefined;
if (item?.type !== "mcp_tool_call") return undefined;
const server = item.server ?? item.server_name;
if (
typeof server !== "string" ||
server.toLowerCase() !== "rea" ||
(item.status !== undefined && item.status !== "completed") ||
(item.error !== undefined && item.error !== null)
)
return undefined;
if (
!consistentAliases(item, "server", "server_name") ||
!consistentAliases(item, "tool", "name")
)
return undefined;
return item;
};
const consistentJsonFields = (
value: Record<string, unknown>,
left: string,
right: string,
): boolean =>
value[left] === undefined ||
value[right] === undefined ||
sameJson(value[left], value[right]);
const consistentJsonAliases = (
value: Record<string, unknown>,
@@ -215,6 +199,7 @@ const consistentJsonAliases = (
const evidenceFromCall = (
item: Record<string, unknown>,
tool: string,
): Evidence | undefined => {
if (!consistentJsonAliases(item, "result", "output")) return undefined;
const result = record(item.result ?? item.output);
@@ -254,22 +239,42 @@ const evidenceFromCall = (
// Transcript output is untrusted; invalid Evidence cannot support a claim.
return undefined;
}
if ((item.tool ?? item.name) !== evidence.operation) return undefined;
if (tool !== evidence.operation) return undefined;
return evidence;
};
/** Authenticate completed REA deliveries for both citations and fixture grading. */
export const deliveredCodexEvidence = (event: unknown): readonly Evidence[] => {
const item = completedCall(event);
if (item === undefined) return [];
const evidence = evidenceFromCall(item);
if (evidence === undefined) return [];
const completedToolItem = (
event: unknown,
): Record<string, unknown> | undefined => {
const value = record(event);
const wrapped = value?.type === "item.completed";
const item = wrapped
? record(value.item)
: value?.type === "mcp_tool_call"
? value
: undefined;
if (item?.type !== "mcp_tool_call") return undefined;
const terminalStatus =
item.status === "completed" || item.status === "failed";
if (
(wrapped
? item.status !== undefined && !terminalStatus
: !terminalStatus) ||
!consistentAliases(item, "server", "server_name") ||
!consistentAliases(item, "tool", "name") ||
!consistentJsonFields(item, "arguments", "input")
)
return undefined;
return item;
};
const artifactDelivery = (evidence: Evidence): readonly Evidence[] => {
const records = [evidence];
// Artifact inspection delivers its inventory Evidence inline. Bare links and
// arbitrary IDs in normalized facts are references, not delivered records.
if (evidence.operation !== "inspect_artifact") return records;
const substeps = record(evidence.normalized_result)?.substeps;
if (!Array.isArray(substeps)) return records;
// Artifact inspection delivers linked inventory Evidence inline; bare IDs in
// normalized facts are references, not authenticated deliveries.
for (const value of substeps) {
const substep = record(value);
if (
@@ -293,13 +298,56 @@ export const deliveredCodexEvidence = (event: unknown): readonly Evidence[] => {
return records;
};
/** Parse one completed transcript call and authenticate any successful REA Evidence. */
export const parseCodexToolCall = (
event: unknown,
): ParsedCodexToolCall | undefined => {
const item = completedToolItem(event);
if (item === undefined) return undefined;
const status = item.status;
const server = item.server ?? item.server_name;
const tool = item.tool ?? item.name;
if (
((item.server !== undefined || item.server_name !== undefined) &&
typeof server !== "string") ||
typeof tool !== "string" ||
tool.length === 0
)
return undefined;
const argumentsValue =
item.arguments !== undefined
? item.arguments
: item.input !== undefined
? item.input
: {};
const parsedArguments = jsonValueSchema.safeParse(argumentsValue);
if (!parsedArguments.success) return undefined;
const parsed: ParsedCodexToolCall = {
item,
id: typeof item.id === "string" && item.id.length > 0 ? item.id : null,
server: typeof server === "string" ? server : null,
tool,
arguments: parsedArguments.data,
evidence: [],
};
if (
parsed.server?.toLowerCase() !== "rea" ||
status === "failed" ||
(item.error !== undefined && item.error !== null)
)
return parsed;
const evidence = evidenceFromCall(item, tool);
if (evidence === undefined) return parsed;
return { ...parsed, evidence: artifactDelivery(evidence) };
};
const collectDeliveredEvidence = (
events: readonly unknown[],
calls: readonly (ParsedCodexToolCall | undefined)[],
): DeliveredEvidence => {
const records = new Map<string, Evidence>();
const conflicts = new Set<string>();
for (const event of events) {
for (const evidence of deliveredCodexEvidence(event)) {
for (const call of calls) {
for (const evidence of call?.evidence ?? []) {
const previous = records.get(evidence.evidence_id);
if (previous !== undefined && !sameJson(previous, evidence))
conflicts.add(evidence.evidence_id);
@@ -401,7 +449,7 @@ const assessClaim = (
/** Grade closed answers only against configured fixture truth and delivered authenticated Evidence. */
export const evaluateKnownAnswers = (
events: readonly unknown[],
calls: readonly (ParsedCodexToolCall | undefined)[],
finalMessage: string,
expectations: readonly FixtureClaimExpectation[] | undefined,
): KnownAnswerAssessment => {
@@ -441,7 +489,7 @@ export const evaluateKnownAnswers = (
manifestFailures.push(`unknown_claim:${claim.id}`);
submitted.set(claim.id, claim);
}
const delivered = collectDeliveredEvidence(events);
const delivered = collectDeliveredEvidence(calls);
const claims = expectations.map((expected) =>
assessClaim(expected, submitted.get(expected.id), delivered),
);
+7 -5
View File
@@ -6,10 +6,12 @@ import { fileURLToPath } from "node:url";
import { z } from "zod";
import {
createAnalysisExecution,
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import type { EvmInterfacePort } from "../application/evm/EvmInterfacePort.js";
import type {
EvmInterfaceExecution,
EvmInterfacePort,
} from "../application/evm/EvmInterfacePort.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import type {
@@ -98,7 +100,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort {
inspect(
input: InspectEvmInterfaceInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
): Promise<Result<EvmInterfaceExecution, AnalysisError>> {
if (this.#closing) return Promise.resolve(err(this.#closedError()));
const operation = this.#tail.then(() =>
this.#closing ? err(this.#closedError()) : this.#inspect(input, options),
@@ -113,7 +115,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort {
async #inspect(
input: InspectEvmInterfaceInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
): Promise<Result<EvmInterfaceExecution, AnalysisError>> {
const pending = await this.#retire();
if (pending !== undefined) return err(pending);
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
@@ -123,7 +125,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort {
let workerLimits: EvmWorkerLimits | undefined;
const limiter =
this.environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
let result: Result<AnalysisExecution, AnalysisError>;
let result: Result<EvmInterfaceExecution, AnalysisError>;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
if (process.platform !== "linux" || process.arch !== "x64")
+10
View File
@@ -101,6 +101,16 @@ export const openRegularFile = async (
options.signal?.throwIfAborted();
if (!metadata.isFile())
throw new NonRegularFileReadError(path, metadata.isDirectory());
// O_NOFOLLOW is unavailable on Windows. Recheck the name only on hosts
// where open could have followed a symlink, while the descriptor is owned.
if (options.symlinks === "reject" && (constants.O_NOFOLLOW ?? 0) === 0) {
const named = await lstat(path);
options.signal?.throwIfAborted();
if (named.isSymbolicLink())
throw new NonRegularFileReadError(path, false);
if (!sameRegularFileState(metadata, named))
throw new RegularFileChangedError(path);
}
return handle;
} catch (cause: unknown) {
try {
+9 -13
View File
@@ -213,19 +213,15 @@ export const inventoryFirmwareOutput = async (
});
if (handle === undefined) continue;
const names: string[] = [];
try {
for await (const entry of handle) {
throwIfFirmwareInventoryCancelled(signal, operation);
count++;
if (count > maxEntries)
throw new AnalysisOutputError(
operation,
`Staging entry budget exceeded (${maxEntries})`,
);
names.push(entry.name);
}
} finally {
await handle.close().catch(() => undefined);
for await (const entry of handle) {
throwIfFirmwareInventoryCancelled(signal, operation);
count++;
if (count > maxEntries)
throw new AnalysisOutputError(
operation,
`Staging entry budget exceeded (${maxEntries})`,
);
names.push(entry.name);
}
for (const name of names.sort()) {
const path = join(directory, name);
+1 -1
View File
@@ -196,7 +196,7 @@ describe("Ghidra seed profile", () => {
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+12 -2
View File
@@ -15,7 +15,7 @@ const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
const installationHost = (
overrides: Partial<GhidraInstallationHost> = {},
): GhidraInstallationHost => ({
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
@@ -111,7 +111,9 @@ describe("Ghidra doctor integration", () => {
"wrong version",
inspection(
{ installDir: INSTALL },
{ readText: () => "application.version=11.4\n" },
{
readText: () => "application.version=11.4\napplication.java.min=21\n",
},
),
"ghidra-version",
],
@@ -136,6 +138,14 @@ describe("Ghidra doctor integration", () => {
),
"ghidra-java",
],
[
"missing Java minimum",
inspection(
{ installDir: INSTALL },
{ readText: () => "application.version=12.1.4\n" },
),
"ghidra-java",
],
[
"unsupported architecture",
inspection({ installDir: INSTALL, architecture: "arm" }),
+178 -6
View File
@@ -12,6 +12,8 @@ import {
import {
SUPPORTED_GHIDRA_JAVA_MAJOR,
SUPPORTED_GHIDRA_VERSION,
ghidraApplicationProperties,
ghidraJavaRequirement,
} from "./GhidraInstallationPolicy.js";
const INSTALL = "/opt/ghidra";
@@ -42,7 +44,7 @@ const host = (
): GhidraInstallationHost => ({
readText: (path) =>
path === PROPERTIES
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
? `application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=${String(SUPPORTED_GHIDRA_JAVA_MAJOR)}\n`
: undefined,
executable: (path) =>
path === HEADLESS || path === MAC_DECOMPILER || path === LINUX_DECOMPILER,
@@ -190,7 +192,7 @@ describe("Ghidra installation inspection", () => {
architecture: "x64",
readText: (path) =>
path === WINDOWS_PROPERTIES
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
? `application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=21\n`
: undefined,
executable: (path) =>
path === WINDOWS_HEADLESS || path === WINDOWS_DECOMPILER,
@@ -275,7 +277,9 @@ describe("Ghidra installation rejection diagnostics", () => {
platform: "linux" as const,
architecture: "x64" as const,
},
override: { readText: () => "application.version=11.4\n" },
override: {
readText: () => "application.version=11.4\napplication.java.min=21\n",
},
failed: "version",
code: "unsupported_version",
},
@@ -350,6 +354,167 @@ describe("Ghidra installation rejection diagnostics", () => {
});
describe("Ghidra release line and JDK bounds", () => {
it("uses Java Properties last-key, delimiter, escape, and continuation rules", () => {
const properties = ghidraApplicationProperties(
[
"application.version=11.4",
"# comment ending with a slash " + "\\",
"application.\\u0076ersion : 12.\\",
" 1.\\u0034",
"! another comment " + "\\",
"application.java.\\u006din\t21",
"application.java.max=",
].join("\n"),
);
expect(properties).toEqual({
providerVersion: "12.1.4",
javaMinimum: { status: "major", major: 21 },
javaMaximum: { status: "absent" },
parseError: null,
});
expect(
ghidraApplicationProperties("application.version=12.1.4").javaMinimum,
).toEqual({
status: "absent",
});
expect(
ghidraApplicationProperties(
"application.version=12.1.4\napplication.java.min=\n",
).javaMinimum,
).toEqual({ status: "unresolved", raw: "" });
expect(
ghidraApplicationProperties("application.version=12.1.4\\")
.providerVersion,
).toBe("12.1.4");
expect(
ghidraApplicationProperties("application.version=12.\\\n #.1")
.providerVersion,
).toBe("12.#.1");
expect(
ghidraApplicationProperties(
"application.version=12.\\\n\napplication.version=12.1.4",
).providerVersion,
).toBe("12.1.4");
});
it("matches Ghidra integer Java bounds and zero maximum semantics", () => {
const properties = ghidraApplicationProperties(
"application.java.min=21.0\napplication.java.max=0\n",
);
expect(properties.javaMinimum).toEqual({
status: "unresolved",
raw: "21.0",
});
expect(properties.javaMaximum).toEqual({ status: "absent" });
expect(
ghidraApplicationProperties("application.java.max=+0").javaMaximum,
).toEqual({
status: "absent",
});
expect(
ghidraApplicationProperties("application.java.max=+0").javaMaximum,
).toEqual({ status: "absent" });
expect(
ghidraApplicationProperties("application.java.min=+21").javaMinimum,
).toEqual({
status: "major",
major: 21,
});
expect(
ghidraApplicationProperties("application.java.min=٢١").javaMinimum,
).toEqual({
status: "major",
major: 21,
});
expect(
ghidraApplicationProperties("application.java.min=21").javaMinimum,
).toEqual({
status: "major",
major: 21,
});
expect(
ghidraApplicationProperties("application.java.max=+0").javaMaximum,
).toEqual({
status: "unresolved",
raw: "+0",
});
expect(
ghidraApplicationProperties("application.java.min=②").javaMinimum,
).toEqual({
status: "unresolved",
raw: "②",
});
expect(
ghidraApplicationProperties("application.java.min=2147483648")
.javaMinimum,
).toEqual({ status: "unresolved", raw: "2147483648" });
});
it("keeps an unavailable properties file unresolved for Java admission", () => {
expect(ghidraJavaRequirement(undefined).unresolved).toBe(
"application.properties is unavailable",
);
});
it("preserves property value trailing whitespace instead of normalizing it", () => {
const properties = ghidraApplicationProperties(
"application.version=12.1.4 \napplication.java.min=21 \n",
);
expect(properties.providerVersion).toBe("12.1.4 ");
expect(properties.javaMinimum).toEqual({
status: "unresolved",
raw: "21 ",
});
expect(properties.parseError).toBeNull();
});
});
describe("Ghidra malformed property admission", () => {
it("fails installation and doctor admission closed on malformed Unicode escapes", () => {
const result = inspectGhidraInstallation(
{
environment: {},
installDir: INSTALL,
platform: "linux",
architecture: "x64",
},
host({
readText: () =>
"application.version=12.1.4\nbroken=\\u12G4\napplication.java.min=17\n",
}),
);
expect(result.status).toBe("unavailable");
expect(result.providerVersion).toBeNull();
expect(result.checks).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "version",
status: "failed",
code: "version_unresolved",
detail: expect.stringContaining("Malformed Unicode escape"),
}),
expect.objectContaining({
name: "java",
status: "failed",
code: "version_unresolved",
remediation: expect.stringContaining(
"application.properties parse failed",
),
}),
]),
);
expect(projectGhidraDoctorInspection(result)).toMatchObject({
available: false,
registrationEnvironment: {},
checks: expect.arrayContaining([
expect.objectContaining({ name: "version", ok: false }),
expect.objectContaining({ name: "java", ok: false }),
]),
});
});
});
describe("Ghidra installation version admission", () => {
it.each([
{
name: "JDK above the installation maximum",
@@ -367,16 +532,23 @@ describe("Ghidra release line and JDK bounds", () => {
failed: "java",
code: "version_unresolved",
},
{
name: "missing Java minimum",
readText: () => "application.version=12.1.4\n",
probeJava: () => JAVA,
failed: "java",
code: "version_unresolved",
},
{
name: "unparseable Ghidra version",
readText: () => "application.version=latest\n",
readText: () => "application.version=latest\napplication.java.min=21\n",
probeJava: () => JAVA,
failed: "version",
code: "version_unresolved",
},
{
name: "different Ghidra line",
readText: () => "application.version=12.2.0\n",
readText: () => "application.version=12.2.0\napplication.java.min=21\n",
probeJava: () => JAVA,
failed: "version",
code: "unsupported_version",
@@ -422,7 +594,7 @@ describe("Ghidra release line and JDK bounds", () => {
});
});
it("honors an installation that declares a lower Java minimum", () => {
it("accepts a lower Java minimum declared by the installation", () => {
expect(
inspectGhidraInstallation(
{
+14 -6
View File
@@ -641,14 +641,20 @@ const versionCheck = (
properties: GhidraApplicationProperties | undefined,
): GhidraInstallationCheck => {
const raw = properties?.providerVersion;
const parseError = properties?.parseError;
return installationCheck({
name: "version",
passed: ghidraReleaseAccepted(raw),
passed: parseError == null && ghidraReleaseAccepted(raw),
code:
ghidraReleaseCompatibility(raw).status === "unsupported"
? "unsupported_version"
: "version_unresolved",
detail: ghidraVersionDetail(raw),
parseError != null
? "version_unresolved"
: ghidraReleaseCompatibility(raw).status === "unsupported"
? "unsupported_version"
: "version_unresolved",
detail:
parseError == null
? ghidraVersionDetail(raw)
: `application.properties could not be parsed: ${parseError}`,
remediation: `Install a Ghidra ${ghidraReleaseLine()} release (verified with ${SUPPORTED_GHIDRA_VERSION}), or update REA for another Ghidra line.`,
});
};
@@ -701,7 +707,9 @@ const javaRemediation = (
const systemGhidraInstallationHost = (): GhidraInstallationHost => ({
readText(path) {
try {
return readFileSync(path, "utf8");
// Ghidra loads this file with Properties.load(InputStream), which maps
// bytes as ISO-8859-1 rather than decoding UTF-8.
return readFileSync(path).toString("latin1");
} catch (cause: unknown) {
// best-effort cleanup: optional install probing; unreadable means unknown.
void cause;
+200 -32
View File
@@ -1,10 +1,8 @@
import { err, ok, type Result } from "../domain/result.js";
/** Ghidra build whose bridge behavior this REA release verifies. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
/**
* JDK major used when an installation omits `application.java.min`.
* Admission uses that installation's `application.java.min` and
* `application.java.max`. An empty maximum means the release sets no upper bound.
*/
/** Verified JDK major; admission uses the installation's declared bounds. */
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
/** Numeric Ghidra release read from `application.version`. */
@@ -40,30 +38,49 @@ type GhidraJavaBound =
| { readonly status: "unresolved"; readonly raw: string };
/** JDK majors this installation admits, after reading its own properties. */
export interface GhidraJavaRequirement {
readonly minimumMajor: number;
readonly maximumMajor: number | null;
readonly unresolved: string | null;
}
export type GhidraJavaRequirement =
| {
readonly minimumMajor: number;
readonly maximumMajor: number | null;
readonly unresolved: null;
}
| { readonly unresolved: string };
/** Version and Java bounds read from one `application.properties` file. */
export interface GhidraApplicationProperties {
readonly providerVersion: string | null;
readonly javaMinimum: GhidraJavaBound;
readonly javaMaximum: GhidraJavaBound;
/** A malformed Java properties escape invalidates the entire file. */
readonly parseError: string | null;
}
const GHIDRA_RELEASE_PATTERN = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u;
const JAVA_MAJOR_PATTERN = /^(\d+)(?:\.\d+)*$/u;
/** Read the version and Java bounds Ghidra publishes for one installation. */
export const ghidraApplicationProperties = (
content: string,
): GhidraApplicationProperties => ({
providerVersion: propertyValue(content, "application.version"),
javaMinimum: parseJavaBound(propertyValue(content, "application.java.min")),
javaMaximum: parseJavaBound(propertyValue(content, "application.java.max")),
});
): GhidraApplicationProperties => {
const parsed = parseJavaProperties(content);
if (!parsed.ok)
return {
providerVersion: null,
javaMinimum: { status: "unresolved", raw: parsed.error },
javaMaximum: { status: "unresolved", raw: parsed.error },
parseError: parsed.error,
};
const providerVersion = parsed.value.get("application.version");
const minimum = parsed.value.get("application.java.min");
const maximum = parsed.value.get("application.java.max");
return {
providerVersion: providerVersion ?? null,
javaMinimum:
minimum === undefined ? { status: "absent" } : parseJavaBound(minimum),
// Ghidra uses an explicitly empty maximum to mean no upper bound.
javaMaximum: parseJavaMaximum(maximum),
parseError: null,
};
};
/** Classify `application.version` against the verified release line. */
export const ghidraReleaseCompatibility = (
@@ -130,14 +147,21 @@ export const ghidraReleaseAccepted = (
export const ghidraJavaRequirement = (
properties: GhidraApplicationProperties | undefined,
): GhidraJavaRequirement => {
const minimum = properties?.javaMinimum ?? { status: "absent" };
const maximum = properties?.javaMaximum ?? { status: "absent" };
if (properties?.parseError !== null && properties?.parseError !== undefined)
return unresolvedJavaRequirement(
`application.properties parse failed: ${properties.parseError}`,
);
if (properties === undefined)
return unresolvedJavaRequirement("application.properties is unavailable");
const minimum = properties.javaMinimum;
const maximum = properties.javaMaximum;
if (minimum.status === "unresolved")
return unresolvedJavaRequirement(`application.java.min=${minimum.raw}`);
if (minimum.status === "absent")
return unresolvedJavaRequirement("application.java.min is missing");
if (maximum.status === "unresolved")
return unresolvedJavaRequirement(`application.java.max=${maximum.raw}`);
const minimumMajor =
minimum.status === "major" ? minimum.major : SUPPORTED_GHIDRA_JAVA_MAJOR;
const minimumMajor = minimum.major;
const maximumMajor = maximum.status === "major" ? maximum.major : null;
if (maximumMajor !== null && maximumMajor < minimumMajor)
return unresolvedJavaRequirement(
@@ -187,14 +211,56 @@ const parseGhidraRelease = (raw: string): GhidraReleaseVersion | undefined => {
return patch === undefined ? undefined : { major, minor, patch };
};
const parseJavaBound = (raw: string | null): GhidraJavaBound => {
if (raw === null) return { status: "absent" };
const major = integerGroup(JAVA_MAJOR_PATTERN.exec(raw)?.[1]);
const parseJavaBound = (raw: string): GhidraJavaBound => {
const major = parseJavaInteger(raw);
return major === undefined
? { status: "unresolved", raw }
: { status: "major", major };
};
const parseJavaMaximum = (raw: string | undefined): GhidraJavaBound => {
if (raw === undefined || raw === "") return { status: "absent" };
const bound = parseJavaBound(raw);
return bound.status === "major" && bound.major === 0
? { status: "absent" }
: bound;
};
const parseJavaInteger = (raw: string): number | undefined => {
let index = 0;
let sign = 1;
if (raw[index] === "+" || raw[index] === "-") {
if (raw[index] === "-") sign = -1;
index += 1;
}
if (index === raw.length) return undefined;
const limit = sign < 0 ? 2_147_483_648 : 2_147_483_647;
let value = 0;
for (; index < raw.length; index += 1) {
const character = raw[index];
if (character === undefined) return undefined;
const digit = javaDecimalDigit(character);
if (digit === undefined) return undefined;
if (value > Math.floor((limit - digit) / 10)) return undefined;
value = value * 10 + digit;
}
return sign * value;
};
/** Match Integer.parseInt(charAt) for BMP Decimal_Number characters. */
const javaDecimalDigit = (character: string): number | undefined => {
const code = character.charCodeAt(0);
if (code >= 48 && code <= 57) return code - 48;
if (!/^\p{Decimal_Number}$/u.test(character)) return undefined;
let blockStart = code;
while (
blockStart > 0 &&
/^\p{Decimal_Number}$/u.test(String.fromCharCode(blockStart - 1))
)
blockStart -= 1;
return (code - blockStart) % 10;
};
const integerGroup = (value: string | undefined): number | undefined => {
if (value === undefined) return undefined;
const parsed = Number(value);
@@ -204,17 +270,119 @@ const integerGroup = (value: string | undefined): number | undefined => {
const unresolvedJavaRequirement = (
unresolved: string,
): GhidraJavaRequirement => ({
minimumMajor: SUPPORTED_GHIDRA_JAVA_MAJOR,
maximumMajor: null,
unresolved,
});
const propertyValue = (content: string, name: string): string | null => {
for (const line of content.split(/\r?\n/u)) {
const separator = line.indexOf("=");
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
const value = line.slice(separator + 1).trim();
return value.length === 0 ? null : value;
/** Parse Java Properties.load(InputStream) syntax from its ISO-8859-1 text. */
const parseJavaProperties = (
content: string,
): Result<ReadonlyMap<string, string>, string> => {
const values = new Map<string, string>();
for (const line of logicalPropertyLines(content)) {
let start = 0;
while (isPropertyWhitespace(line[start])) start += 1;
if (start === line.length || line[start] === "#" || line[start] === "!")
continue;
let end = start;
let escaped = false;
while (end < line.length) {
const character = line[end];
if (
!escaped &&
(character === "=" ||
character === ":" ||
isPropertyWhitespace(character))
)
break;
if (character === "\\") escaped = !escaped;
else escaped = false;
end += 1;
}
let valueStart = end;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
if (line[valueStart] === "=" || line[valueStart] === ":") valueStart += 1;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
const key = decodePropertyEscapes(line.slice(start, end));
if (!key.ok) return err(key.error);
const value = decodePropertyEscapes(line.slice(valueStart));
if (!value.ok) return err(value.error);
values.set(key.value, value.value);
}
return null;
return ok(values);
};
const isPropertyWhitespace = (value: string | undefined): boolean =>
value === " " || value === "\t" || value === "\f";
/** Join odd-backslash continuations while stripping leading continuation space. */
function* logicalPropertyLines(content: string): Generator<string> {
let physicalStart = 0;
let logical = "";
let continuing = false;
while (physicalStart <= content.length) {
let physicalEnd = physicalStart;
while (
physicalEnd < content.length &&
content[physicalEnd] !== "\n" &&
content[physicalEnd] !== "\r"
)
physicalEnd += 1;
let line = content.slice(physicalStart, physicalEnd);
let leading = 0;
while (isPropertyWhitespace(line[leading])) leading += 1;
const comment =
!continuing && (line[leading] === "#" || line[leading] === "!");
if (continuing) line = line.slice(leading);
let continued = false;
if (!comment) {
let slashes = 0;
for (
let index = line.length - 1;
index >= 0 && line[index] === "\\";
index -= 1
)
slashes += 1;
continued = slashes % 2 === 1;
logical += continued ? line.slice(0, -1) : line;
}
if (!continued) {
yield logical;
logical = "";
}
continuing = continued;
if (physicalEnd === content.length) break;
physicalStart =
content[physicalEnd] === "\r" && content[physicalEnd + 1] === "\n"
? physicalEnd + 2
: physicalEnd + 1;
}
// Properties.load still consumes the accumulated line when EOF follows a
// continuation marker; the marker itself was already removed above.
if (continuing) yield logical;
}
const decodePropertyEscapes = (value: string): Result<string, string> => {
let result = "";
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (character !== "\\") {
result += character;
continue;
}
const escaped = value[++index];
if (escaped === undefined)
return err("Trailing escape in Java properties value");
if (escaped === "t") result += "\t";
else if (escaped === "n") result += "\n";
else if (escaped === "r") result += "\r";
else if (escaped === "f") result += "\f";
else if (escaped === "u") {
const digits = value.slice(index + 1, index + 5);
if (digits.length !== 4 || !/^[0-9a-f]{4}$/iu.test(digits))
return err("Malformed Unicode escape in Java properties file");
result += String.fromCharCode(Number.parseInt(digits, 16));
index += 4;
} else result += escaped;
}
return ok(result);
};
+1 -1
View File
@@ -42,7 +42,7 @@ const X86_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+1 -1
View File
@@ -19,7 +19,7 @@ import { ghidraProfileLanguageOverride } from "./GhidraAnalysisProfile.js";
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+1 -1
View File
@@ -38,7 +38,7 @@ const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+1 -1
View File
@@ -53,7 +53,7 @@ const RISCV_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+2 -1
View File
@@ -39,7 +39,8 @@ const fixture = (version = "12.1.4") => {
{
platform: "linux",
architecture: "x64",
readText: () => `application.version=${version}\n`,
readText: () =>
`application.version=${version}\napplication.java.min=21\n`,
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+3
View File
@@ -413,6 +413,8 @@ const launchHopperProcess = async (input: {
runId: input.session.runId,
expectedCommand: ownershipCommand,
hostEnvironment: input.options.environment,
// The helper observes EOF when this REA process exits, including SIGKILL.
stdin: "pipe",
...(input.signal === undefined ? {} : { signal: input.signal }),
});
return spawn(input.argumentsForTarget);
@@ -434,6 +436,7 @@ export const linuxDemoLaunch = (
return undefined;
const helperArguments = [
options.demoHelperPath,
"--owner-stdin",
"--strategy",
strategy ?? "direct",
...(strategy === "user-mount-namespace" ? ["--mount-private-x11"] : []),
@@ -19,31 +19,6 @@ export const isBeforeSourceMapLeafStop = (
);
};
/** Resolve one declaration with the same pinned upstream implementation used by full maps. */
export const resolveSourceMapSource = (
source: string | null,
sourceRoot: string | null | undefined,
mapUrl: string,
): string => {
const map = new TraceMap(
{
version: 3,
names: [],
sources: [source ?? ""],
...(sourceRoot == null ? {} : { sourceRoot }),
mappings: "",
},
mapUrl,
);
const resolved = map.resolvedSources[0];
if (resolved === undefined)
throw new SourceMapFormatFailure(
"format",
"Source-map resolver did not return the requested source identity.",
);
return resolved;
};
/** Decode leaf mappings and validate producer indices before any consumer publishes them. */
export const decodeValidatedSourceMapLeaves = (
leaves: readonly SourceMapLeaf[],
+63 -10
View File
@@ -42,14 +42,62 @@ export const pushDispatchCoverage = (input: {
vtables,
swift,
} = input;
const classOwnedMethods = result.objc_dispatch_implementations.filter(
({ category }) => category === undefined,
);
const classRecords = [
...result.objc_classes.flatMap((record) =>
record.decode?.status === "decoded"
? []
: [
`class ${record.name}: ${record.decode?.reason ?? record.decode?.status ?? "decode_status_missing"}`,
],
),
...result.objc_protocol_records.flatMap((record) =>
record.decode.status === "decoded"
? []
: [
`protocol ${record.name}: ${record.decode.reason ?? record.decode.status}`,
],
),
...classOwnedMethods.flatMap((record) =>
record.decode.status === "decoded"
? []
: [
`method ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`,
],
),
...result.objc_ivars.flatMap((record) =>
record.decode.status === "decoded"
? []
: [
`ivar ${record.class_name}.${record.name}: ${record.decode.reason ?? record.decode.status}`,
],
),
];
const classReasons = [
...failures,
...classRecords,
...(truncated ? ["max_records_reached"] : []),
];
const categoryMethods = result.objc_dispatch_implementations.filter(
({ category }) => category !== undefined,
);
const categoryMethodReasons = categoryMethods.flatMap((record) =>
record.decode.status === "decoded"
? []
: [
`category method ${record.category} ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`,
],
);
result.coverage.push({
facet: "objc_class_method_ivar_metadata",
status: failures.length > 0 || truncated ? "partial" : "complete",
reason:
[...failures, ...(truncated ? ["max_records_reached"] : [])].join("; ") ||
null,
status: classReasons.length > 0 ? "partial" : "complete",
reason: classReasons.join("; ") || null,
examined,
decoded: result.objc_classes.length,
decoded: result.objc_classes.filter(
({ decode }) => decode?.status === "decoded",
).length,
});
result.coverage.push({
facet: "binary_relative_pointers",
@@ -79,13 +127,18 @@ export const pushDispatchCoverage = (input: {
status:
truncated ||
categoryFailures.length > 0 ||
result.objc_categories.some(({ decode }) => decode.status !== "decoded")
result.objc_categories.some(
({ decode }) => decode.status !== "decoded",
) ||
categoryMethodReasons.length > 0
? "partial"
: "complete",
reason:
[...categoryFailures, ...(truncated ? ["max_records_reached"] : [])].join(
"; ",
) || null,
[
...categoryFailures,
...categoryMethodReasons,
...(truncated ? ["max_records_reached"] : []),
].join("; ") || null,
examined: categoriesExamined,
decoded: result.objc_categories.filter(
({ decode }) => decode.status === "decoded",
@@ -110,7 +163,7 @@ export const pushDispatchCoverage = (input: {
: "complete",
reason: fixupReason.length > 0 ? fixupReason : null,
examined: fixups.examined,
decoded: fixups.issues.length > 0 ? 0 : fixups.examined,
decoded: fixups.decoded,
});
result.coverage.push({
facet: "swift_generic_resilient_witnesses_overrides_async_coroutines",
+136 -6
View File
@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";
import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
const base = 0x100000000n;
const fixture = (relative = false) => {
const fixture = (
relative = false,
category?: "partial-method" | "unmapped-pointer",
) => {
const bytes = Buffer.alloc(4096);
const u32 = (offset: number, value: number) =>
bytes.writeUInt32LE(value, offset);
@@ -11,19 +14,26 @@ const fixture = (relative = false) => {
u32(0, 0xfeedfacf);
u32(4, 0x0100000c);
u32(16, 1);
u32(20, 152);
u32(20, category === undefined ? 152 : 232);
u32(32, 0x19);
u32(36, 152);
u32(36, category === undefined ? 152 : 232);
bytes.write("__DATA", 40);
ptr(56, 0);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
u32(92, 5);
u32(96, 1);
u32(96, category === undefined ? 1 : 2);
bytes.write("__objc_classlist", 104);
bytes.write("__DATA", 120);
ptr(136, 0x180);
bytes.writeBigUInt64LE(8n, 144);
if (category !== undefined) {
bytes.write("__objc_catlist", 184);
bytes.write("__DATA", 200);
ptr(216, 0xb00);
bytes.writeBigUInt64LE(8n, 224);
u32(232, 0xb00);
}
u32(152, 0x180);
ptr(0x180, 0x200);
ptr(0x200, 0x280);
@@ -86,10 +96,58 @@ const fixture = (relative = false) => {
bytes.write("FixtureProtocol\0", 0x900);
bytes.write("requiredAction:\0", 0x920);
bytes.write("optionalAction:\0", 0x940);
if (category !== undefined) {
if (category === "unmapped-pointer") {
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0xb00);
} else {
ptr(0xb00, 0xb40);
ptr(0xb40, 0xbc0);
ptr(0xb48, 0x200);
ptr(0xb50, 0xb80);
u32(0xb80, 24);
u32(0xb84, 1);
ptr(0xb88, 0x460);
ptr(0xb90, 0x5c0);
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0xb98);
bytes.write("FixtureCategory\0", 0xbc0);
}
}
return bytes;
};
const provenance = { path: "/fixture/app", sha256: "a".repeat(64) };
describe("chained Apple dispatch binary metadata", () => {
describe("Apple dispatch pointer fixup metadata", () => {
it("keeps decoded bindings and their coverage when an independent stream fails", () => {
const bytes = fixture();
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(200, 20);
bytes.writeUInt32LE(0x80000022, 184);
bytes.writeUInt32LE(48, 188);
const bindings = Buffer.from([
0x40,
...Buffer.from("_OBJC_CLASS_$_NSObject\0"),
0x70,
0x88,
0x04,
0x90,
0x00,
]);
bindings.copy(bytes, 0xc00);
bytes[0xc80] = 0xd0;
bytes.writeUInt32LE(0xc00, 200);
bytes.writeUInt32LE(bindings.length, 204);
bytes.writeUInt32LE(0xc80, 208);
bytes.writeUInt32LE(1, 212);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes[0]).toMatchObject({
name: "Fixture",
super_class: "NSObject",
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({ status: "partial", examined: 2, decoded: 1 });
});
it("keeps absolute metadata pointers between declared chained fixups", () => {
const bytes = fixture();
bytes.writeUInt32LE(2, 16);
@@ -120,7 +178,7 @@ describe("chained Apple dispatch binary metadata", () => {
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({ status: "complete" });
).toMatchObject({ status: "complete", examined: 1, decoded: 1 });
});
});
describe("Apple dispatch binary metadata", () => {
@@ -221,6 +279,9 @@ describe("Apple dispatch binary metadata", () => {
});
},
);
});
describe("Apple dispatch coverage ownership", () => {
it("keeps unsupported pointers and record truncation explicit", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0x498);
@@ -229,6 +290,14 @@ describe("Apple dispatch binary metadata", () => {
implementation_address: null,
decode: { status: "partial" },
});
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("method Fixture instance performAction:"),
});
const truncated = decodeAppleDispatchMetadata(fixture(), 1, provenance);
expect(truncated.coverage[0]?.reason).toContain("max_records_reached");
expect(
@@ -237,6 +306,67 @@ describe("Apple dispatch binary metadata", () => {
),
).toMatchObject({ status: "partial", reason: "max_records_reached" });
});
it("keeps partial category methods in category coverage only", () => {
const baseline = decodeAppleDispatchMetadata(fixture(), 100, provenance);
const result = decodeAppleDispatchMetadata(
fixture(false, "partial-method"),
100,
provenance,
);
expect(result.objc_dispatch_implementations).toContainEqual(
expect.objectContaining({
category: "FixtureCategory",
decode: {
status: "partial",
reason: "implementation_pointer_unmapped_or_encoded",
},
}),
);
const baselineClassCoverage = baseline.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
const classCoverage = result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
expect(baselineClassCoverage).toBeDefined();
expect(classCoverage).toEqual(baselineClassCoverage);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("category method FixtureCategory"),
});
});
it("keeps malformed category pointers out of class failure coverage", () => {
const baseline = decodeAppleDispatchMetadata(fixture(), 100, provenance);
const result = decodeAppleDispatchMetadata(
fixture(false, "unmapped-pointer"),
100,
provenance,
);
const baselineClassCoverage = baseline.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
const classCoverage = result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
expect(baselineClassCoverage).toBeDefined();
expect(classCoverage).toEqual(baselineClassCoverage);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("category_decode_failed"),
});
});
});
describe("malformed Apple dispatch metadata", () => {
it("rejects malformed command and section boundaries", () => {
const bytes = fixture();
bytes.writeUInt32LE(7, 36);
+66 -1
View File
@@ -149,6 +149,64 @@ const SEGMENTS: Segment[] = [
{ address: BASE + 0x4000n, size: 0x4000n, offset: 0x4000, executable: false },
];
describe("independent chained segment coverage", () => {
it("counts successfully decoded chained segments alongside an unsupported segment", () => {
const starts = 28;
const startsSize = 4 + 2 * 4;
const firstInfo = starts + startsSize;
const secondInfo = firstInfo + 24;
const imports = secondInfo + 24;
const data = Buffer.alloc(0x3000);
data.writeUInt32LE(starts, 4);
data.writeUInt32LE(imports, 8);
data.writeUInt32LE(imports, 12);
data.writeUInt32LE(1, 20);
data.writeUInt32LE(2, starts);
data.writeUInt32LE(firstInfo - starts, starts + 4);
data.writeUInt32LE(secondInfo - starts, starts + 8);
for (const [info, format, segmentOffset] of [
[firstInfo, 6, 0],
[secondInfo, 99, 0x1000],
] as const) {
data.writeUInt32LE(24, info);
data.writeUInt16LE(0x1000, info + 4);
data.writeUInt16LE(format, info + 6);
data.writeBigUInt64LE(BigInt(segmentOffset), info + 8);
data.writeUInt16LE(1, info + 20);
data.writeUInt16LE(8, info + 22);
}
const segments: Segment[] = [
{ address: BASE, size: 0x1000n, offset: 0x1000, executable: false },
{
address: BASE + 0x1000n,
size: 0x1000n,
offset: 0x2000,
executable: false,
},
];
const fixups = parsePointerFixups(
data,
{
chained: { offset: 0, size: imports },
binds: [],
rebases: [],
dylibs: [],
},
segments,
BASE,
);
expect(fixups).toMatchObject({ examined: 2, decoded: 1 });
expect(fixups.issues).toMatchObject([
{ code: "unsupported_pointer_format" },
]);
expect(fixups.decode(BASE + 8n, 0n)).toEqual({
kind: "rebase",
target: BASE,
});
});
});
describe("pointer fixup tables", () => {
it("reports unsupported pointer formats even when no pointer is visited", () => {
const data = chainedData(1);
@@ -196,20 +254,27 @@ describe("pointer fixup tables", () => {
{
chained: { offset: 0, size: 128 },
binds: [],
rebases: [],
rebases: [{ offset: 8, size: 12 }],
dylibs: [],
},
SEGMENTS,
BASE,
);
expect(fixups).toMatchObject({
examined: 1,
decoded: 1,
unreadRebaseBytes: 12,
});
expect(fixups.decode(BASE + 0x4008n, field(1n, 63))).toMatchObject({
kind: "bind",
symbol: "_OBJC_CLASS_$_NSObject",
});
expect(fixups.issues).toEqual([]);
expect(fixups.decoded).toBe(1);
expect(fixups.decode(BASE + 0x4008n, 1n | field(1n, 63))).toMatchObject({
kind: "unsupported",
});
expect(fixups.decoded).toBe(0);
expect(fixups.issues).toMatchObject([
{ code: "chained_pointer_decode_failed" },
]);
+28 -11
View File
@@ -42,6 +42,8 @@ export interface PointerFixups {
readonly issues: readonly DecodeIssue[];
/** Fixup segments or bind streams this reader walked. */
readonly examined: number;
/** Fully decoded fixup segments or bind streams, in the same units as `examined`. */
readonly decoded: number;
/** Rebase opcode bytes present in the load command and not decoded. */
readonly unreadRebaseBytes: number;
/** Decode the pointer stored at `address` whose raw 64-bit value is `raw`. */
@@ -260,6 +262,7 @@ const readChainedPage = (
const chainedFixups = (
image: FixupImage,
range: { readonly offset: number; readonly size: number },
unreadRebaseBytes: number,
): PointerFixups => {
const { bytes, segments, dylibs, baseAddress } = image;
const base = range.offset;
@@ -400,19 +403,25 @@ const chainedFixups = (
]
: [],
);
const examinedViews = new Set<string>();
for (const chain of ranges) {
const examinedViews = new Map<string, boolean>();
const decodedRanges = new Set<number>();
for (const [chainIndex, chain] of ranges.entries()) {
// Unknown formats retain their compact starts table; only a queried page
// needs its NONE/presence value. Do not expand unsupported declarations.
if (POINTER_FORMATS[chain.format] === undefined) continue;
const view = `${chain.pageStarts}:${chain.segment.offset}:${chain.segment.size}:${chain.segment.address}`;
if (examinedViews.has(view)) continue;
examinedViews.add(view);
const view = `${chain.pageStarts}:${chain.segment.offset}:${chain.segment.size}:${chain.segment.address}:${chain.format}:${chain.pageSize}:${chain.pageCount}`;
const prior = examinedViews.get(view);
if (prior !== undefined) {
if (prior) decodedRanges.add(chainIndex);
continue;
}
let complete = true;
for (let page = 0; page < chain.pageCount; page++) {
const start = bytes.readUInt16LE(chain.pageStarts + page * 2);
if (start === 0xffff) continue;
const facts = pageFacts(chain, page, start);
if (facts.failure !== undefined) {
complete = false;
issues.push(
issue(
"pointer_fixups",
@@ -427,6 +436,8 @@ const chainedFixups = (
break;
}
}
examinedViews.set(view, complete);
if (complete) decodedRanges.add(chainIndex);
}
const failures = issues.map(({ message }) => message);
return {
@@ -435,13 +446,17 @@ const chainedFixups = (
failures,
issues,
examined: Math.max(ranges.length, 1),
unreadRebaseBytes: 0,
get decoded() {
return ranges.length === 0 ? 1 : decodedRanges.size;
},
unreadRebaseBytes,
decode(address, raw) {
const chain = ranges.find(
const chainIndex = ranges.findIndex(
({ segment }) =>
address >= segment.address &&
address < segment.address + segment.size,
);
const chain = ranges[chainIndex];
// Pointers outside fixup segments, such as in __TEXT, are stored plainly.
if (chain === undefined) return { kind: "rebase", target: raw };
const within = Number(address - chain.segment.address);
@@ -486,6 +501,7 @@ const chainedFixups = (
);
failures.push(reason);
}
decodedRanges.delete(chainIndex);
return { kind: "unsupported", reason };
}
},
@@ -684,10 +700,7 @@ export const parsePointerFixups = (
0,
);
if (commands.chained !== null) {
const chained = chainedFixups(image, commands.chained);
return unreadRebaseBytes === 0
? chained
: { ...chained, unreadRebaseBytes };
return chainedFixups(image, commands.chained, unreadRebaseBytes);
}
if (commands.binds.length === 0)
return {
@@ -696,14 +709,17 @@ export const parsePointerFixups = (
failures: [],
issues: [],
examined: 0,
decoded: 0,
unreadRebaseBytes,
decode: (_address, raw) => ({ kind: "rebase", target: raw }),
};
const binds: BindRun[] = [];
const failures: string[] = [];
let decoded = 0;
for (const stream of commands.binds)
try {
readBindStream(image, stream, binds);
decoded++;
} catch (cause: unknown) {
failures.push(
`${stream.stream} bind opcodes: ${cause instanceof Error ? cause.message : String(cause)}`,
@@ -717,6 +733,7 @@ export const parsePointerFixups = (
issue("pointer_fixups", "bind_stream_decode_failed", message),
),
examined: commands.binds.length,
decoded,
unreadRebaseBytes,
decode(address, raw) {
let match: BindRun | undefined;
+1 -3
View File
@@ -23,7 +23,6 @@ export const decodeObjcCategories = (input: {
readonly sections: readonly Section[];
readonly read: ObjcDispatchReaders;
readonly result: ObjcSwiftMetadata;
readonly failures: string[];
readonly issues: DecodeIssue[];
readonly admit: () => boolean;
/** Decode a method list into implementations attributed to the category. */
@@ -37,7 +36,7 @@ export const decodeObjcCategories = (input: {
/** Name of a class defined in this image, from its class_ro_t. */
readonly localClassName: (address: bigint) => string;
}): number => {
const { read, result, failures } = input;
const { read, result } = input;
let examined = 0;
for (const section of input.sections.filter(
({ name }) => name === "__objc_catlist",
@@ -93,7 +92,6 @@ export const decodeObjcCategories = (input: {
});
} catch (cause: unknown) {
const message = cause instanceof Error ? cause.message : String(cause);
failures.push(`Category at 0x${field.toString(16)}: ${message}`);
input.issues.push(
issue(
"objc_properties_categories",
-1
View File
@@ -335,7 +335,6 @@ export const decodeObjcDispatchFacets = (input: {
sections,
read,
result,
failures,
issues: categoryIssues,
admit: () => budget.admit(),
methods,
+2
View File
@@ -67,6 +67,7 @@ describe("Swift vtable coverage facts: unresolved Swift dispatch slots", () => {
issues: [],
decode: (_address, raw) => ({ kind: "rebase", target: raw }),
examined: 0,
decoded: 0,
unreadRebaseBytes: 0,
},
swift: {
@@ -181,6 +182,7 @@ describe("Swift vtable coverage facts: unsupported pointer fixup coverage", () =
reason: "Unsupported chained pointer format 99",
}),
examined: 0,
decoded: 0,
unreadRebaseBytes: 0,
},
swift: {
+65 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { inspectNativeMacho } from "./NativeMachoInspection.js";
@@ -186,3 +189,64 @@ describe("Mach-O UUID reconciliation", () => {
);
});
});
describe("Mach-O slice command scheduling", () => {
const SLICE_TOOLS = ["otool", "nm", "dyld_info", "dyld_info", "dwarfdump"];
/** Finish later-launched slice commands first and record overlap. */
const reorderingRunner = (failing: ReadonlySet<string> = new Set()) => {
const fixtures = new NativeFixtureRunner();
let inFlight = 0;
let maxInFlight = 0;
let launched = 0;
const run = async (tool: string, args: readonly string[]) => {
if (tool === "file" || tool === "lipo") return fixtures.run(tool, args);
const order = launched++;
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
for (let turn = 0; turn < 12 - order * 2; turn += 1)
await new Promise((resolve) => setImmediate(resolve));
inFlight -= 1;
if (failing.has(tool))
return err(new AnalysisOutputError("inspect_macho", `${tool} failed`));
return fixtures.run(tool, args);
};
return { run, maxInFlight: () => maxInFlight };
};
const inspectWith = (run: ReturnType<typeof reorderingRunner>["run"]) =>
inspectNativeMacho({
target: nativeMachoTarget("/fixture/app"),
run,
invocation: (capture) => ({
tool: capture.tool,
command: [capture.executable, ...capture.arguments],
tool_version: capture.toolVersion,
version_reason: capture.versionReason,
executable_sha256: capture.executableSha256,
exit: { code: capture.exitCode, signal: capture.signal },
stdout_bytes: capture.stdoutBytes,
stderr_bytes: capture.stderrBytes,
}),
});
it("runs independent slice commands together and keeps provenance in declared order", async () => {
const runner = reorderingRunner();
const result = await inspectWith(runner.run);
if (!result.ok) throw result.error;
expect(runner.maxInFlight()).toBe(SLICE_TOOLS.length + 1);
expect(result.value.result).toMatchObject({
provenance: ["file", "lipo", ...SLICE_TOOLS, "vtool"].map((tool) => ({
tool,
})),
});
});
it("reports the first failing slice command in declared order", async () => {
const runner = reorderingRunner(new Set(["nm", "dwarfdump"]));
const result = await inspectWith(runner.run);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({ reason: "nm failed" });
});
});
+13 -12
View File
@@ -79,8 +79,11 @@ export const inspectNativeMacho = async (
);
const selectedArchitecture =
selection.status === "selected" ? selection.architecture : null;
for (const [tool, prefix] of REQUIRED_SLICE_COMMANDS) {
const captured = await context.run(
const runSliceCommand = ([tool, prefix]: readonly [
string,
readonly string[],
]) =>
context.run(
tool,
[
...prefix,
@@ -89,20 +92,18 @@ export const inspectNativeMacho = async (
],
context.signal,
);
// Slice commands only read the selected artifact, so launch them together.
// Every launch settles before return; declared order fixes provenance and
// which failure is reported.
const [required, optional] = await Promise.all([
Promise.all(REQUIRED_SLICE_COMMANDS.map(runSliceCommand)),
runSliceCommand(OPTIONAL_VTOOL_COMMAND),
]);
for (const captured of required) {
if (!captured.ok) return err(captured.error);
captures.push(captured.value);
}
const limitations: string[] = [];
const [tool, prefix] = OPTIONAL_VTOOL_COMMAND;
const optional = await context.run(
tool,
[
...prefix,
...selectedArchitectureArguments(tool, selectedArchitecture),
context.target.path,
],
context.signal,
);
if (optional.ok) captures.push(optional.value);
else if (optional.error._tag === "AnalysisCapabilityUnavailableError")
limitations.push(VTOOL_UNAVAILABLE_LIMITATION);
+7
View File
@@ -518,6 +518,13 @@ export class PwntoolsDecoder<
[
pending.process.launch.ownership?.runId ?? "owned-decoder",
...(pending.root === undefined ? [] : [pending.root.path]),
// The retained group may still be live; name it as OwnedCommand does.
...(pending.process.launch.ownership === undefined
? []
: [
`pid:${pending.process.launch.ownership.leaderPid}`,
`process-group:${pending.process.launch.ownership.processGroupId}`,
]),
],
{
reason: stopped.reason,
+205
View File
@@ -0,0 +1,205 @@
import { randomUUID } from "node:crypto";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisProtocolError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";
import {
isWindowsBatchFile,
windowsBatchCommand,
WindowsBatchCommandError,
} from "../process/WindowsBatchCommand.js";
import { pcapToolUnavailable } from "./PcapConfiguration.js";
export interface PcapCommandLimits {
readonly timeoutMs: number;
readonly maxOutputBytes: number;
}
/** Owned process execution shared by version probes and capture reads. */
export const runPcapCommand = async (options: {
readonly operation: string;
readonly command: string;
readonly arguments: readonly string[];
readonly limits: PcapCommandLimits;
readonly environment: Readonly<Record<string, string | undefined>>;
readonly signal: AbortSignal | undefined;
readonly inputPath?: string;
readonly nativeBound?: {
readonly limiter?: { command: string; arguments: readonly string[] };
readonly memoryLimitBytes?: number;
};
readonly retain: (
owner: ProviderProcessSupervisor,
resources: readonly string[],
) => void;
}): Promise<{ stdout: string; stderr: string }> => {
const { operation, command, limits, signal } = options;
if (signal?.aborted)
throw new AnalysisCancelledError(operation, { cause: signal.reason });
const hostEnvironment = {
...process.env,
...options.environment,
LC_ALL: "C",
LANG: "C",
};
try {
const batch = process.platform === "win32" && isWindowsBatchFile(command);
const invocation = batch
? windowsBatchCommand({
environment: hostEnvironment,
batchPath: command,
arguments: options.arguments,
})
: { command, arguments: options.arguments };
const boundedInvocation =
options.nativeBound?.limiter === undefined
? invocation
: {
command: options.nativeBound.limiter.command,
arguments: [
...options.nativeBound.limiter.arguments,
invocation.command,
...invocation.arguments,
],
};
// Native ownership preparation has its own bounded compiler lifecycle;
// do not spend the tool's execution deadline rebuilding a cold SDK cache.
await prepareProcessOwnershipInspection(signal);
const output = await runOwnedCommand(
{
...boundedInvocation,
runId: randomUUID(),
hostEnvironment,
windowsVerbatimArguments: batch,
expectedCommand: null,
...(options.nativeBound?.memoryLimitBytes === undefined
? {}
: { memoryLimitBytes: options.nativeBound.memoryLimitBytes }),
},
{ timeoutMs: limits.timeoutMs, diagnosticBytes: limits.maxOutputBytes },
signal === undefined ? {} : { signal },
);
return { stdout: output.stdout.text, stderr: output.stderr.text };
} catch (cause) {
if (cause instanceof AnalysisError) throw cause;
if (
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
options.retain(cause.cleanupOwner, cause.resources);
const details = {
cause,
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
capturedOutput: {
stdout: "",
stderr: cause.snapshot.stderr.text,
truncated:
cause.snapshot.stdout.observedBytes > 0 ||
(cause.snapshot.diagnosticTruncated ?? false),
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
},
}
: {}),
...(cause instanceof OwnedCommandFailure && cause.cleanupFailure !== null
? {
cleanup: {
reason: cause.cleanupFailure,
resources: cause.resources,
},
}
: {}),
};
if (
signal?.aborted ||
(cause instanceof OwnedCommandFailure && cause.reason === "cancelled")
)
throw new AnalysisCancelledError(operation, details);
if (
cause instanceof OwnedCommandFailure &&
cause.snapshot?.memoryLimitReached === true
)
throw new AnalysisResourceConstraintError(
operation,
"memory",
"The owned Windows tool tree reached its enforced committed-memory limit.",
{
process_memory_limit_bytes:
options.nativeBound?.memoryLimitBytes ?? null,
},
details,
);
if (
cause instanceof OwnedCommandFailure &&
(cause.snapshot?.signal === "SIGXCPU" ||
cause.snapshot?.signal === "SIGXFSZ")
)
throw new AnalysisResourceConstraintError(
operation,
cause.snapshot.signal === "SIGXCPU" ? "cpu" : "file-size",
`Producer terminated with ${cause.snapshot.signal}; its exact cause is not independently established.`,
null,
details,
);
if (cause instanceof OwnedCommandFailure && cause.reason === "timeout")
throw new AnalysisTimeoutError(operation, limits.timeoutMs, details);
if (cause instanceof OwnedCommandFailure && cause.reason === "output-limit")
throw new AnalysisResourceConstraintError(
operation,
"memory",
"Tool output exceeded its complete-output budget",
{ max_output_bytes: limits.maxOutputBytes },
details,
);
if (
cause instanceof WindowsBatchCommandError ||
(cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "EACCES"))
)
throw pcapToolUnavailable(
operation,
`Cannot run selected tool ${command}: ${cause.message}`,
details,
);
const diagnostic =
cause instanceof OwnedCommandFailure
? cause.snapshot?.stderr.text.trim() || cause.message
: cause instanceof Error
? cause.message
: String(cause);
if (options.inputPath === undefined)
throw pcapToolUnavailable(
operation,
`The selected tool ${command} cannot report its version: ${diagnostic}`,
details,
);
if (
options.inputPath !== undefined &&
/not a capture file|file.*isn't a capture file|file format.*not supported/iu.test(
diagnostic,
)
)
throw new AnalysisUnsupportedTargetError(
operation,
options.inputPath,
diagnostic,
details,
);
throw new AnalysisProtocolError(
`Packet capture tool ${command} failed: ${diagnostic}`,
details,
);
}
};
+170
View File
@@ -0,0 +1,170 @@
import { describe, expect, it } from "vitest";
import {
CAPINFOS_COMMAND_ENV,
TSHARK_COMMAND_ENV,
resolvePcapTools,
} from "./PcapConfiguration.js";
import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js";
describe("resolvePcapTools", () => {
it("prefers absolute environment paths for both tools", () => {
expect(
resolvePcapTools({
[TSHARK_COMMAND_ENV]: "/usr/bin/tshark",
[CAPINFOS_COMMAND_ENV]: "/usr/bin/capinfos",
}),
).toEqual({
tshark: { command: "/usr/bin/tshark", source: "environment" },
capinfos: { command: "/usr/bin/capinfos", source: "environment" },
});
});
it("falls back to PATH resolution without the environment keys", () => {
expect(resolvePcapTools({})).toEqual({
tshark: { command: "tshark", source: "path" },
capinfos: { command: "capinfos", source: "path" },
});
});
it("rejects a relative tshark path explicitly", () => {
expect(() =>
resolvePcapTools({ [TSHARK_COMMAND_ENV]: "bin/tshark" }),
).toThrow(/must be an absolute path/u);
});
it("rejects a relative capinfos path explicitly", () => {
expect(() =>
resolvePcapTools({ [CAPINFOS_COMMAND_ENV]: "capinfos" }),
).toThrow(/must be an absolute path/u);
});
});
const REAL_CAPINFOS = [
"File name: /work/rich-capture.pcap",
"File type: Wireshark/tcpdump/... - pcap",
"File encapsulation: Linux cooked-mode capture v2",
"Packet size limit: file hdr: 262144 bytes",
"Number of packets: 50",
"File size: 23279 bytes",
"Capture duration: 0.373473 seconds",
"Earliest packet time: 2026-10-11 14:13:40.608505",
"Latest packet time: 2026-10-11 14:13:40.981978",
"SHA256: c94f94742b3288b9a979711509ed5eab3028576301f8938319de3c22a6f5c40b",
].join("\n");
describe("parseCapinfosOutput", () => {
it("projects metadata from real capinfos output", () => {
expect(parseCapinfosOutput(REAL_CAPINFOS)).toEqual({
fileType: "Wireshark/tcpdump/... - pcap",
encapsulation: "Linux cooked-mode capture v2",
packetCount: 50,
captureStart: "2026-10-11 14:13:40.608505",
captureEnd: "2026-10-11 14:13:40.981978",
captureDurationSeconds: 0.373473,
snapshotLength: 262144,
sha256:
"c94f94742b3288b9a979711509ed5eab3028576301f8938319de3c22a6f5c40b",
});
});
it("rejects empty metadata rather than reporting complete unknown facts", () => {
expect(() => parseCapinfosOutput("")).toThrow(/machine-readable/u);
});
});
const REAL_TSHARK_JSON = JSON.stringify([
{
_source: {
layers: {
"frame.number": ["1"],
"frame.protocols": ["sll:ethertype:ip:udp:dns"],
"ip.src": ["192.168.1.1"],
"ip.dst": ["8.8.8.8"],
"dns.qry.name": ["example.com"],
"dns.flags.response": ["1"],
"dns.a": ["93.184.216.34"],
},
},
},
{
_source: {
layers: {
"frame.number": ["2"],
"frame.protocols": ["sll:ethertype:ip:tcp:tls"],
"ip.src": ["192.168.1.1"],
"ip.dst": ["93.184.216.34"],
"tls.handshake.extensions_server_name": ["example.com"],
},
},
},
{
_source: {
layers: {
"frame.number": ["3"],
"frame.protocols": ["sll:ethertype:ip:tcp:http"],
"ip.src": ["192.168.1.1"],
"ip.dst": ["93.184.216.34"],
"http.request.full_uri": ["http://example.com/page"],
},
},
},
]);
describe("parseTsharkJsonOutput", () => {
it("projects endpoints, DNS, TLS SNI, protocols, and HTTP URIs", async () => {
const result = await parseTsharkJsonOutput(REAL_TSHARK_JSON);
expect(result.endpoints).toEqual(
expect.arrayContaining([
{ address: "192.168.1.1", port: null, packet_count: 3 },
{ address: "8.8.8.8", port: null, packet_count: 1 },
{ address: "93.184.216.34", port: null, packet_count: 2 },
]),
);
expect(result.dnsQueries).toEqual([
{
query: "example.com",
response_addresses: ["93.184.216.34"],
response_address_count: 1,
},
]);
expect(result.tlsSniValues).toEqual(["example.com"]);
expect(result.httpRequestUris).toEqual(["http://example.com/page"]);
expect(result.protocolDistribution).toEqual(
expect.arrayContaining([
{ protocol: "sll:ethertype:ip:udp:dns", packet_count: 1 },
{ protocol: "sll:ethertype:ip:tcp:tls", packet_count: 1 },
{ protocol: "sll:ethertype:ip:tcp:http", packet_count: 1 },
]),
);
});
it("retains every endpoint within the aggregate resource budget", async () => {
const packets = Array.from({ length: 10 }, (_, index) => ({
_source: {
layers: {
"frame.number": [String(index + 1)],
"frame.protocols": ["ip:tcp"],
"ip.src": [`10.0.0.${index}`],
"ip.dst": ["10.0.1.1"],
},
},
}));
const result = await parseTsharkJsonOutput(JSON.stringify(packets));
expect(result.endpoints).toHaveLength(11);
expect(result.endpointCount).toBe(11); // 10 src + 1 dst
});
it.each([
"",
"not json",
"{}",
"null",
"[null]",
'[{"_source":{"layers":{"ip.src":[3]}}}]',
])("rejects malformed producer output %s", async (text) => {
await expect(parseTsharkJsonOutput(text)).rejects.toMatchObject({
_tag: "AnalysisProtocolError",
});
});
});
+172
View File
@@ -0,0 +1,172 @@
import { isAbsolute } from "node:path";
import type { ProviderAvailability } from "../application/AnalysisProvider.js";
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { JsonValue } from "../domain/jsonValue.js";
/** Environment keys selecting the caller's tshark and capinfos binaries. */
export const TSHARK_COMMAND_ENV = "REA_TSHARK_COMMAND";
export const CAPINFOS_COMMAND_ENV = "REA_CAPINFOS_COMMAND";
const TOOL_REMEDIATION = `Supply Wireshark 4.x tshark and capinfos on PATH or through absolute ${TSHARK_COMMAND_ENV} and ${CAPINFOS_COMMAND_ENV}; REA does not install them.`;
/**
* Host-tool refusals concern the caller's Wireshark installation, not the
* target, so they carry their own guidance instead of the generic advice to
* choose another target.
*/
export const pcapToolUnavailable = (
operation: string,
reason: string,
options?: AnalysisErrorOptions,
): AnalysisCapabilityUnavailableError =>
new AnalysisCapabilityUnavailableError("pcap", operation, reason, {
...options,
userMessage: `${/[.!?]$/u.test(reason) ? reason : `${reason}.`} ${TOOL_REMEDIATION}`,
});
/** How each tool was selected for this provider instance. */
export interface PcapToolSelection {
readonly tshark: { command: string; source: "environment" | "path" };
readonly capinfos: { command: string; source: "environment" | "path" };
}
/**
* Resolve the caller-supplied tshark and capinfos binaries. Each accepts an
* absolute environment path or falls back to PATH resolution, mirroring the
* mitmdump pattern. REA never installs the Wireshark suite.
*/
export const resolvePcapTools = (
environment: Readonly<Record<string, string | undefined>>,
): PcapToolSelection => {
const tsharkEnv = environment[TSHARK_COMMAND_ENV];
const capinfosEnv = environment[CAPINFOS_COMMAND_ENV];
if (
tsharkEnv !== undefined &&
tsharkEnv.trim() !== "" &&
!isAbsolute(tsharkEnv)
)
throw new PcapConfigurationFailure(
"tshark_not_absolute",
`${TSHARK_COMMAND_ENV} must be an absolute path to the tshark binary`,
{ configured: tsharkEnv },
);
if (
capinfosEnv !== undefined &&
capinfosEnv.trim() !== "" &&
!isAbsolute(capinfosEnv)
)
throw new PcapConfigurationFailure(
"capinfos_not_absolute",
`${CAPINFOS_COMMAND_ENV} must be an absolute path to the capinfos binary`,
{ configured: capinfosEnv },
);
return {
tshark: {
command:
tsharkEnv === undefined || tsharkEnv.trim() === ""
? "tshark"
: tsharkEnv,
source:
tsharkEnv === undefined || tsharkEnv.trim() === ""
? "path"
: "environment",
},
capinfos: {
command:
capinfosEnv === undefined || capinfosEnv.trim() === ""
? "capinfos"
: capinfosEnv,
source:
capinfosEnv === undefined || capinfosEnv.trim() === ""
? "path"
: "environment",
},
};
};
export type PcapConfigurationFailureCode =
| "tshark_not_absolute"
| "capinfos_not_absolute"
| "tshark_missing"
| "capinfos_missing"
| "tshark_version_unresolved"
| "capinfos_version_unresolved"
| "tshark_version_unsupported"
| "capinfos_version_unsupported";
export class PcapConfigurationFailure extends Error {
constructor(
readonly code: PcapConfigurationFailureCode,
message: string,
readonly diagnostics: Readonly<Record<string, JsonValue>> = {},
options?: ErrorOptions,
) {
super(message, options);
}
}
/** Recognize the selected Wireshark tool's version banner. */
const parseVersion = (
stdout: string,
tool: "tshark" | "capinfos",
): string | null => {
const line = stdout
.split(/\r?\n/u)
.map((entry) => entry.trim())
.find((entry) => entry !== "");
const parsed =
line === undefined
? null
: new RegExp(`^${tool} \\(Wireshark\\) (\\d+)\\.\\d+\\.\\d+`, "iu").exec(
line,
);
if (parsed === null || line === undefined) return null;
if (parsed[1] !== "4")
throw new PcapConfigurationFailure(
`${tool}_version_unsupported`,
"Packet summary inspection currently requires Wireshark 4.x tools; select an installation with the admitted output profile.",
{ version: line },
);
return line;
};
export interface PcapClientIdentity {
readonly tsharkVersion: string | null;
readonly capinfosVersion: string | null;
}
/** Probe both tools without reading any capture file. */
export const inspectPcapClient = async (
selection: PcapToolSelection,
probe: (command: string) => Promise<string>,
): Promise<PcapClientIdentity> => ({
tsharkVersion: parseVersion(await probe(selection.tshark.command), "tshark"),
capinfosVersion: parseVersion(
await probe(selection.capinfos.command),
"capinfos",
),
});
/** Availability in the shape shared by every provider. */
const rejectionCodeOf = (
code: PcapConfigurationFailureCode,
): ProviderRejectionCode =>
code.includes("missing")
? "executable_missing"
: code.includes("unsupported")
? "unsupported_version"
: code.includes("not_absolute")
? "not_configured"
: "version_unresolved";
export const pcapConfigurationAvailability = (
cause: PcapConfigurationFailure,
): ProviderAvailability => ({
status: "unavailable",
code: rejectionCodeOf(cause.code),
reason: cause.message,
diagnostics: { ...cause.diagnostics },
});
+78
View File
@@ -0,0 +1,78 @@
import { access, realpath } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute } from "node:path";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
import type { runPcapCommand } from "./PcapCommand.js";
const PRLIMIT_COMMAND_ENV = "REA_TSHARK_PRLIMIT_COMMAND";
/** Own native capture admission and the exact enforced resource profile. */
export const preparePcapNativeBound = async (
environment: Readonly<Record<string, string | undefined>>,
resources: ArtifactAnalysisResources,
): Promise<{
nativeBound: NonNullable<Parameters<typeof runPcapCommand>[0]["nativeBound"]>;
limitations: readonly string[];
}> => {
if (process.platform === "win32") {
return {
nativeBound: { memoryLimitBytes: 1024 ** 3 },
limitations: [
"Each owned Windows tool tree has a 1 GiB Job Object committed-memory limit; this is not a machine-wide quota.",
],
};
}
if (process.platform !== "linux") {
const reason =
"Packet summaries require an enforceable native memory bound: Linux with util-linux prlimit, or Windows with owned Job Objects. This host's capture boundary remains unsupported.";
throw new AnalysisCapabilityUnavailableError(
"pcap",
"inspect_pcap_capture",
reason,
{ userMessage: reason },
);
}
const configured = environment[PRLIMIT_COMMAND_ENV] ?? "/usr/bin/prlimit";
try {
if (!isAbsolute(configured))
throw new Error(`${PRLIMIT_COMMAND_ENV} must be absolute.`);
const limiter = await realpath(configured);
await access(limiter, constants.X_OK);
const limits = await resources.readLimits({
address_space_bytes: 1024 ** 3,
file_bytes: 64 * 1024 ** 2,
cpu_seconds: 300,
});
const nativeBound = {
limiter: {
command: limiter,
arguments: [
`--as=${limits.address_space_bytes}:${limits.address_space_bytes}`,
`--fsize=${limits.file_bytes}:${limits.file_bytes}`,
`--cpu=${limits.cpu_seconds}:${limits.cpu_seconds}`,
"--core=0:0",
"--",
],
},
};
const limitations = [
`Linux prlimit preserves stricter inherited ceilings: ${limits.address_space_bytes} bytes of per-process address space, ${limits.file_bytes} bytes per file and ${limits.cpu_seconds} CPU seconds; core dumps are disabled. These are not aggregate machine quotas.`,
];
return { nativeBound, limitations };
} catch (cause) {
if (cause instanceof AnalysisError) throw cause;
const reason =
"Cannot establish the selected Linux resource limiter before processing capture bytes.";
throw new AnalysisCapabilityUnavailableError(
"pcap",
"inspect_pcap_capture",
reason,
{
cause,
userMessage: `${reason} (${cause instanceof Error ? cause.message : String(cause)}) Check that ${PRLIMIT_COMMAND_ENV} (default /usr/bin/prlimit) names an absolute, executable util-linux prlimit.`,
},
);
}
};
+149
View File
@@ -0,0 +1,149 @@
import { expect, it } from "vitest";
import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js";
const capture = (layers: ReadonlyArray<Record<string, string[]>>) =>
JSON.stringify(
layers.map((fields, index) => ({
_source: {
layers: {
"frame.number": [String(index + 1)],
"frame.protocols": ["ip:udp:dns"],
...fields,
},
},
})),
);
it("binds interleaved DNS answers to the question in their response packet", async () => {
const result = await parseTsharkJsonOutput(
capture([
{ "dns.qry.name": ["alpha.example"], "dns.flags.response": ["False"] },
{ "dns.qry.name": ["beta.example"], "dns.flags.response": ["False"] },
{
"dns.qry.name": ["alpha.example"],
"dns.flags.response": ["True"],
"dns.a": ["192.0.2.10"],
},
{
"dns.qry.name": ["beta.example"],
"dns.flags.response": ["True"],
"dns.a": ["192.0.2.20"],
},
]),
);
expect(result.dnsQueries).toEqual([
{
query: "alpha.example",
response_addresses: ["192.0.2.10"],
response_address_count: 1,
},
{
query: "beta.example",
response_addresses: ["192.0.2.20"],
response_address_count: 1,
},
]);
expect(result.partial).toBe(false);
});
it("retains unassignable DNS addresses without inventing a query relationship", async () => {
const result = await parseTsharkJsonOutput(
capture([
{
"dns.qry.name": ["alpha.example", "beta.example"],
"dns.flags.response": ["True"],
"dns.a": ["192.0.2.9"],
},
{ "dns.flags.response": ["True"], "dns.aaaa": ["2001:db8::9"] },
]),
);
expect(
result.dnsQueries.every((query) => query.response_addresses.length === 0),
).toBe(true);
expect(result.unattributedDnsAddresses).toEqual(["192.0.2.9", "2001:db8::9"]);
expect(result.unattributedDnsPackets).toBe(2);
expect(result.partial).toBe(true);
});
it("counts IPv6 endpoints once per packet and preserves every examined fact", async () => {
const packets = Array.from({ length: 51 }, (_, index) => ({
"ipv6.src": ["2001:db8::1"],
"ipv6.dst": ["2001:db8::1"],
"tls.handshake.extensions_server_name": [`host${String(index)}.example`],
"frame.protocols": [`ipv6:protocol${String(index)}`],
}));
const result = await parseTsharkJsonOutput(capture(packets));
expect(result.endpoints).toEqual([
{ address: "2001:db8::1", port: null, packet_count: 51 },
]);
expect(result.tlsSniCount).toBe(51);
expect(result.tlsSniValues).toHaveLength(51);
expect(result.protocolCount).toBe(51);
expect(result.protocolDistribution).toHaveLength(51);
expect(result.partial).toBe(false);
});
it("preserves all DNS addresses and their exact examined count", async () => {
const result = await parseTsharkJsonOutput(
capture(
Array.from({ length: 101 }, (_, index) => ({
"dns.qry.name": ["rotating.example"],
"dns.flags.response": ["True"],
"dns.a": [`192.0.2.${String(index)}`],
})),
),
);
expect(result.dnsQueries[0]?.response_addresses).toHaveLength(101);
expect(result.dnsQueries[0]?.response_address_count).toBe(101);
expect(result.partial).toBe(false);
});
it("accepts exact machine packet counts and rejects scaled human counts", () => {
const prefix =
"File type: pcap\nFile encapsulation: Ethernet\nNumber of packets: ";
expect(parseCapinfosOutput(`${prefix}20010`).packetCount).toBe(20010);
expect(() => parseCapinfosOutput(`${prefix}20 k`)).toThrow(
/machine-readable/u,
);
});
it("excludes transport credentials without normalizing observed URL bytes", async () => {
const result = await parseTsharkJsonOutput(
capture([
{
"http.request.full_uri": [
"http://user:password@Example.com/a/../b?token=local-evidence#keep",
],
},
{
"http.request.full_uri": [
"http://other:secret@Example.com/a/../b?token=local-evidence#keep",
],
},
]),
);
expect(result.httpRequestUris).toEqual([
"http://Example.com/a/../b?token=local-evidence#keep",
]);
expect(result.httpRequestUriCount).toBe(2);
expect(result.httpUriRedactionCount).toBe(2);
expect(result.partial).toBe(true);
});
it("refuses dense JSON before its expanded graph exceeds the decoding budget", async () => {
await expect(
parseTsharkJsonOutput(`[${"{},".repeat(600_000)}{}]`),
).rejects.toMatchObject({
_tag: "AnalysisResourceConstraintError",
});
});
it("permits cancellation while validating and aggregating producer output", async () => {
const controller = new AbortController();
const result = parseTsharkJsonOutput(
capture([{ "ip.src": ["192.0.2.1"] }]),
controller.signal,
);
controller.abort(new Error("stopped"));
await expect(result).rejects.toThrow("stopped");
});
+315
View File
@@ -0,0 +1,315 @@
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
import {
AnalysisProtocolError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
const OPERATION = "inspect_pcap_capture";
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
export const TSHARK_JSON_MAX_BYTES = 8 * 1024 * 1024;
const MAX_RETAINED_BYTES = 16 * 1024 * 1024;
const MAX_DECODED_BYTES = 128 * 1024 * 1024;
const protocolFailure = (reason: string): never => {
throw new AnalysisProtocolError(`Invalid packet-capture output: ${reason}`);
};
export interface CapinfosMetadata {
readonly fileType: string;
readonly encapsulation: string;
readonly packetCount: number;
readonly captureStart: string | null;
readonly captureEnd: string | null;
readonly captureDurationSeconds: number | null;
readonly snapshotLength: number | null;
readonly sha256: string | null;
}
/** capinfos -M with a C locale provides exact numbers instead of "20 k". */
export const parseCapinfosOutput = (stdout: string): CapinfosMetadata => {
const lines = new Map<string, string>();
for (const line of stdout.split(/\r?\n/u)) {
const at = line.indexOf(":");
if (at >= 0 && !/^\s/u.test(line))
lines.set(line.slice(0, at), line.slice(at + 1).trim());
}
const fileType = lines.get("File type");
const encapsulation = lines.get("File encapsulation");
const countText = lines.get("Number of packets");
if (
!fileType ||
!encapsulation ||
countText === undefined ||
!/^\d+$/u.test(countText)
)
return protocolFailure(
"capinfos did not provide machine-readable type, encapsulation and packet count",
);
const packetCount = Number(countText);
if (!Number.isSafeInteger(packetCount))
return protocolFailure("packet count is not representable");
const durationText = lines.get("Capture duration");
const duration =
durationText === undefined
? null
: /^(\d+(?:\.\d+)?)(?:\s+seconds?)?$/u.exec(durationText);
const snapshot = /^file hdr:\s*(\d+) bytes$/u.exec(
lines.get("Packet size limit") ?? "",
);
const snapshotLength = snapshot === null ? null : Number(snapshot[1]);
const sha256 = lines.get("SHA256") ?? null;
if (sha256 !== null && !/^[0-9a-f]{64}$/u.test(sha256))
return protocolFailure("capinfos SHA256 is malformed");
return {
fileType,
encapsulation,
packetCount,
captureStart: lines.get("Earliest packet time") ?? null,
captureEnd: lines.get("Latest packet time") ?? null,
captureDurationSeconds: duration === null ? null : Number(duration[1]),
snapshotLength:
snapshotLength !== null &&
Number.isSafeInteger(snapshotLength) &&
snapshotLength > 0
? snapshotLength
: null,
sha256,
};
};
export interface TsharkFields {
readonly endpoints: { address: string; port: null; packet_count: number }[];
readonly endpointCount: number;
readonly dnsQueries: {
query: string;
response_addresses: string[];
response_address_count: number;
}[];
readonly dnsQueryCount: number;
readonly tlsSniValues: string[];
readonly tlsSniCount: number;
readonly protocolDistribution: { protocol: string; packet_count: number }[];
readonly protocolCount: number;
readonly httpRequestUris: string[];
readonly httpRequestUriCount: number;
readonly httpUriRedactionCount: number;
readonly unattributedDnsAddresses: string[];
readonly unattributedDnsAddressCount: number;
readonly unattributedDnsPackets: number;
readonly packetCount: number;
readonly partial: boolean;
}
const object = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Validate the fixed JSON field representation before retaining aggregate facts. */
export const parseTsharkJsonOutput = async (
stdout: string,
signal?: AbortSignal,
): Promise<TsharkFields> => {
signal?.throwIfAborted();
if (Buffer.byteLength(stdout) > TSHARK_JSON_MAX_BYTES)
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
"tshark JSON exceeds the bounded decoding budget",
{ max_json_bytes: TSHARK_JSON_MAX_BYTES },
);
// The selected-field protocol has five container levels. Reject deeper
// graphs before materializing them; quoted brackets are string data.
let depth = 0,
quoted = false,
escaped = false;
let decodedBytes = stdout.length * 2;
for (let index = 0; index < stdout.length; index += 1) {
if (index % 65536 === 0) {
await yieldToEventLoop();
signal?.throwIfAborted();
}
const char = stdout[index];
if (quoted) {
if (escaped) escaped = false;
else if (char === "\\") escaped = true;
else if (char === '"') quoted = false;
} else if (char === '"') {
quoted = true;
decodedBytes += 64;
} else if (char === "{" || char === "[") {
decodedBytes += 128;
if (++depth > 5) protocolFailure("unexpected JSON nesting");
} else if (char === "}" || char === "]") depth -= 1;
else if (char === ":" || char === ",") decodedBytes += 128;
if (decodedBytes > MAX_DECODED_BYTES)
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
"tshark JSON expansion exceeds the decoding budget",
{ max_decoded_bytes: MAX_DECODED_BYTES },
);
}
let packets: unknown;
try {
packets = JSON.parse(stdout) as unknown;
} catch (cause) {
throw new AnalysisProtocolError("tshark emitted malformed JSON", { cause });
}
if (!Array.isArray(packets))
return protocolFailure("tshark packet root must be an array");
const endpoints = new Map<string, number>();
const dns = new Map<string, Set<string>>();
const sni = new Set<string>();
const protocols = new Map<string, number>();
const uris = new Set<string>();
const observedUris = new Set<string>();
let uriRedactions = 0;
const unattributed = new Set<string>();
let unattributedPackets = 0;
let retainedBytes = 0;
const charge = (value: string): void => {
retainedBytes += 192 + 2 * Buffer.byteLength(value);
if (retainedBytes > MAX_RETAINED_BYTES)
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
"Packet inventory exceeds the retained-fact budget",
{ max_retained_bytes: MAX_RETAINED_BYTES },
);
};
const add = (set: Set<string>, value: string): void => {
if (!set.has(value)) {
charge(value);
set.add(value);
}
};
for (let index = 0; index < packets.length; index += 1) {
if (index % 256 === 0) {
await yieldToEventLoop();
signal?.throwIfAborted();
}
const packet: unknown = packets[index];
if (
!object(packet) ||
!object(packet._source) ||
!object(packet._source.layers)
)
return protocolFailure(
`packet ${String(index + 1)} lacks _source.layers`,
);
const layers = packet._source.layers;
for (const [key, value] of Object.entries(layers))
if (
!Array.isArray(value) ||
!value.every((item) => typeof item === "string")
)
return protocolFailure(
`packet ${String(index + 1)} field ${key} must be an array of strings`,
);
const field = (name: string): readonly string[] =>
(layers[name] as string[] | undefined) ?? [];
const frame = field("frame.number");
if (
frame.length !== 1 ||
!/^\d+$/u.test(frame[0]!) ||
Number(frame[0]) !== index + 1
)
return protocolFailure(
"frame inventory is missing, duplicated or out of order",
);
if (
field("frame.protocols").length !== 1 ||
field("frame.protocols")[0] === ""
)
return protocolFailure(
"packet protocol inventory is missing or ambiguous",
);
// Count one occurrence per packet even for loopback or nested IP layers.
for (const address of new Set([
...field("ip.src"),
...field("ip.dst"),
...field("ipv6.src"),
...field("ipv6.dst"),
])) {
if (address === "") continue;
if (!endpoints.has(address)) charge(address);
endpoints.set(address, (endpoints.get(address) ?? 0) + 1);
}
const questions = new Set(
field("dns.qry.name").filter((value) => value !== ""),
);
for (const question of questions)
if (!dns.has(question)) {
charge(question);
dns.set(question, new Set());
}
const addresses = [...field("dns.a"), ...field("dns.aaaa")].filter(
(value) => value !== "",
);
const response = field("dns.flags.response");
if (addresses.length > 0) {
if (
questions.size === 1 &&
response.length > 0 &&
response.every((value) => value === "True" || value === "1")
) {
const values = dns.get(questions.values().next().value!)!;
for (const address of addresses) add(values, address);
} else {
unattributedPackets += 1;
for (const address of addresses) add(unattributed, address);
}
}
for (const value of field("tls.handshake.extensions_server_name"))
if (value !== "") add(sni, value);
for (const value of new Set(field("frame.protocols"))) {
if (value === "") continue;
if (!protocols.has(value)) charge(value);
protocols.set(value, (protocols.get(value) ?? 0) + 1);
}
for (const value of field("http.request.full_uri")) {
if (value === "" || observedUris.has(value)) continue;
add(observedUris, value);
const { credentials } = parseRecordedTransportUrl(value);
if (credentials !== null) uriRedactions += 1;
if (credentials === "ambiguous") continue;
add(
uris,
credentials === null
? value
: value.slice(0, credentials.start) + value.slice(credentials.end),
);
}
}
signal?.throwIfAborted();
return {
endpoints: [...endpoints]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([address, packet_count]) => ({
address,
port: null,
packet_count,
})),
endpointCount: endpoints.size,
dnsQueries: [...dns].map(([query, addresses]) => ({
query,
response_addresses: [...addresses],
response_address_count: addresses.size,
})),
dnsQueryCount: dns.size,
tlsSniValues: [...sni],
tlsSniCount: sni.size,
protocolDistribution: [...protocols]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
protocolCount: protocols.size,
httpRequestUris: [...uris],
httpRequestUriCount: observedUris.size,
httpUriRedactionCount: uriRedactions,
unattributedDnsAddresses: [...unattributed],
unattributedDnsAddressCount: unattributed.size,
unattributedDnsPackets: unattributedPackets,
packetCount: packets.length,
partial: observedUris.size > uris.size || unattributedPackets > 0,
};
};
+491
View File
@@ -0,0 +1,491 @@
import type {
ExecutionOptions,
ProviderAvailability,
} from "../application/AnalysisProvider.js";
import {
createAnalysisExecution,
type AnalysisExecution,
} from "../application/AnalysisProvider.js";
import {
pcapResultSchemas,
type PcapRequest,
type PcapOperation,
} from "../domain/pcap/pcapAnalysis.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import {
PcapConfigurationFailure,
inspectPcapClient,
resolvePcapTools,
pcapConfigurationAvailability,
pcapToolUnavailable,
type PcapToolSelection,
} from "./PcapConfiguration.js";
import {
parseCapinfosOutput,
parseTsharkJsonOutput,
TSHARK_JSON_MAX_BYTES,
} from "./PcapOutput.js";
import { runPcapCommand, type PcapCommandLimits } from "./PcapCommand.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { createPcapEvidence } from "../domain/pcap/pcapEvidence.js";
import { preparePcapNativeBound } from "./PcapNativeBound.js";
import { PcapSnapshot } from "./PcapSnapshot.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
import { readLinuxResourceLimits } from "../process/LinuxResourceLimits.js";
export const PCAP_PROVIDER_IDENTITY = {
id: "pcap",
name: "Packet capture analysis",
version: null,
} as const;
const FIELDS = [
"frame.number",
"frame.protocols",
"ip.src",
"ip.dst",
"ipv6.src",
"ipv6.dst",
"dns.flags.response",
"dns.qry.name",
"dns.a",
"dns.aaaa",
"tls.handshake.extensions_server_name",
"http.request.full_uri",
];
export interface PcapProviderOptions {
readonly environment?: Readonly<Record<string, string | undefined>>;
}
/** Inspect saved captures through bounded, owned tool processes and one stable input copy. */
export class PcapProvider {
readonly #resources = new ArtifactAnalysisResources(
"pcap",
"inspect_pcap_capture",
readStableArtifact,
readLinuxResourceLimits,
{
message: "A packet summary is already active; retry after it completes.",
details: { max_concurrent_inspections: 1 },
},
);
private readonly environment: Readonly<Record<string, string | undefined>>;
private readonly snapshots = new Set<PcapSnapshot>();
private readonly commands = new Map<
ProviderProcessSupervisor,
{ snapshot: PcapSnapshot | undefined; resources: readonly string[] }
>();
constructor(options: PcapProviderOptions = {}) {
this.environment = options.environment ?? process.env;
}
private run(
operation: PcapOperation,
command: string,
args: readonly string[],
limits: PcapCommandLimits,
signal: AbortSignal | undefined,
snapshot?: PcapSnapshot,
inputPath?: string,
) {
return runPcapCommand({
operation,
command,
arguments: args,
limits,
signal,
environment:
snapshot === undefined
? this.environment
: {
...this.environment,
WIRESHARK_CONFIG_DIR: snapshot.configurationPath,
},
...(inputPath === undefined ? {} : { inputPath }),
...(inputPath === undefined || this.nativeBound === undefined
? {}
: { nativeBound: this.nativeBound }),
retain: (owner, resources) => {
this.commands.set(owner, { snapshot, resources });
},
});
}
private nativeBound: Parameters<typeof runPcapCommand>[0]["nativeBound"];
private nativeLimitations: readonly string[] = [];
private async prepareCaptureBound(): Promise<void> {
const prepared = await preparePcapNativeBound(
this.environment,
this.#resources,
);
this.nativeBound = prepared.nativeBound;
this.nativeLimitations = prepared.limitations;
}
private async client(operation: PcapOperation, signal?: AbortSignal) {
const selection = resolvePcapTools(this.environment);
const identity = await inspectPcapClient(
selection,
async (command) =>
(
await this.run(
operation,
command,
["--version"],
{ timeoutMs: 20_000, maxOutputBytes: 64 * 1024 },
signal,
)
).stdout,
);
for (const [name, version] of [
["tshark", identity.tsharkVersion],
["capinfos", identity.capinfosVersion],
] as const) {
if (version === null)
throw new PcapConfigurationFailure(
`${name}_version_unresolved`,
`The selected ${name} command did not report a version. Set REA_${name.toUpperCase()}_COMMAND to its absolute executable path.`,
);
}
return {
selection,
client: {
tshark_command: selection.tshark.command,
tshark_source: selection.tshark.source,
tshark_version: identity.tsharkVersion,
capinfos_command: selection.capinfos.command,
capinfos_source: selection.capinfos.source,
capinfos_version: identity.capinfosVersion,
},
};
}
async inspectAvailability(
signal?: AbortSignal,
): Promise<ProviderAvailability> {
const result = await this.#resources.run(
async () => ok(await this.inspectAvailabilityAdmitted(signal)),
signal,
);
if (!result.ok) throw result.error;
return result.value;
}
private async inspectAvailabilityAdmitted(
signal?: AbortSignal,
): Promise<ProviderAvailability> {
try {
const { client } = await this.client("inspect_pcap_client", signal);
if (process.platform !== "linux" && process.platform !== "win32")
return {
status: "unavailable",
code: "unsupported_host",
reason:
"No enforceable native memory boundary is available for capture summaries on this host.",
diagnostics: client,
};
await this.prepareCaptureBound();
return {
status: "available",
code: null,
reason: null,
diagnostics: client,
};
} catch (cause) {
if (signal?.aborted || cause instanceof AnalysisCancelledError)
throw new AnalysisCancelledError("inspect_pcap_client", { cause });
if (cause instanceof PcapConfigurationFailure)
return pcapConfigurationAvailability(cause);
return {
status: "unavailable",
code:
cause instanceof AnalysisCapabilityUnavailableError
? "executable_missing"
: "version_unresolved",
reason: cause instanceof Error ? cause.message : String(cause),
diagnostics: {},
};
}
}
private async discard(
snapshot: PcapSnapshot,
): Promise<AnalysisError | undefined> {
try {
if (
[...this.commands.values()].some(
(command) => command.snapshot === snapshot,
)
)
throw new Error(
"An unreleased command still owns the capture snapshot",
);
await snapshot.close();
this.snapshots.delete(snapshot);
return undefined;
} catch (cause) {
return new ProviderCleanupError(
"pcap",
[snapshot.path],
{ reason: String(cause) },
{ operation: "inspect_pcap_capture", cause },
);
}
}
async close(): Promise<void> {
const failures: unknown[] = [];
try {
await this.#resources.close();
} catch (cause) {
failures.push(cause);
}
for (const owner of this.commands.keys()) {
try {
const result = await owner.stop();
if (result.status === "incomplete") failures.push(result.reason);
else if (result.status === "not-owned")
failures.push("Command ownership remains unresolved");
else this.commands.delete(owner);
} catch (cause) {
failures.push(cause);
}
}
for (const snapshot of this.snapshots) {
const failure = await this.discard(snapshot);
if (failure !== undefined) failures.push(failure);
}
if (failures.length > 0)
throw new ProviderCleanupError(
"pcap",
[...this.snapshots]
.map((snapshot) => snapshot.path)
.concat(
[...this.commands.values()].flatMap((command) => command.resources),
),
{ reason: "Owned process or snapshot cleanup failed" },
{ operation: "pcap.close", cause: new AggregateError(failures) },
);
}
async execute(
request: PcapRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
return this.#resources.run(
() => this.executeAdmitted(request, options),
options?.signal,
);
}
private async executeAdmitted(
request: PcapRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const signal = options?.signal;
let snapshot: PcapSnapshot | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
signal?.throwIfAborted();
const { selection, client } = await this.client(
request.operation,
signal,
);
const provider = {
...PCAP_PROVIDER_IDENTITY,
version: client.tshark_version,
};
if (request.operation === "inspect_pcap_client")
result = ok(
createAnalysisExecution(
pcapResultSchemas.inspect_pcap_client.parse({ client }),
provider,
),
);
else {
await this.prepareCaptureBound();
snapshot = await PcapSnapshot.create();
this.snapshots.add(snapshot);
const identity = await snapshot.capture(request.input.path, signal);
const captured = await this.inspectCapture(
selection,
snapshot,
request.input.path,
identity,
signal,
);
const data = pcapResultSchemas.inspect_pcap_capture.parse({
client,
...captured.result,
});
result = ok(
createAnalysisExecution(data, provider, {
subject: {
path: request.input.path,
format: "file",
sha256: identity.sha256,
},
limitations: captured.limitations,
}),
);
}
} catch (cause) {
result = err(
cause instanceof AnalysisError
? cause
: signal?.aborted
? new AnalysisCancelledError(request.operation, { cause })
: cause instanceof PcapConfigurationFailure
? pcapToolUnavailable(request.operation, cause.message, {
cause,
})
: new AnalysisProtocolError(
`Packet-capture analysis failed: ${cause instanceof Error ? cause.message : String(cause)}`,
{ cause },
),
);
}
if (signal?.aborted && result.ok)
result = err(
new AnalysisCancelledError(request.operation, {
cause: signal.reason,
partialObservation: createPcapEvidence(request, result.value),
}),
);
if (snapshot !== undefined) {
const cleanup = await this.discard(snapshot);
if (signal?.aborted && result.ok)
result = err(
new AnalysisCancelledError(request.operation, {
cause: signal.reason,
partialObservation: createPcapEvidence(request, result.value),
}),
);
if (cleanup !== undefined)
result = result.ok
? err(
cleanup.retainPartialObservation(
createPcapEvidence(request, result.value),
),
)
: err(
analysisErrorWithCleanupFailure(
result.error,
cleanup,
request.operation,
),
);
}
return result;
}
private async inspectCapture(
selection: PcapToolSelection,
snapshot: PcapSnapshot,
path: string,
identity: { bytes: number; sha256: string },
signal: AbortSignal | undefined,
) {
const info = await this.run(
"inspect_pcap_capture",
selection.capinfos.command,
["-M", "--", snapshot.path],
{ timeoutMs: 60_000, maxOutputBytes: 64 * 1024 },
signal,
snapshot,
path,
);
const metadata = parseCapinfosOutput(info.stdout);
if (metadata.sha256 !== null && metadata.sha256 !== identity.sha256)
throw new AnalysisProtocolError(
"capinfos SHA256 disagrees with the owned capture snapshot",
);
const dissected = await this.run(
"inspect_pcap_capture",
selection.tshark.command,
[
"-n",
"-r",
snapshot.path,
"-T",
"json",
"--no-duplicate-keys",
`--temp-dir=${snapshot.configurationPath}`,
...FIELDS.flatMap((field) => ["-e", field]),
],
{ timeoutMs: 300_000, maxOutputBytes: TSHARK_JSON_MAX_BYTES },
signal,
snapshot,
path,
);
const fields = await parseTsharkJsonOutput(dissected.stdout, signal);
await snapshot.verify(identity, path, signal);
if (fields.packetCount !== metadata.packetCount)
throw new AnalysisProtocolError(
`capinfos counted ${String(metadata.packetCount)} packets but tshark returned ${String(fields.packetCount)}`,
);
return {
result: {
target: { path, ...identity },
file_type: metadata.fileType,
encapsulation: metadata.encapsulation,
packet_count: metadata.packetCount,
capture_start: metadata.captureStart,
capture_end: metadata.captureEnd,
capture_duration_seconds: metadata.captureDurationSeconds,
diagnostics: {
capinfos_stderr: info.stderr,
tshark_stderr: dissected.stderr,
},
snapshot_length: metadata.snapshotLength,
endpoints: fields.endpoints,
endpoint_count: fields.endpointCount,
dns_queries: fields.dnsQueries,
dns_query_count: fields.dnsQueryCount,
tls_sni_values: fields.tlsSniValues,
tls_sni_count: fields.tlsSniCount,
protocol_distribution: fields.protocolDistribution,
protocol_count: fields.protocolCount,
http_request_uris: fields.httpRequestUris,
http_request_uri_count: fields.httpRequestUriCount,
http_uri_redaction_count: fields.httpUriRedactionCount,
unattributed_dns_addresses: fields.unattributedDnsAddresses,
unattributed_dns_address_count: fields.unattributedDnsAddressCount,
unattributed_dns_packet_count: fields.unattributedDnsPackets,
coverage: fields.partial ? "partial" : "complete",
},
limitations: [
...this.nativeLimitations,
"Both tools read one owned snapshot; target identity comes from its admitted source descriptor",
"DNS address values are associated only with a single question in the same response packet; values may include additional DNS records, not only final resolution answers",
"Only bytes present in the saved capture are examined; encryption and capture truncation can hide higher-level fields",
...(fields.partial
? [
"One or more projected categories were capped, credential-bearing URIs were omitted or coalesced, or DNS address attribution remains unresolved; counts retain the examined totals",
]
: []),
...(fields.httpUriRedactionCount > 0
? [
"HTTP transport credentials were excluded; ambiguous credential spans cause the URI to be omitted",
]
: []),
...(fields.unattributedDnsPackets > 0
? [
`DNS address attribution was unresolved in ${String(fields.unattributedDnsPackets)} packet(s); unattributed addresses are retained separately`,
]
: []),
],
};
}
}
+269
View File
@@ -0,0 +1,269 @@
import { createHash } from "node:crypto";
import { chmod, open, stat, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
openRegularFile,
RegularFileAdmissionFailure,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRootUnavailableError.js";
const OPERATION = "inspect_pcap_capture";
const MAX_CAPTURE_BYTES = 2 * 1024 ** 3;
/** An owned capture copy and every descriptor needed to release it safely. */
export class PcapSnapshot {
private readonly handles = new Set<OwnedFileHandle>();
readonly path: string;
readonly configurationPath: string;
private constructor(private readonly root: PrivateRuntimeRoot) {
this.path = join(root.path, "capture.pcap");
this.configurationPath = join(root.path, "configuration");
}
static async create(): Promise<PcapSnapshot> {
try {
return new PcapSnapshot(
await PrivateRuntimeRoot.create({ prefix: "rea-pcap-" }),
);
} catch (cause) {
if (cause instanceof PrivateRuntimeRootUnavailableError)
throw new AnalysisCapabilityUnavailableError(
"pcap",
OPERATION,
cause.message,
{ cause, retryable: cause.retryable },
);
throw new AnalysisResourceConstraintError(
OPERATION,
"file-size",
"Cannot allocate the owned capture workspace",
null,
{ cause },
);
}
}
private own(handle: OwnedFileHandle): OwnedFileHandle {
this.handles.add(handle);
return handle;
}
private async release(handle: OwnedFileHandle): Promise<void> {
await handle.close();
this.handles.delete(handle);
}
async capture(
path: string,
signal?: AbortSignal,
): Promise<{ bytes: number; sha256: string }> {
const sourceRead = async <T>(read: () => Promise<T>): Promise<T> => {
try {
return await read();
} catch (cause) {
if (signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { cause });
if (cause instanceof AnalysisError) throw cause;
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
throw new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
throw new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Cannot read selected capture ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
},
]);
}
};
try {
signal?.throwIfAborted();
await mkdir(this.configurationPath, { mode: 0o700 });
const source = await sourceRead(async () => {
try {
return this.own(
new OwnedFileHandle(
await openRegularFile(path, { symlinks: "follow", signal }),
),
);
} catch (cause) {
if (cause instanceof RegularFileAdmissionFailure) {
this.own(cause.owner);
throw cause.cause;
}
throw cause;
}
});
const before = await sourceRead(() =>
source.handle.stat({ bigint: true }),
);
if (before.size > BigInt(MAX_CAPTURE_BYTES))
throw new AnalysisResourceConstraintError(
OPERATION,
"file-size",
"Capture exceeds the owned-snapshot disk budget",
{ max_capture_bytes: MAX_CAPTURE_BYTES },
);
const destination = this.own(
new OwnedFileHandle(await open(this.path, "wx", 0o600)),
);
const buffer = Buffer.alloc(64 * 1024);
const hash = createHash("sha256");
let copied = 0;
while (copied <= Number(before.size)) {
signal?.throwIfAborted();
const { bytesRead } = await sourceRead(() =>
source.handle.read(
buffer,
0,
Math.min(buffer.length, Number(before.size) - copied + 1),
copied,
),
);
signal?.throwIfAborted();
if (bytesRead === 0) break;
copied += bytesRead;
if (BigInt(copied) > before.size)
throw new AnalysisArtifactChangedError(
OPERATION,
path,
"Capture grew during acquisition",
);
const chunk = buffer.subarray(0, bytesRead);
await destination.handle.writeFile(chunk);
hash.update(chunk);
}
const after = await sourceRead(() =>
source.handle.stat({ bigint: true }),
);
const selected = await stat(path, { bigint: true }).catch(
(cause: unknown) => {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
throw new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
throw new AnalysisArtifactChangedError(
OPERATION,
path,
"Selected path became unavailable during acquisition",
{ cause },
);
},
);
if (
BigInt(copied) !== before.size ||
!sameRegularFileState(before, after) ||
!sameRegularFileState(before, selected)
)
throw new AnalysisArtifactChangedError(
OPERATION,
path,
"Capture identity or contents changed during acquisition",
);
await this.release(source);
await this.release(destination);
await chmod(this.path, 0o400);
signal?.throwIfAborted();
return { bytes: copied, sha256: hash.digest("hex") };
} catch (cause) {
if (signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { cause });
if (cause instanceof AnalysisError) throw cause;
throw new AnalysisResourceConstraintError(
OPERATION,
"file-size",
"Owned capture snapshot I/O failed",
null,
{ cause },
);
}
}
/** Recheck byte identity after both tools; a read-only mode alone is not proof. */
async verify(
expected: { bytes: number; sha256: string },
selectedPath: string,
signal?: AbortSignal,
): Promise<void> {
try {
const file = this.own(
new OwnedFileHandle(
await openRegularFile(this.path, { symlinks: "reject", signal }),
),
);
const before = await file.handle.stat({ bigint: true });
const buffer = Buffer.alloc(64 * 1024);
const hash = createHash("sha256");
let bytes = 0;
while (bytes <= expected.bytes) {
signal?.throwIfAborted();
const read = await file.handle.read(
buffer,
0,
Math.min(buffer.length, expected.bytes - bytes + 1),
bytes,
);
if (read.bytesRead === 0) break;
bytes += read.bytesRead;
hash.update(buffer.subarray(0, read.bytesRead));
}
const after = await file.handle.stat({ bigint: true });
const selected = await stat(this.path, { bigint: true });
if (
bytes !== expected.bytes ||
hash.digest("hex") !== expected.sha256 ||
!sameRegularFileState(before, after) ||
!sameRegularFileState(before, selected)
)
throw new AnalysisArtifactChangedError(
OPERATION,
selectedPath,
"Owned packet snapshot changed during tool analysis.",
);
await this.release(file);
} catch (cause) {
if (signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { cause });
if (cause instanceof RegularFileAdmissionFailure) this.own(cause.owner);
if (cause instanceof AnalysisError) throw cause;
throw new AnalysisArtifactChangedError(
OPERATION,
selectedPath,
"Cannot establish the owned packet snapshot's post-analysis identity.",
{ cause },
);
}
}
async close(): Promise<void> {
const results = await Promise.allSettled(
[...this.handles].map((handle) => this.release(handle)),
);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason as unknown] : [],
);
if (failures.length > 0)
throw new AggregateError(failures, "Capture descriptor cleanup failed");
await this.root.close();
}
}
+4 -2
View File
@@ -74,7 +74,9 @@ const sourceFiles = [
export const SWIFTC_INTERRUPT = "SIGINT";
/** Deadline for the one-shot helper compilation. */
const COMPILER_TIMEOUT_MS = 60_000;
// A fresh Swift SDK cache took 88 seconds on the supported Intel macOS VM.
// Keep compilation bounded independently of short provider version probes.
const COMPILER_TIMEOUT_MS = 120_000;
/** Bound on compiler diagnostics embedded in the inspection failure text. */
const STDERR_EXCERPT_LIMIT = 512;
@@ -253,7 +255,7 @@ export type DarwinProcessReaderCompiler =
export const createDarwinProcessRunTokenReader = (
options: {
readonly compiler?: DarwinProcessReaderCompiler;
/** Deadline for the helper compilation; the default keeps verification fast. */
/** Deadline for helper compilation, independent of provider execution. */
readonly compileTimeoutMs?: number;
/**
* Caller-owned directory holding the compiler's module cache. Unset keeps
+15
View File
@@ -84,6 +84,7 @@ import type { FirmwareAnalysisPort } from "../application/firmware/FirmwareAnaly
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
import { registerAndroidTools } from "./registerAndroidTools.js";
import { registerApktoolTools } from "./registerApktoolTools.js";
import { registerPcapTools } from "./registerPcapTools.js";
import { registerFlutterTools } from "./registerFlutterTools.js";
import { registerJebTools } from "./registerJebTools.js";
import { registerAdbTools } from "./registerAdbTools.js";
@@ -91,11 +92,14 @@ import { AndroidAnalysisService } from "../application/android/AndroidAnalysisSe
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
import type { ApktoolResourceAnalysisPort } from "../application/apktool/ApktoolResourceAnalysisPort.js";
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import { ApktoolResourceAnalysisService } from "../application/apktool/ApktoolResourceAnalysisService.js";
import type { FlutterBuildAnalysisPort } from "../application/flutter/FlutterBuildAnalysisPort.js";
import { FlutterBuildAnalysisService } from "../application/flutter/FlutterBuildAnalysisService.js";
import { createAndroidAnalysisProvider } from "../composition/android.js";
import { createApktoolResourceAnalysisProvider } from "../composition/apktool.js";
import { createPcapAnalysisProvider } from "../composition/pcap.js";
import { createFlutterBuildAnalysisProvider } from "../composition/flutter.js";
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
import { createJebAnalysisProvider } from "../composition/jeb.js";
@@ -146,6 +150,7 @@ export interface CreateServerOptions {
readonly webNetworkCapture?: WebNetworkCaptureService;
readonly androidAnalysis?: AndroidAnalysisPort;
readonly apktoolAnalysis?: ApktoolResourceAnalysisPort;
readonly pcapAnalysis?: PcapAnalysisPort;
readonly flutterAnalysis?: FlutterBuildAnalysisPort;
readonly jebAnalysis?: JebAnalysisPort;
readonly adbDeviceAnalysis?: AdbDeviceAnalysisPort;
@@ -303,6 +308,7 @@ export const createServer = (
);
const android =
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
const pcap = options.pcapAnalysis ?? createPcapAnalysisProvider(environment);
const flutter =
options.flutterAnalysis ?? createFlutterBuildAnalysisProvider();
const fridaInstrumentation =
@@ -333,6 +339,7 @@ export const createServer = (
jeb.close(),
adbDevice.close(),
flutter.close(),
pcap.close(),
evmInterface.close(),
sqliteDatabase.close(),
binaryLayout.close(),
@@ -438,6 +445,14 @@ export const createServer = (
recordEvidence,
analysisAdmission,
);
registerPcapTools(
server,
new PcapAnalysisService(pcap),
toolLogger,
recordEvidence,
analysisAdmission,
evidenceById,
);
registerFlutterTools(
server,
new FlutterBuildAnalysisService(flutter),
+83
View File
@@ -0,0 +1,83 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import type { Logger } from "pino";
import {
createContractToolHandler,
createEvidenceToolHandler,
} from "./contractToolHandler.js";
import {
toolRegistrationOptions,
applicationValidatedInputSchema,
} from "./toolRegistrationOptions.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { err } from "../domain/result.js";
/** Bind pcap handlers to their exact named contracts through admission. */
export const registerPcapTools = (
server: EvidenceMcpServer,
service: PcapAnalysisService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
evidenceById?: EvidenceLookup,
): void => {
const handler = createContractToolHandler(
server,
service,
logger,
recordEvidence,
withAdmittedAnalysis,
);
const clientContract = toolContract("inspect_pcap_client");
server.registerTool(
clientContract.name,
toolRegistrationOptions(clientContract),
handler(clientContract),
);
const contract = toolContract("inspect_pcap_capture");
const registration = toolRegistrationOptions(contract);
const capture = createEvidenceToolHandler(
server,
async (rawInput, options) => {
const parsed = contract.inputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
contract.name,
parsed.error.issues,
rawInput,
{ cause: parsed.error },
),
);
const { detail, ...input } = parsed.data;
const retention = { recordEvidence, evidenceById };
if (detail === "summary") {
const ready = requireAnalysisViewRetention(contract.name, retention);
if (!ready.ok) return ready;
}
const result = await service.execute(contract.name, input, options);
return detail === "summary" && result.ok
? summarizeRetainedAnalysis(result.value, retention)
: result;
},
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
{
...registration,
inputSchema: applicationValidatedInputSchema(registration.inputSchema),
},
capture(contract),
);
};
+7 -7
View File
@@ -2,12 +2,12 @@ import { randomUUID, createHash } from "node:crypto";
import { access, realpath, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../application/AnalysisProvider.js";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
import type { WasmArtifactPort } from "../application/wasm/WasmArtifactPort.js";
import type {
WasmArtifactExecution,
WasmArtifactPort,
} from "../application/wasm/WasmArtifactPort.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import type {
AnalysisError,
@@ -76,10 +76,10 @@ export class WabtArtifactProvider implements WasmArtifactPort {
async inspect(
input: InspectWasmArtifactInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
): Promise<Result<WasmArtifactExecution, AnalysisError>> {
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let phase: "configuration" | "artifact" | "producer" = "configuration";
let result: Result<AnalysisExecution, AnalysisError>;
let result: Result<WasmArtifactExecution, AnalysisError>;
let capturedOutput: AnalysisCapturedOutput | undefined;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);