Merge remote-tracking branch 'origin/main' into fix/ida-native-verification-oracles

This commit is contained in:
N0zoM1z0
2026-10-13 08:17:06 +08:00
351 changed files with 19764 additions and 1714 deletions
+42 -13
View File
@@ -23,9 +23,11 @@ import {
type AnalysisExecution,
} from "../application/AnalysisProvider.js";
import type {
AdbActivityStartPartialObservation,
AdbAcquiredFilePartialObservation,
AdbRequest,
} from "../domain/adb/adbDeviceAnalysis.js";
import { adbResultSchemas } from "../domain/adb/adbDeviceAnalysis.js";
import {
AnalysisArtifactChangedError,
AnalysisCancelledError,
@@ -1985,28 +1987,55 @@ export class AdbProvider {
signal,
);
if (!started.ok) return started;
const verdict = parseAmStartOutput(started.value.stdout);
if (verdict.status === "refused")
const verdict = parseAmStartOutput(
started.value.stdout,
started.value.stderr,
);
const result = {
...resultFields,
started_activity: verdict.startedActivity,
reported_activity: verdict.activity,
reported_status: verdict.reportedStatus,
};
if (verdict.status === "refused") {
const partialObservation: AdbActivityStartPartialObservation =
operation === "start_adb_app"
? {
provider_id: "adb",
operation,
result: adbResultSchemas.start_adb_app.parse(result),
}
: {
provider_id: "adb",
operation,
result: adbResultSchemas.start_adb_activity.parse(result),
};
return err(
new AnalysisUnsupportedTargetError(
operation,
serial,
verdict.reason ?? "am start refused the intent",
{
capturedOutput: {
stdout: started.value.stdout,
stderr: started.value.stderr,
truncated: false,
},
partialObservation,
},
),
);
}
return ok(
createAnalysisExecution(
{
...resultFields,
started_activity: verdict.startedActivity,
createAnalysisExecution(result, provider, {
rawResult: {
stdout: started.value.stdout,
stderr: started.value.stderr,
},
provider,
{
limitations: [
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
],
},
) as AnalysisExecution,
limitations: [
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
],
}) as AnalysisExecution,
);
}
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from "vitest";
import { parseAmStartOutput } from "./AdbShellOutput.js";
const starting =
"Starting: Intent { act=android.intent.action.MAIN cmp=com.example/.Main }";
describe("parseAmStartOutput", () => {
it("recognizes a CRLF wait-timeout report", () => {
expect(
parseAmStartOutput(
`${starting}\r\nStatus: timeout\r\nActivity: com.example/.Main\r\nComplete\r\n`,
),
).toMatchObject({
status: "refused",
activity: "com.example/.Main",
reportedStatus: "timeout",
reason: "am start reported status: timeout",
});
});
it("treats every non-ok status as refusal, including a later status after ok", () => {
expect(
parseAmStartOutput(`${starting}\nStatus: ok\nStatus: timeout\n`),
).toMatchObject({
status: "refused",
reportedStatus: "timeout",
reason: "am start reported status: timeout",
});
expect(
parseAmStartOutput(`${starting}\nStatus: future-value\n`),
).toMatchObject({
status: "refused",
reportedStatus: "future-value",
});
});
it("gives hard errors in either stream priority over status and attempt", () => {
expect(
parseAmStartOutput(
`${starting}\nStatus: timeout\nActivity: com.example/.Main\n`,
"Exception: Activity class does not exist\n",
),
).toEqual({
status: "refused",
startedActivity: "act=android.intent.action.MAIN cmp=com.example/.Main",
activity: "com.example/.Main",
reportedStatus: "timeout",
reason: "Activity class does not exist",
});
expect(
parseAmStartOutput(
`${starting}\nStatus: ok\nError: Activity class does not exist\n`,
),
).toMatchObject({
status: "refused",
reason: "Activity class does not exist",
});
});
it("keeps Starting-only output compatible and refuses no-attempt output", () => {
expect(parseAmStartOutput(starting)).toMatchObject({
status: "started",
reportedStatus: null,
activity: null,
});
expect(
parseAmStartOutput("Status: ok\nWarning: Activity not started\n"),
).toMatchObject({
status: "refused",
startedActivity: null,
reportedStatus: "ok",
});
});
});
+63 -15
View File
@@ -320,32 +320,80 @@ export const parseResolveActivityOutput = (stdout: string): string | null => {
return lines.length === 0 ? null : lines[lines.length - 1]!;
};
/** Parsed facts and verdict from the full `am start -W` report. */
export interface AmStartOutput {
readonly status: "started" | "refused";
readonly startedActivity: string | null;
readonly activity: string | null;
readonly reportedStatus: string | null;
readonly reason: string | null;
}
/**
* Parse `am start` output. Success prints `Starting: Intent { ... }`;
* refusals print lines starting with `Error:` or `Warning:` and activity
* classes that do not exist name the component.
* Parse the complete `am start -W` report. `Starting:` records an attempt;
* hard errors and any non-ok Activity Manager status determine the verdict.
*/
export const parseAmStartOutput = (
stdout: string,
): {
readonly status: "started" | "refused";
readonly startedActivity: string | null;
readonly reason: string | null;
} => {
const text = stdout.trim();
const starting = /^Starting:\s+Intent\s*\{(.*)\}\s*$/mu.exec(text);
if (starting !== null)
stderr = "",
): AmStartOutput => {
const normalizedStdout = stdout.replaceAll("\r\n", "\n");
const starting = /^Starting:[ \t]+Intent[ \t]*\{(.*)\}[ \t]*$/mu.exec(
normalizedStdout,
);
const startedActivity = starting?.[1]?.trim() ?? null;
const activityMatch = /^Activity:[ \t]*(.*)$/mu.exec(normalizedStdout);
const activity = activityMatch?.[1]?.trim() || null;
const statuses = [...normalizedStdout.matchAll(/^Status:[ \t]*(.*)$/gmu)].map(
(match) => match[1]!.trim(),
);
const nonOkStatus = statuses.find((status) => status.toLowerCase() !== "ok");
const reportedStatus = nonOkStatus ?? statuses[0] ?? null;
const error = [normalizedStdout, stderr.replaceAll("\r\n", "\n")]
.flatMap((stream) => stream.split("\n"))
.map((line) => line.trim())
.map((line) => ({
line,
match: /^(?:Error|Exception)(?::|\b)(.*)$/iu.exec(line),
}))
.find(({ match }) => match !== null);
const errorReason = error?.match?.[1]?.trim() || error?.line || null;
const statusReason =
nonOkStatus === ""
? "am start reported an empty status"
: nonOkStatus === undefined
? null
: `am start reported status: ${nonOkStatus}`;
const reason =
errorReason ??
statusReason ??
(/^Warning:/mu.test(normalizedStdout.trim())
? normalizedStdout.trim().slice(0, 512)
: null);
if (errorReason !== null || nonOkStatus !== undefined)
return {
status: "refused",
startedActivity,
activity,
reportedStatus,
reason: reason ?? "am start did not report a successful launch",
};
if (startedActivity !== null)
return {
status: "started",
startedActivity: starting[1]!.trim(),
startedActivity,
activity,
reportedStatus,
reason: null,
};
const error = /^(?:Error|Warning|Exception)(?::|\b)(.*)$/mu.exec(text);
const text = `${normalizedStdout}\n${stderr.replaceAll("\r\n", "\n")}`.trim();
return {
status: "refused",
startedActivity: null,
startedActivity,
activity,
reportedStatus,
reason:
error?.[1]?.trim() ??
reason ??
(text === "" ? "am start returned no activity" : text.slice(0, 512)),
};
};
+5 -5
View File
@@ -12,6 +12,7 @@ import {
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
import { err, ok, type Result } from "../domain/result.js";
/** Decoded representation bound for one binary Info.plist. */
@@ -195,11 +196,10 @@ const resolveLayoutExecutable = async (
let name: string;
try {
name =
plist.subarray(0, 6).toString("ascii") === "bplist"
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
parseBinaryPlistExecutable(plist))
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
name = hasBinaryPlistSignature(plist)
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
parseBinaryPlistExecutable(plist))
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
} catch (cause: unknown) {
return err(
new BinaryTargetError(
+44 -10
View File
@@ -31,7 +31,8 @@ import {
rawBinarySelectionError,
} from "../domain/rawBinary.js";
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
import { observeMzWindowsHeader } from "../domain/dosMz.js";
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
import {
hasZipSignature,
isZipPackageFormat,
@@ -295,7 +296,7 @@ const detectArtifactFormat = async (
return zipPackageFormatForPath(lower) ?? "zip";
}
// Binary plists, including keyed archives, often use other extensions.
if (observed.bytesRead === 8 && magic.equals(Buffer.from("bplist00")))
if (hasBinaryPlistSignature(magic.subarray(0, observed.bytesRead)))
return "plist";
const named = namedArtifactFormat(lower);
if (named !== undefined) return named;
@@ -412,11 +413,31 @@ const readExecutableMetadata = async (
const fileSize = (await handle.stat()).size;
throwIfTargetResolutionCancelled(signal);
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
const offset = mzWindowsHeaderOffset(bytes);
if (offset !== null) {
if (offset < 64)
let windowsHeader = observeMzWindowsHeader(bytes, fileSize);
let signatureBytes: Buffer | undefined;
if (windowsHeader.state === "signature-needed") {
const { offset } = windowsHeader;
const signature = Buffer.alloc(Math.min(4, fileSize - offset));
const observedSignature = await handle.read(
signature,
0,
signature.length,
offset,
);
throwIfTargetResolutionCancelled(signal);
signatureBytes = signature.subarray(0, observedSignature.bytesRead);
windowsHeader = observeMzWindowsHeader(bytes, fileSize, signatureBytes);
}
if (windowsHeader.state === "declared") {
if (windowsHeader.offset < 64)
return err("invalid Windows new-header offset in MZ image");
return readPeMetadata(handle, offset, signal);
return readPeMetadata(
handle,
windowsHeader.offset,
bytes,
fileSize,
signal,
);
}
// MZ relocation records may extend past the initial probe; their format
// bounds are at most 65535 records inside a 65535-paragraph header.
@@ -439,7 +460,12 @@ const readExecutableMetadata = async (
fileSize,
);
}
return parseExecutableHeader(bytes, hostArchitecture, fileSize);
return parseExecutableHeader(
bytes,
hostArchitecture,
fileSize,
signatureBytes,
);
}
if (bytes.length >= 8) {
const magic = bytes.readUInt32BE(0);
@@ -490,6 +516,8 @@ const readExecutableMetadata = async (
const readPeMetadata = async (
handle: FileHandle,
offset: number,
mzPrefix: Buffer,
fileSize: number,
signal?: AbortSignal,
): Promise<Result<ExecutableMetadata, string>> => {
throwIfTargetResolutionCancelled(signal);
@@ -503,9 +531,15 @@ const readPeMetadata = async (
throwIfTargetResolutionCancelled(signal);
if (fileHeaderRead.bytesRead !== fileHeader.length)
return err("invalid or truncated PE header");
const signature = fileHeader.toString("ascii", 0, 2);
if (["NE", "LE", "LX"].includes(signature))
return err(`unsupported ${signature} executable in MZ image`);
const windowsHeader = observeMzWindowsHeader(
mzPrefix,
fileSize,
fileHeader.subarray(0, 4),
);
if (windowsHeader.state !== "declared")
return err("invalid Windows new-header signature in MZ image");
if (["NE", "LE", "LX"].includes(windowsHeader.signature))
return err(`unsupported ${windowsHeader.signature} executable in MZ image`);
const optionalHeaderSize = fileHeader.readUInt16LE(20);
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
const record = Buffer.alloc(24 + optionalHeaderSize);
+18
View File
@@ -43,6 +43,8 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly packetCaptureEnabled?: boolean;
readonly signalRecordingEnabled?: boolean;
readonly wasmArtifactEnabled?: boolean;
readonly evmInterfaceEnabled?: boolean;
readonly processCaptureEnabled: boolean;
@@ -395,6 +397,22 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (name === "inspect_packet_capture")
return policy.packetCaptureEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
};
if (name === "decode_signal_recording")
return policy.signalRecordingEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux, supply sigrok-cli 0.7.2 via absolute REA_SIGROK_COMMAND and util-linux prlimit (REA_SIGROK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
};
if (name === "inspect_wasm_artifact")
return policy.wasmArtifactEnabled === true
? { reason: "available", remediation: null }
+3
View File
@@ -21,6 +21,7 @@ import {
parseFunctionDossier,
parseListCount,
parseRelatedAddresses,
parseSegmentImageBase,
parseSegments,
} from "../domain/hopperValues.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -527,6 +528,7 @@ export class EnhancedTools {
const segments = parseSegments(segmentsResult.value);
if (!segments.ok) return segments;
const imageBase = parseSegmentImageBase(segmentsResult.value);
const procedureCount = parseListCount(proceduresResult.value, "procedures");
if (!procedureCount.ok) return procedureCount;
const stringCount = parseListCount(stringsResult.value, "strings");
@@ -543,6 +545,7 @@ export class EnhancedTools {
segment_count: segments.value.length,
procedure_count: procedureCount.value,
string_count: stringCount.value,
...(imageBase === undefined ? {} : { image_base: imageBase }),
});
}
+2 -10
View File
@@ -1,9 +1,9 @@
import { resolve } from "node:path";
import {
createImmutableEvidenceBundle,
describeEvidenceBundleFailure,
describeValidationFailure,
parseImmutableEvidenceBundle,
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
@@ -49,15 +49,7 @@ export const readImmutableEvidenceBundle = (
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
readBundle(
path,
(input) => {
const bundle = parseEvidenceBundle(input);
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
},
signal,
resources,
);
readBundle(path, parseImmutableEvidenceBundle, signal, resources);
const readBundle = async (
path: string,
+6 -4
View File
@@ -3,6 +3,7 @@ import type {
MipsAbiFlags,
MipsElfMetadata,
} from "../domain/binaryTargetTypes.js";
import { readElfFixedHeader } from "../domain/elfFixedHeader.js";
import { err, ok, type Result } from "../domain/result.js";
import {
readMipsElfSharedLoad,
@@ -64,21 +65,22 @@ export const readMipsElfMetadata = async (
const header = await read(0, 52, "ELF32 header");
if (!header.ok) return header;
const bytes = header.value;
const fixedHeader = readElfFixedHeader(bytes, fileSize);
if (!fixedHeader.ok) return fixedHeader;
const little = metadata.byteOrder === "little";
const u16 = (data: Buffer, offset: number): number =>
little ? data.readUInt16LE(offset) : data.readUInt16BE(offset);
const u32 = (data: Buffer, offset: number): number =>
little ? data.readUInt32LE(offset) : data.readUInt32BE(offset);
if (
bytes.toString("hex", 0, 4) !== "7f454c46" ||
bytes[4] !== 1 ||
bytes[5] !== (little ? 1 : 2) ||
fixedHeader.value.elfClass !== 32 ||
fixedHeader.value.byteOrder !== metadata.byteOrder ||
u16(bytes, 18) !== 8 ||
u16(bytes, 16) !== metadata.type ||
u32(bytes, 36) !== metadata.flags
)
return err("MIPS ELF header no longer matches the resolved identity");
if (bytes[6] !== 1 || u32(bytes, 20) !== 1 || u16(bytes, 40) !== 52)
if (fixedHeader.value.headerSize !== 52)
return err("invalid MIPS ELF32 version or header size");
const tables = [
@@ -109,12 +109,18 @@ const resolveInternalSpecifier = (
: { to: match, resolution: "internal" };
};
type ReadFile = Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>;
const appendFile = (
entry: Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>,
entry: ReadFile,
lookupPath: ReferenceSourcePathLookup,
output: ParsedReferenceSourceEntries,
): void => {
const language = detectReferenceSourceLanguage(entry.path);
const parsed =
language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language)
? undefined
: parseReferenceSourceImports(entry.path, entry.bytes, language);
output.entries.push({
path: entry.path,
kind: "file",
@@ -123,11 +129,9 @@ const appendFile = (
language,
classifications: classifyReferenceSourcePath(entry.path),
content_state: "hashed",
limitations: [],
limitations: [...(parsed?.limitations ?? [])],
});
if (language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
return;
const parsed = parseReferenceSourceImports(entry.path, entry.bytes, language);
if (parsed === undefined) return;
for (const relationship of parsed.relationships) {
if (relationship.resolution !== "internal") {
output.relationships.push(relationship);
+17 -11
View File
@@ -1,6 +1,6 @@
import fs from "node:fs";
import { lstat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { dirname, join, resolve } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
@@ -32,18 +32,24 @@ export const readReferenceSourceVcs = async (
): Promise<Result<ReferenceSourceVcsInfo, ReferenceSourceReaderError>> => {
try {
return await resources.run(async () => {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(root, ".git"));
} catch (cause: unknown) {
return ok(
errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: unknownVcs(),
);
// Like Git, a subdirectory belongs to its nearest enclosing repository;
// only a missing `.git` at every ancestor means no version control.
let repository = resolve(root);
for (;;) {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(repository, ".git"));
break;
} catch (cause: unknown) {
if (errorCode(cause) !== "ENOENT") return ok(unknownVcs());
}
const parent = dirname(repository);
if (parent === repository)
return ok({ kind: "none", head: null, dirty: null });
repository = parent;
}
try {
const head = await resolveSourceHead(root, resources, signal);
const head = await resolveSourceHead(repository, resources, signal);
if (isAborted(signal)) return ok(unknownVcs());
return ok({ kind: "git", head, dirty: null });
} catch (cause: unknown) {
+9 -11
View File
@@ -75,6 +75,10 @@ interface ClientDefinition {
) => NonNullable<SetupClient["geminiSettings"]>;
}
/** XDG treats an empty config-home value as unset. */
const xdgConfigHome = ({ home, env }: ClientPathContext): string =>
env.XDG_CONFIG_HOME || join(home, ".config");
const vscodeUserDirectory = ({
home,
platform,
@@ -88,7 +92,7 @@ const vscodeUserDirectory = ({
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Code", "User");
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Code", "User");
return join(xdgConfigHome({ home, platform, env }), "Code", "User");
};
const traeUserDirectory = ({
@@ -104,7 +108,7 @@ const traeUserDirectory = ({
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Trae", "User");
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Trae", "User");
return join(xdgConfigHome({ home, platform, env }), "Trae", "User");
};
const claudeDesktopDirectory = ({
@@ -115,7 +119,7 @@ const claudeDesktopDirectory = ({
if (platform === "win32")
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
if (platform === "linux")
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Claude");
return join(xdgConfigHome({ home, platform, env }), "Claude");
return join(home, "Library", "Application Support", "Claude");
};
@@ -268,19 +272,13 @@ const openCodeOverrideDirectory = (
const opencodeDirectory = (context: ClientPathContext): string =>
openCodeOverrideDirectory(context.env) ??
join(
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
"opencode",
);
join(xdgConfigHome(context), "opencode");
/** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */
const openCodeConfigurationPaths = (
context: ClientPathContext,
): readonly string[] => {
const directory = join(
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
"opencode",
);
const directory = join(xdgConfigHome(context), "opencode");
const overrideDirectory = openCodeOverrideDirectory(context.env);
const paths = [
join(directory, "config.json"),
@@ -19,6 +19,10 @@ import type {
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type {
UnknownPage,
UnknownQuery,
} from "../investigation/InvestigationRecordPort.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisExecution,
@@ -350,6 +354,10 @@ export abstract class BinarySessionRecords {
return this.#records.listUnknowns(filters);
}
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
return this.#records.listUnknownsPage(query);
}
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
@@ -0,0 +1,93 @@
import { isAbsolute } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
inspectPacketCaptureInputSchema,
packetCaptureSchema,
type InspectPacketCaptureInput,
} from "../../domain/captures/packetCapture.js";
import { err, ok, type Result } from "../../domain/result.js";
export interface PacketCapturePort {
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
close(): Promise<void>;
}
/** One shared validation and Evidence owner for CLI and MCP. */
export class PacketCaptureService {
constructor(readonly provider: PacketCapturePort) {}
close(): Promise<void> {
return this.provider.close();
}
async inspect(
raw: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "inspect_packet_capture";
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const input = inspectPacketCaptureInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute local path.",
},
]),
);
const decoded = await this.provider.inspect(input.data, options);
if (!decoded.ok) return decoded;
const execution = decoded.value;
const report = packetCaptureSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
)
return err(
new AnalysisOutputError(
operation,
"Capture analyzer returned malformed data or changed the selected artifact identity/options.",
),
);
const evidence = createEvidence(execution.subject, execution.provider, {
operation,
parameters: input.data,
result: report.data,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
});
return options?.signal?.aborted
? err(
new AnalysisCancelledError(operation, {
partialObservation: evidence,
}),
)
: ok(evidence);
}
}
@@ -26,6 +26,7 @@ import {
} from "../../domain/residualUnknown.js";
import { err, ok, type Result } from "../../domain/result.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import type { UnknownPage, UnknownQuery } from "./InvestigationRecordPort.js";
type EvidenceLedgerFailure = EvidenceIntegrityError;
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
@@ -326,18 +327,39 @@ export class EvidenceLedger {
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return [...this.#unknownHeads.values()]
return this.listUnknownsPage(filters).items;
}
/** Select a stable page of current heads before detaching record payloads. */
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
const offset = query.offset ?? 0;
const matching = [...this.#unknownHeads.values()]
.filter(
(unknown) =>
(filters.status === undefined || unknown.status === filters.status) &&
(filters.severity === undefined ||
unknown.severity === filters.severity) &&
(filters.domain === undefined || unknown.domain === filters.domain),
(query.status === undefined || unknown.status === query.status) &&
(query.severity === undefined ||
unknown.severity === query.severity) &&
(query.domain === undefined || unknown.domain === query.domain),
)
.sort((left, right) =>
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
)
.map((unknown) => structuredClone(unknown));
);
const start = Math.min(offset, matching.length);
const end =
query.limit === undefined
? undefined
: start + Math.min(query.limit, matching.length - start);
const page = matching.slice(start, end);
const nextOffset =
offset <= matching.length && start + page.length < matching.length
? start + page.length
: null;
return {
items: page.map((unknown) => structuredClone(unknown)),
total: matching.length,
offset,
next_offset: nextOffset,
};
}
/** Return current resolution validity; imported invalid states are rejected. */
@@ -38,6 +38,21 @@ export interface EvidenceUnknownWriter {
): Result<ResidualUnknown | null, AnalysisError>;
}
export type UnknownPage = {
readonly items: ResidualUnknown[];
readonly total: number;
readonly offset: number;
readonly next_offset: number | null;
};
export interface UnknownQuery {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
readonly offset?: number;
readonly limit?: number;
}
/** Optimistic Unknown revisions and consistency verification. */
export interface UnknownRegistryPort {
recordUnknown(
@@ -51,6 +66,7 @@ export interface UnknownRegistryPort {
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[];
listUnknownsPage(query?: UnknownQuery): UnknownPage;
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
@@ -19,6 +19,8 @@ import type {
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort,
UnknownPage,
UnknownQuery,
} from "./InvestigationRecordPort.js";
/** One investigation's validated record owner, independent of binary execution. */
@@ -124,6 +126,10 @@ export class InvestigationRecords
return this.#evidence.listUnknowns(filters);
}
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
return this.#evidence.listUnknownsPage(query);
}
/** Verify registry consistency without asserting the answer is true. */
verifyUnknownResolution(unknownId: string): Result<
{
@@ -1,18 +1,11 @@
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import type { ProviderIdentity } from "../AnalysisProvider.js";
import type { CanonicalElectronActiveObservationInput } from "./ElectronActiveObservationPort.js";
import type { Evidence, EvidenceObservation } from "../../domain/evidence.js";
import { createEvidence } from "../../domain/evidence.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../../domain/javascript/electronActiveObservation.js";
import type { ElectronActiveObservationResult } from "../../domain/javascript/electronActiveObservation.js";
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
readonly application_root: string;
};
/** Commit the selected Electron experiment and its observed result. */
export const createElectronActiveEvidence = (
input: CanonicalElectronActiveObservationInput,
@@ -9,11 +9,15 @@ import type {
} from "../../domain/javascript/electronActiveObservation.js";
import type { Result } from "../../domain/result.js";
/** Caller selections resolved once before entering the runtime adapter. */
export type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & { readonly application_root: string };
/** Provider-neutral boundary for owned Electron runtime experiments. */
export interface ElectronActiveObservationPort {
identity(): ProviderIdentity;
capture(
input: ElectronActiveObservationInput,
input: CanonicalElectronActiveObservationInput,
options?: ExecutionOptions,
): Promise<Result<ElectronActiveObservationResult, AnalysisError>>;
}
@@ -2,57 +2,80 @@ import { dirname } from "node:path";
import { realpath } from "node:fs/promises";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { ElectronActiveObservationPort } from "./ElectronActiveObservationPort.js";
import type {
CanonicalElectronActiveObservationInput,
ElectronActiveObservationPort,
} from "./ElectronActiveObservationPort.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
type AnalysisInputIssue,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import type { ElectronActiveObservationInput } from "../../domain/javascript/electronActiveObservation.js";
import { err, type Result } from "../../domain/result.js";
import { err, ok, type Result } from "../../domain/result.js";
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
const OPERATION = "capture_electron_scenario" as const;
const PROVIDER_ID = "rea-playwright-electron-active";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
readonly application_root: string;
};
const resolveInputPath = async (
field: "executable_path" | "application_path" | "application_root",
selected: string,
): Promise<
Result<
string,
{ readonly issue: AnalysisInputIssue; readonly cause: unknown }
>
> => {
try {
return ok(await realpath(selected));
} catch (cause: unknown) {
return err({
issue: {
path: [field],
reason: "invalid_value",
message: `Cannot resolve ${field} ${selected}: ${cause instanceof Error ? cause.message : String(cause)}`,
},
cause,
});
}
};
const canonicalizeInput = async (
input: ElectronActiveObservationInput,
): Promise<Result<CanonicalElectronActiveObservationInput, AnalysisError>> => {
try {
const [executablePath, applicationPath] = await Promise.all([
realpath(input.executable_path),
realpath(input.application_path),
]);
const applicationRoot =
input.application_root === undefined
? dirname(applicationPath)
: await realpath(input.application_root);
return {
ok: true,
value: {
...input,
executable_path: executablePath,
application_path: applicationPath,
application_root: applicationRoot,
},
};
} catch (cause: unknown) {
const [executable, application, root] = await Promise.all([
resolveInputPath("executable_path", input.executable_path),
resolveInputPath("application_path", input.application_path),
input.application_root === undefined
? Promise.resolve(ok(undefined))
: resolveInputPath("application_root", input.application_root),
]);
if (!executable.ok || !application.ok || !root.ok) {
const failures = [executable, application, root].flatMap((result) =>
result.ok ? [] : [result.error],
);
return err(
new AnalysisInputError(OPERATION, { cause }, [
new AnalysisInputError(
OPERATION,
{
path: ["application_path"],
reason: "invalid_format",
message:
"Electron executable, application, and root must resolve to existing paths",
cause: new AggregateError(
failures.map(({ cause }) => cause),
"Electron paths could not be resolved",
),
},
]),
failures.map(({ issue }) => issue),
),
);
}
return ok({
...input,
executable_path: executable.value,
application_path: application.value,
application_root: root.value ?? dirname(application.value),
});
};
/** Canonicalize request paths and execute one provider-owned Electron run. */
@@ -1,4 +1,6 @@
import { createHash } from "node:crypto";
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
import { setImmediate } from "node:timers/promises";
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
@@ -380,7 +382,10 @@ function* analyzeArtifactFileSteps<
yield;
const semantics =
analysis.parse_status === "complete" || analysis.parse_status === "partial"
? yield* analyzeParsedJavaScriptSemanticsSteps(parsed)
? yield* analyzeParsedJavaScriptSemanticsSteps(
parsed,
moduleKindForJavaScriptReference(file.path, "static-import"),
)
: null;
const projected =
semantics === null
@@ -376,10 +376,14 @@ const resolveReference = (
): ResolvedReference | null => {
const specifier = reference.specifier;
if (specifier === null) return null;
const chunk = resolveBundlerChunkReference(context, sourcePath, reference);
const isWorker =
reference.kind === "worker" || reference.kind === "service-worker";
const chunk = isWorker
? null
: resolveBundlerChunkReference(context, sourcePath, reference);
if (chunk !== null) return chunk;
const module =
reference.module_runtime === undefined
isWorker || reference.module_runtime === undefined
? undefined
: context.moduleNodes.get(
moduleLookupKey(sourcePath, reference.module_runtime, specifier),
@@ -391,24 +395,23 @@ const resolveReference = (
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
}
// Worker scripts are URLs relative to the script, not module specifiers.
const path =
reference.kind === "worker" || reference.kind === "service-worker"
? resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "url-reference",
files: context.filesByPath,
}).resolved_path
: resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require" ||
reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
: undefined,
);
const path = isWorker
? resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "url-reference",
files: context.filesByPath,
}).resolved_path
: resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require" ||
reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
: undefined,
);
if (path === null) return null;
const file = context.filesByPath.get(path);
const node = context.fileNodes.get(path);
@@ -509,17 +509,6 @@ describe("contextual JavaScript artifact path resolution", () => {
resolution_status: "resolved",
resolved_path: "renderer/local.js",
});
expect(
resolve({
declaredPath: "file:///assets/app.js#entry",
sourcePath: "main.js",
context: "module-specifier",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
});
it.each(["node:fs", "electron", "../../escape.js", "%2e%2e/escape.js"])(
@@ -576,24 +565,52 @@ describe("contextual JavaScript artifact path resolution", () => {
});
});
describe("CommonJS file URL resolution", () => {
it("keeps file URL resolution specific to the import loader", () => {
const files = fileMap([file("entry.cjs", "root"), file("dep.cjs", "root")]);
const input = {
declaredPath: "file:///dep.cjs",
sourcePath: "entry.cjs",
context: "module-specifier" as const,
files,
};
describe("JavaScript file URL resolution", () => {
it("resolves file URL paths without interpreting query bytes as path syntax", () => {
const files = fileMap([file("assets/app.js", "root")]);
for (const declaredPath of [
"file:///assets/app.js#entry",
"FILE:///assets/app.js?token=%2F#entry",
]) {
expect(
resolve({
declaredPath,
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
}
expect(resolve({ ...input, moduleKind: "require" })).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(resolve({ ...input, moduleKind: "import" })).toMatchObject({
resolution_status: "resolved",
resolved_path: "dep.cjs",
});
for (const declaredPath of [
"file:///assets%2Fapp.js",
"file:///assets%2\nFapp.js",
]) {
expect(
resolve({
declaredPath,
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
expect(
resolve({
declaredPath: "file:/assets/app.js",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
});
});
@@ -2000,15 +2017,143 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
});
});
describe("url-reference directory and empty-segment semantics", () => {
it.each([
"./worker.js/.",
"./worker.js/child/..",
"./worker.js/",
"/dist/worker.js/.",
"./worker.js/.?cache=1#entry",
])("keeps directory-form URLs distinct from files: %s", (declaredPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file("dist/worker.js", "root")]),
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "not-found",
resolved_path: null,
});
});
it.each(["./nested//worker.js", "./nested//../worker.js"])(
"does not collapse empty URL path segments: %s",
(declaredPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
}),
).toMatchObject({ resolved_path: null });
},
);
it.each([
["./nested/.././worker.js?cache=1#entry", "dist/worker.js"],
["./.worker.js", "dist/.worker.js"],
])("resolves exact file URLs with dots: %s", (declaredPath, resolvedPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(resolvedPath, "root")]),
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: resolvedPath,
});
});
});
describe("url-reference JavaScript artifact path resolution", () => {
it.each([
["C|?cache=1#entry", "dist/C|"],
["/c:/worker.js", "c:/worker.js"],
["/./c|/worker.js", "c|/worker.js"],
["../c|/worker.js", "c|/worker.js"],
["/nested/../c|/worker.js", "c|/worker.js"],
["c|/../worker.js", "dist/worker.js"],
])("leaves drive-letter URL paths unresolved: %s", (declaredPath, decoy) => {
const resolution = resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(decoy, "root")]),
});
expect(resolution).toMatchObject({
declared_path: declaredPath,
resolution_status: "unavailable",
resolved_path: null,
});
expect(resolution.limitations.length).toBeGreaterThan(0);
});
it.each([
["./c|/worker.js", "dist/c|/worker.js"],
["c|name/worker.js", "dist/c|name/worker.js"],
["/%63|/worker.js", "c|/worker.js"],
["/c%3A/worker.js", "c:/worker.js"],
])(
"retains non-drive URL path identities: %s",
(declaredPath, resolvedPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(resolvedPath, "root")]),
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: resolvedPath,
});
},
);
it.each(["?value=", "#value="])(
"admits the pathname independently of its %s suffix",
(suffix) => {
for (const value of ["%2F", "%2E", "%5C", "%00", "%FF", "\\", "\0"]) {
const declaredPath = `./worker.js${suffix}${value}`;
expect(
resolve({
declaredPath,
sourcePath: "dist/app.js",
context: "url-reference",
files: fileMap([file("dist/worker.js", "root")]),
}),
declaredPath,
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: "dist/worker.js",
});
}
},
);
it.each([
"app\0.js.map?valid=1",
"nested\\worker.js#valid",
"app%00.js.map",
"app%FF.js.map",
"app%C0%AF.js.map",
"app%2ejs.map",
"nested%2fworker.js",
"nested%5cworker.js",
"h\nttp://[",
"../../outside.js.map",
"../../outside/.",
])("rejects an inadmissible URL path: %s", (declaredPath) => {
const resolution = resolve({
declaredPath,
@@ -68,12 +68,20 @@ export interface ResolveArtifactPathInput {
export const moduleKindForJavaScriptReference = (
sourcePath: string,
referenceKind: "static-import" | "dynamic-import" | "require",
resolutionMode?: "import" | "require",
): "import" | "require" =>
referenceKind === "require" ||
resolutionMode ??
(referenceKind === "require" ||
(referenceKind === "static-import" &&
posix.extname(sourcePath).toLowerCase() === ".cts")
? "require"
: "import";
: "import");
/** Preserve an explicitly retained loader mode on graph relationships. */
export const moduleResolutionModeProperties = (
mode: "import" | "require" | undefined,
): Readonly<Record<string, "import" | "require">> =>
mode === undefined ? {} : { resolution_mode: mode };
const EXTENSIONS = [
".js",
@@ -145,17 +153,15 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
input.declaredPath.startsWith("#")
)
return resolvePackageImportAlias(input, input.declaredPath);
const rejected = rejectDeclaration(input.declaredPath);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(input);
if (typeof candidate !== "string") return candidate;
const confined = confineCandidate(candidate);
if (typeof confined !== "string") return confined;
if (input.context === "html-reference")
if (input.context === "html-reference" || input.context === "url-reference")
return (
resolveFileCandidates(input, [confined]) ??
unresolvedCandidate("not-found", [
`The exact HTML resource ${confined} was not found among the selected application files.`,
`The exact ${input.context === "html-reference" ? "HTML" : "URL"} resource ${confined} was not found among the selected application files.`,
])
);
const isModuleUrlPath =
@@ -193,19 +199,32 @@ const contextualCandidate = (
input: ResolveArtifactPathInput,
): string | CandidateResolution => {
const { context } = input;
// URL suffixes are evidence, not pathname bytes. Admit only the path while
// retaining the complete declaration on the resolution result.
let declared =
context === "html-reference" || context === "url-reference"
context === "url-reference"
? stripQueryAndFragment(input.declaredPath)
: input.declaredPath;
if (context === "html-reference") return htmlCandidate(input);
if (context === "module-specifier") {
if (context === "module-specifier" && /^file:/iu.test(declared)) {
const fileUrl = fileUrlPath(declared);
if (fileUrl === null)
return unresolvedCandidate("rejected", [
"The file URL path contains syntax that cannot identify a canonical artifact path.",
]);
if (fileUrl !== undefined)
return input.moduleKind === "require"
? unresolvedCandidate("external", [
"Node CommonJS require specifiers do not resolve file URLs as local artifacts.",
])
: fileUrl;
return unresolvedCandidate("external", [
"File URL authorities or invalid file URL forms cannot be mapped to artifact-local paths.",
]);
}
const rejected = rejectDeclaration(declared);
if (rejected !== null) return rejected;
if (context === "html-reference") return htmlCandidate(input);
if (context === "module-specifier") {
if (hasScheme(declared))
return unresolvedCandidate("external", [
"URL and Node builtin schemes are outside static artifact module resolution.",
@@ -222,12 +241,39 @@ const contextualCandidate = (
"URL schemes and protocol-relative URLs are outside this local artifact path context.",
]);
if (context === "url-reference") {
// A file base gives raw drive-letter segments special meaning, including
// after dot segments reach the root. Parse before percent decoding so an
// encoded drive-like filename stays literal. The synthetic base establishes
// only this ambiguity; it does not establish the source's runtime scheme.
const sourceUrlPath = input.sourcePath
.split("/")
.map(encodeURIComponent)
.join("/");
const fileReference = URL.parse(declared, `file:///${sourceUrlPath}`);
if (fileReference === null)
return unresolvedCandidate("rejected", [
"The URL reference cannot be parsed as a URL.",
]);
if (/^\/[A-Za-z]:(?:\/|$)/u.test(fileReference.pathname))
return unresolvedCandidate("unavailable", [
"Drive-letter URL paths cannot be mapped without the source URL scheme and filesystem root.",
]);
const decoded = percentDecodeUrlPath(declared);
if (decoded === null)
return unresolvedCandidate("rejected", [
"The URL reference path percent-decodes to NUL or to bytes that are not UTF-8.",
]);
declared = decoded;
// Empty URL segments are significant; canonical filesystem paths cannot
// preserve them, including their interaction with following dot segments.
if (decoded.includes("//"))
return unresolvedCandidate("unavailable", [
"Repeated URL path separators cannot be mapped to an exact canonical artifact file.",
]);
return exactUrlPathCandidate(
decoded,
relativeCandidate(input.sourcePath, decoded),
"URL",
);
}
return relativeCandidate(input.sourcePath, declared);
};
@@ -681,37 +727,34 @@ const htmlCandidate = (
const basePath = decodedBase.startsWith("/")
? decodedBase.slice(1)
: posix.join(posix.dirname(input.sourcePath), decodedBase);
if (declaredPath === "") return emptyHtmlReference(decodedBase, basePath);
if (declaredPath === "")
return exactUrlPathCandidate(decodedBase, basePath, "HTML");
return posix.join(htmlBaseDirectory(decodedBase, basePath), declaredPath);
};
const emptyHtmlReference = (
base: string,
basePath: string,
const exactUrlPathCandidate = (
declared: string,
candidate: string,
kind: "HTML" | "URL",
): string | CandidateResolution => {
if (!htmlBaseIsDirectory(base)) return basePath;
const confined = confineCandidate(basePath);
if (!urlPathIsDirectory(declared)) return candidate;
const confined = confineCandidate(candidate);
if (typeof confined !== "string") return confined;
return unresolvedCandidate("not-found", [
`The HTML reference resolves to directory ${confined || "."}, not an exact selected application file.`,
`The ${kind} reference resolves to directory ${confined || "."}, not an exact selected application file.`,
]);
};
/**
* The directory a relative HTML reference resolves against. A base path
* ending in "/" or in a "." or ".." segment is already a directory, because a
* relative reference resolves against the base URL's directory and those
* segments are dropped rather than stepped through.
*/
const htmlBaseIsDirectory = (base: string): boolean =>
base.endsWith("/") ||
base.endsWith("/.") ||
base.endsWith("/..") ||
base === "." ||
base === "..";
/** Whether a URL path retains directory form after dot-segment normalization. */
const urlPathIsDirectory = (path: string): boolean =>
path.endsWith("/") ||
path.endsWith("/.") ||
path.endsWith("/..") ||
path === "." ||
path === "..";
const htmlBaseDirectory = (base: string, basePath: string): string =>
htmlBaseIsDirectory(base) ? basePath : posix.dirname(basePath);
urlPathIsDirectory(base) ? basePath : posix.dirname(basePath);
const confineCandidate = (candidate: string): string | CandidateResolution => {
const normalized = normalizeJoinedLogicalPath(candidate);
@@ -854,8 +897,6 @@ const resolveDirectory = (
files: input.files,
...(input.moduleKind === undefined ? {} : { moduleKind: input.moduleKind }),
};
const rejected = rejectDeclaration(entryInput.declaredPath);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(entryInput);
if (typeof candidate !== "string") return candidate;
const confined = confineCandidate(candidate);
@@ -1162,12 +1203,26 @@ const exactPackageTargetNotFound = (
],
});
const fileUrlPath = (value: string): string | undefined => {
if (!value.startsWith("file://")) return undefined;
const fileUrlPath = (value: string): string | null | undefined => {
if (!/^file:\/\//iu.test(value)) return undefined;
// URL parsing removes tabs and newlines and normalizes encoded dot segments.
// Check the raw path first, excluding URL identity suffixes, then check the
// parsed pathname so parser normalization cannot introduce a separator.
const rawPath = stripQueryAndFragment(value);
if (
value.includes("\0") ||
value.includes("\\") ||
/[\t\n\r]/u.test(rawPath) ||
!admitsCanonicalPathSyntax(rawPath)
)
return null;
try {
const url = new URL(value);
if (url.protocol !== "file:" || url.hostname !== "") return undefined;
return decodeURIComponent(url.pathname).replace(/^\/+/, "");
if (!admitsCanonicalPathSyntax(url.pathname)) return null;
const decoded = decodeURIComponent(url.pathname);
if (decoded.includes("\0")) return null;
return decoded.replace(/^\/+/, "");
} catch (cause: unknown) {
// Unparseable file URLs have no path to resolve.
void cause;
@@ -31,6 +31,7 @@ import {
} from "./JavaScriptArtifactGraphEvidence.js";
import {
moduleKindForJavaScriptReference,
moduleResolutionModeProperties,
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "./JavaScriptArtifactPathResolution.js";
@@ -281,6 +282,7 @@ const resolveModuleTarget = (
input.link.kind === "require" || input.link.kind === "commonjs-export"
? "require"
: "static-import",
input.link.resolutionMode,
),
});
if (resolution.resolution_status !== "resolved")
@@ -373,6 +375,7 @@ const relationshipProperties = (
origin?: JavaScriptModuleOrigin,
) => ({
module_link_kind: link.kind,
...moduleResolutionModeProperties(link.resolutionMode),
specifier: origin?.specifier ?? link.specifier,
imported_name: origin?.importedPath.at(-1) ?? link.importedName,
imported_path: origin?.importedPath ?? [],
@@ -0,0 +1,93 @@
import { isAbsolute } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
decodeSignalRecordingInputSchema,
signalRecordingSchema,
type DecodeSignalRecordingInput,
} from "../../domain/signals/signalRecording.js";
import { err, ok, type Result } from "../../domain/result.js";
export interface SignalRecordingPort {
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
decode(
input: DecodeSignalRecordingInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
close(): Promise<void>;
}
/** One shared validation and Evidence owner for CLI and MCP. */
export class SignalRecordingService {
constructor(readonly provider: SignalRecordingPort) {}
close(): Promise<void> {
return this.provider.close();
}
async decode(
raw: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "decode_signal_recording";
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const input = decodeSignalRecordingInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute local path.",
},
]),
);
const decoded = await this.provider.decode(input.data, options);
if (!decoded.ok) return decoded;
const execution = decoded.value;
const report = signalRecordingSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
)
return err(
new AnalysisOutputError(
operation,
"Decoder returned malformed data or changed the selected recording identity/options.",
),
);
const evidence = createEvidence(execution.subject, execution.provider, {
operation,
parameters: input.data,
result: report.data,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
});
return options?.signal?.aborted
? err(
new AnalysisCancelledError(operation, {
partialObservation: evidence,
}),
)
: ok(evidence);
}
}
+9
View File
@@ -6,6 +6,7 @@ import type { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js";
import type { ArtifactReader } from "./ArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { SafeOutputTree } from "./SafeOutputTree.js";
import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
/** One artifact resource and its format-specific cleanup owner. */
export type ArtifactResourceOwner =
@@ -38,6 +39,11 @@ export type ArtifactResourceOwner =
readonly kind: "staged-output";
readonly resource: string;
readonly output: OwnedStagedOutput;
}
| {
readonly kind: "private-runtime-root";
readonly resource: string;
readonly root: Pick<PrivateRuntimeRoot, "path" | "close">;
};
export type ArtifactCleanupAttempt =
@@ -161,5 +167,8 @@ const cleanup = async (owner: ArtifactResourceOwner): Promise<void> => {
return;
case "staged-output":
await owner.output.close();
return;
case "private-runtime-root":
await owner.root.close();
}
};
+2
View File
@@ -625,7 +625,9 @@ const verifyFailureReason = (
processOutput(cause, "stderr"),
);
switch (diagnostic) {
// hdiutil follows AppleLanguages, so en-GB and en-AU spell it "recognised".
case "image not recognized":
case "image not recognised":
return "format";
case "invalid checksum":
case "image data corrupted":
+191
View File
@@ -0,0 +1,191 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { ZipArtifactReader } from "./ZipArtifactReader.js";
import {
ARTIFACT_DECOMPRESSION_RATIO,
artifactDecompressionBudgetBytes,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
} from "../domain/artifactDecompressionBudget.js";
/** Small real ZIP carriers with forged sizes; metadata-only controls, never decompressed. */
const writeZipWithDeclaredSize = async (
directory: string,
declaredBytes: readonly number[],
): Promise<string> => {
const path = join(directory, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [index] of declaredBytes.entries())
await writer.add(
`member-${index}.bin`,
new TextReader("real member bytes"),
);
await writeFile(path, await writer.close());
const bytes = await readFile(path);
let offset = 0;
for (const declared of declaredBytes) {
const centralDirectory = bytes.indexOf(
Buffer.from([0x50, 0x4b, 0x01, 0x02]),
offset,
);
if (centralDirectory < 0)
throw new Error("Expected a ZIP central directory");
// Metadata-only controls: these declarations do not describe valid member streams.
bytes.writeUInt32LE(declared, centralDirectory + 24);
offset = centralDirectory + 46;
}
await writeFile(path, bytes);
return path;
};
const enumerate = async (reader: ZipArtifactReader): Promise<number> => {
let files = 0;
for await (const entry of reader.entries())
if (entry.kind === "file") files += 1;
return files;
};
describe("ZipArtifactReader decompression budget", () => {
it("refuses an archive whose entries declare more than its size can justify", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-bomb-");
// A ~160-byte archive cannot declare 2 GiB of members without being a bomb.
const path = await writeZipWithDeclaredSize(directory, [2_147_483_647]);
const reader = new ZipArtifactReader(path, "zip");
try {
await expect(enumerate(reader)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "limit",
});
} finally {
await reader.close();
}
});
it("charges all declarations in one traversal before yielding an over-budget member", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-total-");
const half = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2;
const path = await writeZipWithDeclaredSize(directory, [half, half + 1]);
const reader = new ZipArtifactReader(path, "zip");
const iterator = reader.entries()[Symbol.asyncIterator]();
try {
expect((await iterator.next()).value?.declaredSize).toBe(half);
await expect(iterator.next()).rejects.toMatchObject({ reason: "limit" });
} finally {
await iterator.return?.();
await reader.close();
}
});
it("keeps repeated and interleaved metadata traversals independently charged", async () => {
const directory = await createTestTempDirectory(
"rea-zip-budget-iterators-",
);
const path = await writeZipWithDeclaredSize(directory, [
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
]);
const reader = new ZipArtifactReader(path, "zip");
const first = reader.entries()[Symbol.asyncIterator]();
const second = reader.entries()[Symbol.asyncIterator]();
try {
expect((await first.next()).done).toBe(false);
expect((await second.next()).done).toBe(false);
expect((await first.next()).done).toBe(false);
expect((await second.next()).done).toBe(false);
expect((await first.next()).done).toBe(true);
expect((await second.next()).done).toBe(true);
expect(await enumerate(reader)).toBe(2);
} finally {
await Promise.all([first.return?.(), second.return?.()]);
await reader.close();
}
});
it("streams a valid small member through open", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-valid-");
const path = join(directory, "valid.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("member.bin", new TextReader("valid member bytes"));
await writeFile(path, await writer.close());
const reader = new ZipArtifactReader(path, "zip");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries[0];
if (entry === undefined) throw new Error("Expected a ZIP member");
const chunks: Buffer[] = [];
for await (const chunk of await reader.open(entry))
chunks.push(Buffer.from(chunk));
expect(Buffer.concat(chunks).toString()).toBe("valid member bytes");
} finally {
await reader.close();
}
});
it("rejects under-declared member output before delivering its complete actual bytes", async () => {
const directory = await createTestTempDirectory("rea-zip-underdeclared-");
const path = join(directory, "underdeclared.zip");
const content = new Uint8Array(128 * 1024);
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("member.bin", new Uint8ArrayReader(content), {
dataDescriptor: false,
bufferedWrite: true,
});
const bytes = Buffer.from(await writer.close());
const local = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
if (local < 0 || central < 0) throw new Error("Expected ZIP entry headers");
// Both headers agree and no descriptor remains: rejection must enforce
// actual decompressed output, not merely detect conflicting metadata.
expect(bytes.readUInt16LE(local + 6) & 8).toBe(0);
expect(bytes.readUInt16LE(local + 8)).toBe(8);
expect(bytes.readUInt32LE(local + 22)).toBe(content.length);
expect(bytes.readUInt32LE(central + 24)).toBe(content.length);
bytes.writeUInt32LE(1, local + 22);
bytes.writeUInt32LE(1, central + 24);
await writeFile(path, bytes);
const reader = new ZipArtifactReader(path, "zip");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries[0];
if (entry === undefined) throw new Error("Expected a ZIP member");
expect(entry.declaredSize).toBe(1);
let deliveredBytes = 0;
await expect(
(async () => {
for await (const chunk of await reader.open(entry))
deliveredBytes += Buffer.from(chunk).length;
})(),
).rejects.toThrow("Invalid uncompressed size");
expect(deliveredBytes).toBeLessThan(content.length);
} finally {
await reader.close();
}
});
});
describe("artifactDecompressionBudgetBytes", () => {
it("grants at least the floor and grows with the compressed size", () => {
expect(artifactDecompressionBudgetBytes(0)).toBe(
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
);
expect(artifactDecompressionBudgetBytes(1024)).toBe(
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
);
const large = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES * 4;
expect(artifactDecompressionBudgetBytes(large)).toBe(
large * ARTIFACT_DECOMPRESSION_RATIO,
);
});
});
+23 -1
View File
@@ -12,6 +12,11 @@ import {
type ArtifactReader,
} from "./ArtifactReader.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import {
ARTIFACT_DECOMPRESSION_RATIO,
artifactDecompressionBudgetBytes,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
} from "../domain/artifactDecompressionBudget.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
NonRegularFileReadError,
@@ -132,7 +137,6 @@ export class ZipArtifactReader implements ArtifactReader {
string,
{ readonly source: Entry; readonly metadata: ArtifactEntry }
>();
/** Optionally bound each metadata read before allocating its backing buffer. */
constructor(
path: string,
@@ -153,6 +157,8 @@ export class ZipArtifactReader implements ArtifactReader {
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
let index = 0;
// A traversal owns its accounting, including overlapping or repeated passes.
let declaredFileBytes = 0;
for await (const entry of this.#reader.getEntriesGenerator({
decodeText: decodeZipEntryText,
})) {
@@ -160,6 +166,22 @@ export class ZipArtifactReader implements ArtifactReader {
// ZIP member identity is its directory occurrence, not its filename.
// Logical path uniqueness belongs to the artifact inventory boundary.
const metadata = projectZipEntry(entry, index++);
// zip.js enforces each member's declared output size, so this sum bounds streamed work.
if (
metadata.kind === "file" &&
!metadata.encrypted &&
metadata.declaredSize !== null &&
Number.isSafeInteger(metadata.declaredSize) &&
metadata.declaredSize >= 0
) {
declaredFileBytes += metadata.declaredSize;
const budget = artifactDecompressionBudgetBytes(this.#source.size);
if (declaredFileBytes > budget)
throw new ArtifactReaderFailure(
"limit",
`ZIP entries declare ${String(declaredFileBytes)} uncompressed bytes, exceeding this archive's ${String(budget)}-byte decompression budget (${String(MINIMUM_ARTIFACT_DECOMPRESSION_BYTES)}-byte minimum, ${String(ARTIFACT_DECOMPRESSION_RATIO)}x archive size); a small archive cannot expand this far`,
);
}
const stored = this.#entries.get(metadata.adapterKey);
if (stored !== undefined && !sameArtifactEntry(metadata, stored.metadata))
throw new ArtifactReaderFailure(
+20 -12
View File
@@ -2,6 +2,10 @@ import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
import {
interfaceBuilderConnectionFieldNames,
isUIKitRuntimeConnectionClass,
} from "../../domain/apple/interfaceBuilderKeyedArchive.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
@@ -29,6 +33,10 @@ import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import {
hasBinaryPlistSignature,
hasNibArchiveSignature,
} from "../../domain/apple/appleArchiveFormat.js";
const MAX_AGGREGATE_INPUT_BYTES = 32 * 1024 * 1024;
const MAX_AGGREGATE_DECODE_BYTES = 256 * 1024 * 1024;
@@ -90,8 +98,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
remainingInputBytes,
);
aggregateInputBytes += bytes.length;
const isNibArchive =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive";
const isNibArchive = hasNibArchiveSignature(bytes);
let nib: ReturnType<typeof projectNibArchive> | null = null;
let xmlText: string | undefined;
let binaryPrototypeKeyObserved = false;
@@ -109,7 +116,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
"NIBArchive representation exceeds the aggregate Interface Builder decode budget",
);
} else {
if (bytes.subarray(0, 8).toString("ascii") !== "bplist00")
if (!hasBinaryPlistSignature(bytes))
xmlText = decodeXmlPlistText(bytes);
const decodedReservation = preflightPropertyListDecode(
bytes,
@@ -438,8 +445,10 @@ const projectNibArchive = (
archive.objects
.filter((object) => {
const name = runtimeClass(object.id) ?? "";
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
name,
return (
!/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector)$/u.test(
name,
) && !isUIKitRuntimeConnectionClass(name)
);
})
.map((object) => {
@@ -498,15 +507,14 @@ const projectNibArchive = (
const className = normalizeClassName(object.class_name);
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
// event connections use UI-prefixed keys with the same roles.
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
const uiKit = isUIKitRuntimeConnectionClass(className);
if (!uiKit && !className.includes("Connector")) continue;
const values = object.values;
const source = reference(uiKit ? values.UISource : values.NSSource);
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = reference(values[connectionFields.source]);
if (source === null) continue;
const destination = reference(
uiKit ? values.UIDestination : values.NSDestination,
);
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
const destination = reference(values[connectionFields.destination]);
const label = referencedString(values[connectionFields.label]);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control") || className.includes("Event")
@@ -660,7 +668,7 @@ const decodePlist = (
readonly value: JsonValue;
readonly omittedPrototypeKeys: number | null;
} => {
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const binary = hasBinaryPlistSignature(bytes);
const { value, omittedPrototypeKeys } = binary
? {
value: parseBinary(bytes),
@@ -1,4 +1,5 @@
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
/** Reason reported when an archive would exceed the shared decoding budget. */
export type InterfaceBuilderBudgetReason = "aggregate_decode_budget_exhausted";
@@ -94,13 +95,12 @@ export const preflightPropertyListDecode = (
maxBytes: number,
xmlText?: string,
): PlistDecodePreflight => {
const expansion =
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? estimateBinaryPlistExpansion(bytes, maxBytes)
: {
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
binaryPrototypeKeyObserved: false,
};
const expansion = hasBinaryPlistSignature(bytes)
? estimateBinaryPlistExpansion(bytes, maxBytes)
: {
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
binaryPrototypeKeyObserved: false,
};
if (expansion.estimatedBytes > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
@@ -170,8 +170,8 @@ export interface BinaryPlistExpansionOptions {
readonly fail?: (kind: BinaryPlistExpansionFailure, message: string) => Error;
/**
* Structural bounds: "strict" keeps objects and the offset table before the
* trailer; "decoder" admits exactly what plist.parseBinary can read, so
* expansion is bounded without rejecting archives that decoder accepts.
* trailer; "decoder" follows the decoder's object-table boundary policy
* while still rejecting structures whose coercion would lose plist facts.
*/
readonly bounds?: "strict" | "decoder";
}
@@ -267,6 +267,8 @@ export const estimateBinaryPlistExpansion = (
throw new TypeError("binary plist object offset is invalid");
const marker = bytes[offset] ?? 0;
const type = marker >> 4;
if (entry.dictionaryKey && type !== 5 && type !== 6)
throw new TypeError("binary plist dictionary key is not a string");
let size = marker & 0x0f;
let cursor = offset + 1;
if (size === 0x0f && type !== 0 && type !== 8) {
+49 -1
View File
@@ -23,6 +23,23 @@ const archive = {
$top: { root: { UID: 1 }, other: { UID: 2 } },
};
describe("inert keyed archive decoding", () => {
it.each(["bplist00", "NIBArchive"])(
"rejects high-bit mutations of %s as malformed bytes rather than another archive kind",
(signature) => {
for (let index = 0; index < signature.length; index += 1) {
const bytes = Buffer.from(signature);
bytes[index] = (bytes[index] ?? 0) | 0x80;
expect(() =>
decodeKeyedArchiveBytes(bytes, { offset: 0, limit: 1 }),
).toThrow(
expect.objectContaining({
code: "ERR_ENCODING_INVALID_ENCODED_DATA",
}),
);
}
},
);
it("preserves CF$UID, malformed references and original pagination identities", () => {
const bytes = Buffer.from(
build({
@@ -202,6 +219,37 @@ const keyedRoot = (payload: readonly Buffer[]): Buffer =>
describe("binary plist reference preflight", () => {
const selection = { offset: 0, limit: 10 };
it("rejects an array key that coerces to __proto__ before parsing", () => {
expect(() =>
decodeKeyedArchiveBytes(
keyedRoot([
plistArray([9]),
Buffer.from([0xd1, 0, 10, 0, 11]),
plistArray([12]),
Buffer.from([0xd1, 0, 13, 0, 14]),
plistString("__proto__"),
plistString("lost"),
plistString("value"),
]),
selection,
),
).toThrow("binary plist dictionary key is not a string");
});
it("rejects binary data dictionary keys", () => {
expect(() =>
decodeKeyedArchiveBytes(
keyedRoot([
plistArray([9]),
Buffer.from([0xd1, 0, 10, 0, 11]),
Buffer.from([0x41, 0xab]),
plistString("value"),
]),
selection,
),
).toThrow("binary plist dictionary key is not a string");
});
it("reports a reference cycle as malformed, not as an oversized archive", () => {
expect(() =>
decodeKeyedArchiveBytes(keyedRoot([plistArray([8])]), selection),
@@ -356,7 +404,7 @@ describe("XML plist nesting preflight", () => {
return cursor;
};
it.each([129, 200, 3000, 4000])(
it.each([129, 4000])(
"rejects %i-level XML nesting as the documented resource limit",
(depth) => {
// Recursive decoding exceeds the call stack before the projection limit
+6 -2
View File
@@ -27,6 +27,10 @@ import { ArtifactReaderFailure } from "../ArtifactReader.js";
import type { ArtifactEntry } from "../ArtifactReader.js";
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import {
hasBinaryPlistSignature,
hasNibArchiveSignature,
} from "../../domain/apple/appleArchiveFormat.js";
import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";
const MAX_BYTES = 64 * 1024 * 1024;
@@ -40,12 +44,12 @@ export const decodeKeyedArchiveBytes = (
) => {
if (bytes.length > MAX_BYTES)
throw new RangeError("Keyed archive exceeds 64 MiB");
if (bytes.subarray(0, 10).toString("ascii") === "NIBArchive")
if (hasNibArchiveSignature(bytes))
throw new KeyedArchiveKindError(
"Selected file is a compiled NIBArchive, not a Foundation plist archive; decode it with decode_interface_builder",
"nib-archive",
);
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const binary = hasBinaryPlistSignature(bytes);
const xmlText = binary ? undefined : decodeXmlPlistText(bytes);
// plist.parseBinary recurses on every object reference and copies shared
// containers, so a few hundred bytes can exhaust memory or the stack.
@@ -21,6 +21,7 @@ export const CPU = {
i386: { type: 7, subtype: 3 },
arm64: { type: 0x0100000c, subtype: 0 },
arm64e: { type: 0x0100000c, subtype: 0x80000002 },
arm64eX1: { type: 0x0100000c, subtype: 0x8000000c },
x86_64: { type: 0x01000007, subtype: 3 },
} as const;
@@ -26,6 +26,7 @@ import {
} from "./MachoLoadCommandReader.js";
import { traceDylibResolution } from "./DylibResolutionReader.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javaClassFile } from "../../../tests/fixtures/javaClassFile.js";
const read = (bytes: Uint8Array) =>
readMachoImage(readerOf(bytes), bytes.length);
@@ -135,6 +136,98 @@ it("uses legacy simulator and device platform facts when resolving dylibs", asyn
);
});
it("selects matching arm64e subtype slices when tracing a mixed FAT image", async () => {
const root = await createTestTempDirectory("rea-macho-arm64e-subtypes-");
const executablePath = "Contents/MacOS/App";
const dylibPath = "Contents/MacOS/libVariant.dylib";
const installName = "@executable_path/libVariant.dylib";
const arm64eDependency = "@executable_path/libArm64e.dylib";
const arm64eX1Dependency = "@executable_path/libArm64eX1.dylib";
const executableSlice = (cpu: typeof CPU.arm64e | typeof CPU.arm64eX1) =>
machoImage({
cpu,
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, installName),
],
});
const executable = fatImage([
{
cpu: CPU.arm64eX1,
bytes: executableSlice(CPU.arm64eX1),
},
{
cpu: CPU.arm64e,
bytes: executableSlice(CPU.arm64e),
},
]);
const variantSlice = (
cpu: typeof CPU.arm64e | typeof CPU.arm64eX1,
dependencyName: string,
) =>
machoImage({
cpu,
fileType: FILE_TYPE.dylib,
commands: [
buildVersionCommand(1),
dylibCommand(LC.ID_DYLIB, installName),
dylibCommand(LC.LOAD_DYLIB, dependencyName),
],
});
const completeDylib = fatImage([
{
cpu: CPU.arm64e,
bytes: variantSlice(CPU.arm64e, arm64eDependency),
},
{
cpu: CPU.arm64eX1,
bytes: variantSlice(CPU.arm64eX1, arm64eX1Dependency),
},
]);
await mkdir(join(root, "Contents/MacOS"), { recursive: true });
await writeFile(join(root, executablePath), executable);
await writeFile(join(root, dylibPath), completeDylib);
const trace = () =>
traceDylibResolution({
rootPath: root,
targetPath: join(root, executablePath),
targetSha256: createHash("sha256").update(executable).digest("hex"),
enumerateRoots: false,
parameters: { roots: [executablePath] },
});
const complete = await trace();
expect(
complete.edges
.filter(({ loader }) => loader === dylibPath)
.map(({ install_name: dependencyName }) => dependencyName),
).toEqual([arm64eX1Dependency, arm64eDependency]);
const onlyArm64e = fatImage([
{
cpu: CPU.arm64e,
bytes: variantSlice(CPU.arm64e, arm64eDependency),
},
]);
await writeFile(join(root, dylibPath), onlyArm64e);
const missingVariant = await trace();
expect(
missingVariant.edges
.filter(
({ loader, install_name: dependencyName }) =>
loader === executablePath && dependencyName === installName,
)
.map(({ candidates, resolution }) => [
candidates[0]?.outcome,
resolution.status,
]),
).toEqual([
["architecture-missing", "unresolved"],
["resolved", "resolved"],
]);
});
describe("Mach-O load command reader: decodes thin-image load commands", () => {
it("decodes dylib loading commands of a thin image", async () => {
const image = machoImage({
@@ -345,10 +438,13 @@ describe("Mach-O load command reader inputs", () => {
expect(i386.status === "parsed" && i386.slices[0]?.architecture).toBe(
"i386",
);
// A Java class file shares the FAT magic; its version is not a slice count.
const javaClass = Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
// A Java class file shares the FAT magic; version fields are not a slice count.
const javaClasses = [javaClassFile(), javaClassFile(4000)];
expect(javaClasses.map(({ length }) => length)).toEqual([57, 4060]);
for (const javaClass of javaClasses) {
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
}
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
status: "not-mach-o",
});
@@ -489,6 +585,16 @@ describe("Mach-O load command reader failures", () => {
reason: "FAT architecture 0 slice range extends beyond the file",
});
});
it("preserves unsupported status for an unsupported FAT alignment exponent", async () => {
const fat = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
new DataView(fat.buffer).setUint32(24, 53, false);
expect(await read(fat)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("alignment exponent 53 is unsupported"),
});
});
});
it.each([true, false])(
+38 -80
View File
@@ -3,9 +3,11 @@ import type {
MachoImageFacts,
MachoSlice,
} from "../../domain/apple/dylibResolution.js";
import { machoCpuSubtypeBase } from "../../domain/apple/machoCpuIdentity.js";
import {
readFatSliceDeclarations,
validateFatSlice,
classifyFatContainerIdentity,
readFatContainerHeader,
validateFatSliceIdentity,
type FatSliceDeclaration,
} from "../../domain/apple/machoContainer.js";
@@ -14,13 +16,6 @@ export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
/** Load commands larger than this are refused instead of buffered. */
export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
const MAX_FAT_ARCHITECTURES = 128;
/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
const KNOWN_CPU_TYPES: readonly number[] = [
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
];
const MH_MAGIC = 0xfeedface;
const MH_MAGIC_64 = 0xfeedfacf;
const MH_CIGAM = 0xcefaedfe;
@@ -146,69 +141,41 @@ export const readMachoImage = async (
: { status: "not-mach-o" };
const view = viewOf(head);
const magic = view.getUint32(0, false);
if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
// FAT headers are big-endian; the swapped magics store them little-endian.
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
const count = view.getUint32(4, littleEndian);
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
// A Java class file's nonzero major version reads as the count, so an
// empty architecture table can only be a malformed universal header.
if (count === 0)
return {
status: "malformed",
reason: "FAT header declares no architectures",
};
if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
return { status: "not-mach-o" };
const tableBytes = await readExact(
readAt,
8,
count * (wide ? 32 : 20),
"FAT table",
);
const declarations = readFatSliceDeclarations(tableBytes, {
count,
wide,
littleEndian,
});
if (declarations.status !== "parsed")
throw new MachoFormatIssue("malformed", declarations.reason);
// A Java class file's version fields read as a FAT count; its "table" names no CPU.
if (
!declarations.slices.some(({ cpuType }) =>
KNOWN_CPU_TYPES.includes(cpuType),
)
) {
let hasMachOSliceHeader = false;
for (const declaration of declarations.slices) {
if (
validateFatSlice(
declaration,
size,
8 + count * (wide ? 32 : 20),
) !== null
)
continue;
const bytes = await readAt(declaration.offset, 4);
if (bytes.byteLength < 4) continue;
const sliceMagic = viewOf(bytes).getUint32(0, false);
if (
[MH_MAGIC, MH_MAGIC_64, MH_CIGAM, MH_CIGAM_64].includes(sliceMagic)
) {
hasMachOSliceHeader = true;
break;
}
}
if (!hasMachOSliceHeader) return { status: "not-mach-o" };
let header = readFatContainerHeader(head, size);
if (header.state !== "not-fat") {
if (header.state === "needs-data") {
header = readFatContainerHeader(
await readAt(0, header.requiredBytes),
size,
);
}
if (header.state === "not-fat") return { status: "not-mach-o" };
if (header.state === "needs-data")
throw new MachoFormatIssue("malformed", "FAT table is truncated");
if (header.state === "malformed")
throw new MachoFormatIssue("malformed", header.reason);
let identity = classifyFatContainerIdentity(header, () => undefined);
if (identity.state === "needs-slice-header") {
const sliceHeaders = new Map<number, number | null>();
for (const offset of identity.offsets) {
const bytes = await readAt(offset, 4);
sliceHeaders.set(
offset,
bytes.byteLength < 4 ? null : viewOf(bytes).getUint32(0, false),
);
}
identity = classifyFatContainerIdentity(header, (offset) =>
sliceHeaders.get(offset),
);
}
if (identity.state === "not-mach-o") return { status: "not-mach-o" };
if (identity.state === "malformed")
throw new MachoFormatIssue(identity.category, identity.reason);
if (identity.state === "needs-slice-header")
return { status: "not-mach-o" };
return {
status: "parsed",
slices: await readFatSlices(
readAt,
size,
8 + count * (wide ? 32 : 20),
declarations.slices,
),
slices: await readFatSlices(readAt, header.slices),
};
}
if (magic === MH_CIGAM || magic === MH_CIGAM_64)
@@ -228,25 +195,17 @@ export const readMachoImage = async (
const readFatSlices = async (
readAt: ReadAt,
size: number,
tableEnd: number,
declarations: readonly FatSliceDeclaration[],
): Promise<MachoSlice[]> => {
const slices: MachoSlice[] = [];
for (const declaration of declarations) {
const { offset, size: length, cpuType, cpuSubtype } = declaration;
const rangeIssue = validateFatSlice(declaration, size, tableEnd);
if (rangeIssue !== null)
throw new MachoFormatIssue(
rangeIssue.includes("unsupported") ? "unsupported" : "malformed",
rangeIssue,
);
const slice = await readSlice(readAt, offset, length, {
fatCpuType: cpuType,
fatCpuSubtype: cpuSubtype,
alignmentExponent: declaration.alignmentExponent,
});
const identityIssue = validateFatSlice(declaration, size, tableEnd, {
const identityIssue = validateFatSliceIdentity(declaration, {
cpuType: slice.cpu_type,
cpuSubtype: slice.cpu_subtype,
});
@@ -524,13 +483,12 @@ const CPU_ARCH_ABI64 = 0x01000000;
const CPU_ARCH_ABI64_32 = 0x02000000;
const CPU_TYPE_X86 = 7;
const CPU_TYPE_ARM = 12;
const CPU_SUBTYPE_MASK = 0xff000000;
const CPU_SUBTYPE_ARM64E = 2;
const CPU_SUBTYPE_ARM64E_X1 = 12;
const CPU_SUBTYPE_X86_64_H = 8;
const architectureName = (cpuType: number, cpuSubtype: number): string => {
const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
const subtype = machoCpuSubtypeBase(cpuSubtype);
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
// Both pointer-authentication subtypes belong to the arm64e family.
return subtype === CPU_SUBTYPE_ARM64E || subtype === CPU_SUBTYPE_ARM64E_X1
+2 -2
View File
@@ -1,11 +1,11 @@
import type { JsonValue } from "../../domain/jsonValue.js";
import { hasNibArchiveSignature } from "../../domain/apple/appleArchiveFormat.js";
import { TextDecoder } from "node:util";
import {
InterfaceBuilderDecodeBudget,
InterfaceBuilderDecodeBudgetExceeded,
} from "./InterfaceBuilderDecodeBudget.js";
const MAGIC = Buffer.from("NIBArchive", "ascii");
const DEFAULT_DECODE_BUDGET_BYTES = 128 * 1024 * 1024;
interface NibObjectRecord {
@@ -39,7 +39,7 @@ export const decodeNibArchive = (
bytes: Buffer,
budget = new InterfaceBuilderDecodeBudget(DEFAULT_DECODE_BUDGET_BYTES),
): NibArchiveDocument => {
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
if (bytes.length < 50 || !hasNibArchiveSignature(bytes))
throw new TypeError("NIBArchive magic or header is invalid");
const formatVersion = readU32(bytes, 10);
+2 -4
View File
@@ -1,5 +1,6 @@
import type { PlistNumberLiterals } from "../../domain/apple/plistNumbers.js";
import { decodeXmlText } from "../../domain/propertyListKeys.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
const collector = () => {
const integers = new Map<number, Set<string>>();
@@ -124,10 +125,7 @@ export const binaryPlistNumberLiterals = (
bytes: Buffer,
): PlistNumberLiterals => {
const output = collector();
if (
bytes.length < 40 ||
bytes.subarray(0, 8).toString("ascii") !== "bplist00"
)
if (bytes.length < 40 || !hasBinaryPlistSignature(bytes))
return output.result(true);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const trailer = bytes.length - 32;
@@ -1,5 +1,6 @@
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
import {
artifactEdgeId,
artifactIdForContent,
@@ -18,7 +19,14 @@ import {
zipPackageFormatForPath,
type ZipPackageFormat,
} from "../../domain/zipPackageFormat.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
import {
observeMzWindowsHeader,
parseDosMzHeader,
} from "../../domain/dosMz.js";
import {
classifyFatContainerIdentity,
readFatContainerHeader,
} from "../../domain/apple/machoContainer.js";
/** Mutable internal occurrence used until root-bound IDs are known. */
export interface MutableOccurrence {
@@ -433,11 +441,11 @@ export const classifyArtifactBytes = (
fileSize = prefix.length,
): ArtifactNode["format"] => {
if (hasZipSignature(prefix)) return "zip";
if (prefix.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist";
if (hasBinaryPlistSignature(prefix)) return "plist";
const fatFormat = classifyFatArtifact(prefix, fileSize);
if (fatFormat !== null) return fatFormat;
if (prefix.length >= 4) {
const magic = prefix.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return "mach-o";
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
@@ -450,22 +458,40 @@ export const classifyArtifactBytes = (
prefix.length < Math.min(fileSize, 64)
)
return "unknown";
const windowsOffset = mzWindowsHeaderOffset(prefix);
if (windowsOffset !== null) {
const windowsHeader = observeMzWindowsHeader(prefix, fileSize);
if (windowsHeader.state === "signature-needed") return "unknown";
if (windowsHeader.state === "declared") {
const windowsOffset = windowsHeader.offset;
if (
windowsHeader.signature === "PE" &&
windowsOffset >= 64 &&
windowsOffset <= prefix.length - 4 &&
prefix
.subarray(windowsOffset, windowsOffset + 4)
.equals(Buffer.from([0x50, 0x45, 0, 0]))
windowsOffset <= prefix.length - 4
)
return "pe";
} else if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
return "unknown";
}
if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
return "unknown";
}
return "file";
};
const classifyFatArtifact = (
prefix: Buffer,
fileSize: number,
): ArtifactNode["format"] | null => {
const fatHeader = readFatContainerHeader(prefix, fileSize);
if (fatHeader.state === "needs-data" || fatHeader.state === "malformed")
return "unknown";
if (fatHeader.state === "not-fat") return null;
const identity = classifyFatContainerIdentity(fatHeader, (offset) => {
if (offset >= prefix.length) return undefined;
if (offset + 4 > prefix.length) return null;
return prefix.readUInt32BE(offset);
});
return identity.state === "mach-o" ? "mach-o-universal" : "unknown";
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
const lower = path.toLowerCase();
if (lower.endsWith(".map")) return "maps-source";
+4 -4
View File
@@ -1,8 +1,8 @@
import { realpath } from "node:fs/promises";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
artifactInventoryOutputSchema,
type ArtifactInventoryOutput,
} from "../../domain/artifactGraph.js";
import { abortIfNeeded } from "../ArtifactHash.js";
import { scanCanonicalArtifactInventoryInScope } from "./scanCanonical.js";
@@ -13,9 +13,9 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySn
export const inventoryArtifact = async (
inputPath: string,
options: ArtifactInventoryOptions,
): Promise<ArtifactInventoryResult> => {
): Promise<ArtifactInventoryOutput> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
return artifactInventoryOutputSchema.parse(snapshot);
};
/** Scan an artifact once and retain the complete immutable graph for projection. */
+40 -14
View File
@@ -4,7 +4,11 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import type {
ArtifactInventoryCoverage,
ArtifactOccurrence,
IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import {
isZipPackageFormat,
ZIP_NON_ENTRY_TAIL_LIMITATION,
@@ -36,20 +40,42 @@ export const createReader = (
}
};
export const inventoryLimitations = (
/** Classify source coverage and preserve its user-facing explanation once. */
export const inventoryAssessment = (
format: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
): string[] => {
if (reader !== undefined)
return isZipPackageFormat(reader.format)
? [ZIP_NON_ENTRY_TAIL_LIMITATION]
: [];
// dmg and pkg reach here only after classifyRootFormat matched their bytes.
if (format === "dmg" || format === "pkg")
return [
integrityContradictions: readonly IntegrityContradiction[],
caseCollisionLimitation: string | undefined,
): {
readonly coverage_status: ArtifactInventoryCoverage;
readonly limitations: string[];
} => {
let coverageStatus: ArtifactInventoryCoverage = "complete";
const limitations: string[] = [];
if (reader !== undefined) {
if (isZipPackageFormat(reader.format))
limitations.push(ZIP_NON_ENTRY_TAIL_LIMITATION);
} else if (format === "dmg" || format === "pkg") {
coverageStatus = "partial";
limitations.push(
`${format.toUpperCase()} root hash is observed; child inventory requires a native macOS adapter.`,
];
if (format === "mach-o-universal" && process.platform !== "darwin")
return ["Universal Mach-O slices require the native macOS lipo adapter."];
return ["Artifact has no child container entries."];
);
} else if (format === "mach-o-universal" && process.platform !== "darwin") {
coverageStatus = "partial";
limitations.push(
"Universal Mach-O slices require the native macOS lipo adapter.",
);
} else {
// The graph's modeled scope is the root itself for recognized leaf formats.
limitations.push("Artifact has no child container entries.");
}
if (caseCollisionLimitation !== undefined) {
coverageStatus = "partial";
limitations.push(caseCollisionLimitation);
}
if (integrityContradictions.length > 0)
limitations.push(
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
);
return { coverage_status: coverageStatus, limitations };
};
+9 -22
View File
@@ -40,7 +40,7 @@ import {
hashStableRootArtifact,
hashStableRootArtifactHandle,
} from "./hashStableRootArtifact.js";
import { createReader, inventoryLimitations } from "./reader.js";
import { createReader, inventoryAssessment } from "./reader.js";
import {
scanReader,
type PendingIntegrityContradiction,
@@ -268,6 +268,12 @@ const buildInventorySnapshot = async (
orderedOccurrences,
orderedEdges,
});
const assessment = inventoryAssessment(
rootFormat,
reader,
integrityContradictions,
input.caseCollisionLimitation,
);
return {
manifest,
nodes: orderedNodes,
@@ -275,12 +281,8 @@ const buildInventorySnapshot = async (
edges: orderedEdges,
provenance: reader?.provenance() ?? [],
integrity_contradictions: integrityContradictions,
limitations: buildLimitations(
rootFormat,
reader,
integrityContradictions,
input.caseCollisionLimitation,
),
coverage_status: assessment.coverage_status,
limitations: assessment.limitations,
};
};
@@ -393,18 +395,3 @@ const buildManifest = ({
occurrence_count: orderedOccurrences.length,
edge_count: orderedEdges.length,
});
const buildLimitations = (
rootFormat: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
integrityContradictions: readonly IntegrityContradiction[],
caseCollisionLimitation: string | undefined,
): string[] => [
...inventoryLimitations(rootFormat, reader),
...(caseCollisionLimitation === undefined ? [] : [caseCollisionLimitation]),
...(integrityContradictions.length === 0
? []
: [
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
]),
];
+43
View File
@@ -80,6 +80,49 @@ const baseScenario = () => ({
},
});
describe("browser scenario secret redaction", () => {
it("matches percent-escape hex case without case-folding raw secrets", () => {
const secrets = BrowserScenarioSecrets.resolve(
browserScenarioSchema.parse(baseScenario()),
{
REA_TEST_SESSION: "a/b?",
REA_TEST_PASSWORD: "password",
REA_TEST_COOKIE: "cookie",
},
);
if (secrets === undefined) throw new Error("Expected resolved secrets");
expect(secrets.redact("logged a%2fb%3f, a%2Fb%3F and a%2fb%3F")).toBe(
"logged [REDACTED:session], [REDACTED:session] and [REDACTED:session]",
);
expect(secrets.redact("raw A/B? remains case-sensitive")).toBe(
"raw A/B? remains case-sensitive",
);
expect(
secrets.redactBytes(
Buffer.concat([
Buffer.from([0xff, 0]),
Buffer.from("a%2fb%3F"),
Buffer.from([0x80]),
]),
),
).toEqual(
Buffer.concat([
Buffer.from([0xff, 0]),
Buffer.from("[REDACTED:session]"),
Buffer.from([0x80]),
]),
);
expect(
secrets.sanitizeUrl("https://app.example.test/?token=a%2fb%3F").url,
).toBe("https://app.example.test/?token=[REDACTED:session]");
expect(secrets.fingerprint("stored a%2fb%3F")).toEqual({
value_state: "redacted-secret",
value_sha256: null,
});
});
});
describe("browserScenarioSchema", () => {
it("accepts and normalizes a declared scenario", () => {
const parsed = browserScenarioSchema.parse(baseScenario());
+254 -74
View File
@@ -15,84 +15,229 @@ const REDACTION_PREFIX = "[REDACTED:";
const encodedSecretValues = (secret: string): ReadonlySet<string> =>
new Set([
secret,
encodeURIComponent(secret),
new URLSearchParams([["value", secret]]).toString().slice("value=".length),
]);
type SecretSpellings = "raw" | "url" | "bytes";
type SecretSpellings = "url" | "text";
interface SecretPattern {
readonly text: string;
readonly searchText: string;
readonly percentInsensitive: boolean;
}
interface SecretReplacement extends SecretPattern {
readonly id: string;
}
interface SecretNeedle {
readonly id: string;
readonly needle: Buffer;
readonly percentInsensitive: boolean;
readonly marker: Buffer;
}
const secretSpellings = (
secret: string,
spellings: SecretSpellings,
): readonly string[] => {
if (secret === "") return [];
if (spellings === "raw") return [secret];
const values = [...encodedSecretValues(secret)];
if (spellings === "bytes") values.push(JSON.stringify(secret).slice(1, -1));
return [...new Set(values)].filter((value) => value !== "");
const normalizePercentEscapes = (value: string): string => {
if (!value.includes("%")) return value;
return value.replace(/%[0-9a-f]{2}/giu, (escape) => escape.toLowerCase());
};
const declaredLiterals = (
const secretPatterns = (
secret: string,
spellings: SecretSpellings,
): readonly SecretPattern[] => {
if (secret === "") return [];
const patterns: SecretPattern[] = [
{ text: secret, searchText: secret, percentInsensitive: false },
...[...encodedSecretValues(secret)].map((text) => ({
text,
searchText: normalizePercentEscapes(text),
percentInsensitive: true,
})),
];
if (spellings === "text")
patterns.push({
text: JSON.stringify(secret).slice(1, -1),
searchText: JSON.stringify(secret).slice(1, -1),
percentInsensitive: false,
});
const seen = new Set<string>();
return patterns.filter(({ text, percentInsensitive }) => {
if (text === "") return false;
const key = `${percentInsensitive ? "percent" : "literal"}:${text}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
const declaredPatterns = (
values: ReadonlyMap<string, string>,
spellings: SecretSpellings,
): readonly string[] => [
...new Set(
[...values.values()].flatMap((secret) =>
secretSpellings(secret, spellings),
),
),
];
): readonly SecretPattern[] => {
const seen = new Set<string>();
return [...values.values()]
.flatMap((secret) => secretPatterns(secret, spellings))
.filter(({ text, percentInsensitive }) => {
const key = `${percentInsensitive ? "percent" : "literal"}:${text}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
/** Pick a marker that does not itself contain a declared secret spelling. */
const redactionMarker = (id: string, literals: readonly string[]): string =>
[`${REDACTION_PREFIX}${id}]`, "[REDACTED]", "…", ""].find((candidate) =>
literals.every((literal) => !candidate.includes(literal)),
) ?? "";
const replaceSecretLiterals = (
value: string,
const secretReplacements = (
values: ReadonlyMap<string, string>,
spellings: SecretSpellings,
literals: readonly string[],
): string => {
const replacements = [...values]
): readonly SecretReplacement[] =>
[...values]
.flatMap(([id, secret]) =>
secretSpellings(secret, spellings).map((text) => ({ id, text })),
secretPatterns(secret, spellings).map((pattern) => ({ id, ...pattern })),
)
.sort(
(left, right) =>
right.text.length - left.text.length ||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
);
let output = value;
for (const replacement of replacements)
output = output.replaceAll(
replacement.text,
redactionMarker(replacement.id, literals),
);
return output;
const normalizePercentEscapesBytes = (value: Buffer): Buffer => {
if (value.indexOf(37) < 0) return value;
const normalized = Buffer.from(value);
for (let index = 0; index + 2 < normalized.length; index += 1)
if (
normalized[index] === 37 &&
isHexByte(normalized[index + 1]) &&
isHexByte(normalized[index + 2])
) {
normalized[index + 1] = lowercaseHexByte(normalized[index + 1]!);
normalized[index + 2] = lowercaseHexByte(normalized[index + 2]!);
index += 2;
}
return normalized;
};
const isHexByte = (value: number | undefined): boolean =>
value !== undefined &&
((value >= 48 && value <= 57) ||
(value >= 65 && value <= 70) ||
(value >= 97 && value <= 102));
const lowercaseHexByte = (value: number): number =>
value >= 65 && value <= 70 ? value + 32 : value;
const patternMatches = (
value: string,
normalizedValue: string,
pattern: SecretPattern,
): boolean =>
(pattern.percentInsensitive ? normalizedValue : value).includes(
pattern.searchText,
);
const containsSecretPattern = (
value: string,
normalizedValue: string,
patterns: readonly SecretPattern[],
): boolean => {
if (patterns.length === 0) return false;
return patterns.some((pattern) =>
patternMatches(value, normalizedValue, pattern),
);
};
const containsSecretBytePattern = (
value: Buffer,
normalizedValue: Buffer,
needles: readonly SecretNeedle[],
): boolean =>
needles.some((needle) =>
(needle.percentInsensitive ? normalizedValue : value).includes(
needle.needle,
),
);
/** Pick a marker that does not itself contain a declared secret spelling. */
const redactionMarker = (
id: string,
patterns: readonly SecretPattern[],
): string => {
const candidates = [`${REDACTION_PREFIX}${id}]`, "[REDACTED]", "…", ""];
return (
candidates.find((candidate) =>
patterns.every(
(pattern) =>
!patternMatches(
candidate,
normalizePercentEscapes(candidate),
pattern,
),
),
) ?? ""
);
};
const replaceSecretLiterals = (
value: string,
replacements: readonly SecretReplacement[],
patterns: readonly SecretPattern[],
): string => {
const normalizedValue = replacements.some(
({ percentInsensitive }) => percentInsensitive,
)
? normalizePercentEscapes(value)
: value;
const parts: string[] = [];
let offset = 0;
while (offset < value.length) {
let next:
| ((typeof replacements)[number] & { readonly index: number })
| undefined;
for (const replacement of replacements) {
const search = replacement.searchText;
const view = replacement.percentInsensitive ? normalizedValue : value;
const index = view.indexOf(search, offset);
if (
index >= 0 &&
(next === undefined ||
index < next.index ||
(index === next.index && replacement.text.length > next.text.length))
)
next = { ...replacement, index };
}
if (next === undefined) break;
const marker = redactionMarker(next.id, patterns);
parts.push(value.slice(offset, next.index), marker);
offset = next.index + next.text.length;
}
if (parts.length === 0) return value;
parts.push(value.slice(offset));
return parts.join("");
};
const secretNeedles = (
values: ReadonlyMap<string, string>,
literals: readonly string[],
): Array<{
readonly id: string;
readonly needle: Buffer;
readonly marker: Buffer;
}> =>
[...values].flatMap(([id, secret]) =>
secretSpellings(secret, "bytes").map((text) => ({
id,
needle: Buffer.from(text),
marker: Buffer.from(redactionMarker(id, literals)),
})),
);
replacements: readonly SecretReplacement[],
patterns: readonly SecretPattern[],
): SecretNeedle[] =>
replacements.map((pattern) => ({
id: pattern.id,
needle: Buffer.from(pattern.searchText),
percentInsensitive: pattern.percentInsensitive,
marker: Buffer.from(redactionMarker(pattern.id, patterns)),
}));
/** Resolved secret values kept only for one in-memory scenario session. */
export class BrowserScenarioSecrets {
private constructor(private readonly values: ReadonlyMap<string, string>) {}
private readonly urlPatterns: readonly SecretPattern[];
private readonly textPatterns: readonly SecretPattern[];
private readonly urlReplacements: readonly SecretReplacement[];
private readonly textReplacements: readonly SecretReplacement[];
private readonly textNeedles: readonly SecretNeedle[];
private constructor(private readonly values: ReadonlyMap<string, string>) {
this.urlPatterns = declaredPatterns(values, "url");
this.textPatterns = declaredPatterns(values, "text");
this.urlReplacements = secretReplacements(values, "url");
this.textReplacements = secretReplacements(values, "text");
this.textNeedles = secretNeedles(this.textReplacements, this.textPatterns);
}
static resolve(
scenario: BrowserScenario,
@@ -127,18 +272,40 @@ export class BrowserScenarioSecrets {
}
redact(value: string): string {
const literals = declaredLiterals(this.values, "raw");
const output = replaceSecretLiterals(value, this.values, "raw", literals);
return literals.some((literal) => output.includes(literal)) ? "" : output;
const patterns = this.textPatterns;
if (patterns.length === 0) return value;
const output = replaceSecretLiterals(
value,
this.textReplacements,
patterns,
);
return containsSecretPattern(
output,
normalizePercentEscapes(output),
patterns,
)
? ""
: output;
}
/** Replace declared UTF-8, URI/form, and JSON-escaped secrets without decoding binary data. */
/** Replace declared UTF-8, URI/form, and JSON-escaped secret spellings. */
redactBytes(value: Buffer): Buffer {
const literals = declaredLiterals(this.values, "bytes");
const candidates = secretNeedles(this.values, literals)
const patterns = this.textPatterns;
if (patterns.length === 0) return value;
const candidates = this.textNeedles;
const hasPercentPatterns = candidates.some(
({ percentInsensitive }) => percentInsensitive,
);
const normalizedValue =
hasPercentPatterns && value.indexOf(37) >= 0
? normalizePercentEscapesBytes(value)
: value;
const sortedCandidates = candidates
.map((candidate) => ({
...candidate,
index: value.indexOf(candidate.needle),
index: (candidate.percentInsensitive ? normalizedValue : value).indexOf(
candidate.needle,
),
}))
.sort(
(left, right) =>
@@ -148,13 +315,18 @@ export class BrowserScenarioSecrets {
const parts: Buffer[] = [];
let offset = 0;
while (true) {
let next: (typeof candidates)[number] | undefined;
for (const candidate of candidates) {
let next: (typeof sortedCandidates)[number] | undefined;
for (const candidate of sortedCandidates) {
if (candidate.index >= 0 && candidate.index < offset)
candidate.index = value.indexOf(candidate.needle, offset);
candidate.index = (
candidate.percentInsensitive ? normalizedValue : value
).indexOf(candidate.needle, offset);
if (
candidate.index >= 0 &&
(next === undefined || candidate.index < next.index)
(next === undefined ||
candidate.index < next.index ||
(candidate.index === next.index &&
candidate.needle.length > next.needle.length))
)
next = candidate;
}
@@ -165,16 +337,23 @@ export class BrowserScenarioSecrets {
if (parts.length === 0) return value;
parts.push(value.subarray(offset));
const redacted = Buffer.concat(parts);
return literals.some((literal) => redacted.includes(Buffer.from(literal)))
const normalizedRedacted =
hasPercentPatterns && redacted.indexOf(37) >= 0
? normalizePercentEscapesBytes(redacted)
: redacted;
return containsSecretBytePattern(redacted, normalizedRedacted, candidates)
? Buffer.alloc(0)
: redacted;
}
/** Remove only declared secret values from one URL and report that action. */
sanitizeUrl(value: string): SanitizedBrowserUrl {
const literals = declaredLiterals(this.values, "url");
const output = replaceSecretLiterals(value, this.values, "url", literals);
if (literals.some((literal) => output.includes(literal)))
const patterns = this.urlPatterns;
if (patterns.length === 0) return sanitizeBrowserUrl(value);
const output = replaceSecretLiterals(value, this.urlReplacements, patterns);
if (
containsSecretPattern(output, normalizePercentEscapes(output), patterns)
)
return {
url: "",
origin: null,
@@ -189,14 +368,15 @@ export class BrowserScenarioSecrets {
}
fingerprint(value: string): BrowserStorageValueFingerprint {
for (const secret of this.values.values())
if (secret !== "" && value.includes(secret))
return { value_state: "redacted-secret", value_sha256: null };
const patterns = this.textPatterns;
if (
patterns.length > 0 &&
containsSecretPattern(value, normalizePercentEscapes(value), patterns)
)
return { value_state: "redacted-secret", value_sha256: null };
return {
value_state: "hashed",
value_sha256: createHash("sha256")
.update(this.redact(value))
.digest("hex"),
value_sha256: createHash("sha256").update(value).digest("hex"),
};
}
}
+96 -17
View File
@@ -1,4 +1,4 @@
import { request } from "node:http";
import { request, type ClientRequest, type IncomingMessage } from "node:http";
import { z } from "zod";
@@ -7,6 +7,7 @@ import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { urlDeclaresQueryOrFragment } from "../domain/urlComponents.js";
import { safeParseJson } from "../domain/safeJson.js";
const endpointVersionSchema = z.object({
@@ -28,6 +29,17 @@ const endpointTargetSchema = z.object({
});
const endpointTargetsSchema = z.array(endpointTargetSchema);
/** Per-response bounds for loopback CDP discovery documents. */
const CDP_DISCOVERY_RESPONSE_LIMITS = {
bytes: 8 * 1024 * 1024,
timeoutMs: 10_000,
} as const;
interface CdpDiscoveryResponseLimits {
readonly bytes: number;
readonly timeoutMs: number;
}
/** Validated direct CDP WebSocket bound to one discovered page target. */
interface CdpPageWebSocketEndpoint {
readonly scope: "page";
@@ -230,8 +242,7 @@ const safeCdpWebSocketEndpoint = (
parsed.port !== trustedEndpoint.port ||
parsed.username !== "" ||
parsed.password !== "" ||
parsed.search !== "" ||
parsed.hash !== "" ||
urlDeclaresQueryOrFragment(parsed) ||
path === undefined
)
throw new BrowserObservationError(operation, "invalid_endpoint_response");
@@ -291,29 +302,71 @@ export const readCdpJson = async (
url: URL,
operation: BrowserObservationOperation,
signal?: AbortSignal,
limits: CdpDiscoveryResponseLimits = CDP_DISCOVERY_RESPONSE_LIMITS,
): Promise<unknown> =>
await new Promise((resolve, reject) => {
if (signal?.aborted === true) {
reject(new AnalysisCancelledError(operation));
return;
}
const request_ = request(
let response: IncomingMessage | undefined;
let request_: ClientRequest | undefined;
let timer: NodeJS.Timeout | undefined;
let settled = false;
const removeAbort = (): void =>
signal?.removeEventListener("abort", onAbort);
const finish = (error?: Error, value?: unknown): void => {
if (settled) return;
settled = true;
if (timer !== undefined) clearTimeout(timer);
removeAbort();
if (error !== undefined) {
reject(error);
response?.destroy();
request_?.destroy();
} else resolve(value);
};
const onAbort = (): void => {
if (signal?.aborted === true)
finish(new AnalysisCancelledError(operation));
};
request_ = request(
url,
{ method: "GET", signal, headers: { Accept: "application/json" } },
(response) => {
if (response.statusCode !== 200) {
response.resume();
reject(
{ method: "GET", headers: { Accept: "application/json" } },
(received) => {
response = received;
if (settled) {
received.destroy();
return;
}
if (received.statusCode !== 200) {
finish(
new BrowserObservationError(operation, "invalid_endpoint_response"),
);
return;
}
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.on("end", () => {
const parsed = safeParseJson(Buffer.concat(chunks).toString("utf8"));
let bytes = 0;
received.on("data", (chunk: Buffer) => {
if (settled) return;
bytes += chunk.byteLength;
if (bytes > limits.bytes) {
finish(
new BrowserObservationError(operation, "payload_limit", {
detail: `CDP discovery response exceeds its ${String(limits.bytes)} byte limit.`,
}),
);
return;
}
chunks.push(chunk);
});
received.on("end", () => {
if (settled) return;
const parsed = safeParseJson(
Buffer.concat(chunks, bytes).toString("utf8"),
);
if (!parsed.ok) {
reject(
finish(
new BrowserObservationError(
operation,
"invalid_endpoint_response",
@@ -322,15 +375,41 @@ export const readCdpJson = async (
);
return;
}
resolve(parsed.value);
finish(undefined, parsed.value);
});
response.on("error", (cause: unknown) =>
reject(endpointFailure(cause, operation, signal)),
received.on("aborted", () =>
finish(
new BrowserObservationError(operation, "invalid_endpoint_response"),
),
);
received.on("close", () => {
if (!settled && !received.complete)
finish(
new BrowserObservationError(
operation,
"invalid_endpoint_response",
),
);
});
received.on("error", (cause: unknown) =>
finish(endpointFailure(cause, operation, signal)),
);
},
);
request_.on("error", (cause: unknown) =>
reject(endpointFailure(cause, operation, signal)),
finish(endpointFailure(cause, operation, signal)),
);
signal?.addEventListener("abort", onAbort, { once: true });
onAbort();
if (settled) return;
timer = setTimeout(
() =>
finish(
new BrowserObservationError(operation, "timeout", {
detail: `CDP discovery response exceeded its ${String(limits.timeoutMs)} ms deadline.`,
}),
),
limits.timeoutMs,
);
request_.end();
});
+4 -19
View File
@@ -17,6 +17,7 @@ import { mainFrameUrl } from "./CdpCaptureDocuments.js";
import { captureFrames } from "./CdpCaptureDocuments.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";
import { readPngHeaderDimensions } from "../domain/pngHeader.js";
interface ScreenshotContext {
readonly connection: CdpConnection;
@@ -94,7 +95,9 @@ export const captureCdpScreenshot = async (
encoded === undefined ? undefined : decodeCanonicalBase64(encoded);
if (bytes === undefined)
throw new BrowserObservationError("inspect_web_page", "payload_limit");
const dimensions = pngDimensions(bytes);
const dimensions = readPngHeaderDimensions(bytes);
if (dimensions === undefined)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
if (navigation.leftScope)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
const afterUrl = mainFrameUrl(after);
@@ -158,21 +161,3 @@ const observeScreenshotNavigation = (
if (allowedSanitizedUrl(frame?.url, origins) === undefined)
state.leftScope = true;
};
const pngDimensions = (
bytes: Buffer,
): { readonly width: number; readonly height: number } => {
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
const width = bytes.readUInt32BE(16);
const height = bytes.readUInt32BE(20);
if (width === 0 || height === 0)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
return { width, height };
};
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
@@ -1,4 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { dirname } from "node:path";
import * as processOwnership from "../process/ProcessOwnership.js";
import * as electronActions from "./PlaywrightElectronActiveActions.js";
@@ -28,12 +29,13 @@ it("passes the selected environment and ownership token to Electron launch", asy
throw new Error("launch boundary reached");
},
);
const result = await provider.capture(
electronActiveObservationInputSchema.parse({
const result = await provider.capture({
...electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: process.execPath,
}),
);
application_root: dirname(process.execPath),
});
expect(result.ok).toBe(false);
expect(launchedEnvironment).toEqual({
@@ -151,12 +153,13 @@ it("retains the partial capture without taskkill when Windows lineage is unavail
);
try {
const result = await provider.capture(
electronActiveObservationInputSchema.parse({
const result = await provider.capture({
...electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: process.execPath,
}),
);
application_root: dirname(process.execPath),
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected unverified cleanup to fail");
+10 -22
View File
@@ -1,5 +1,3 @@
import { realpath } from "node:fs/promises";
import { dirname } from "node:path";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
@@ -9,11 +7,11 @@ import type {
ExecutionOptions,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import type { ElectronActiveObservationPort } from "../application/javascript/ElectronActiveObservationPort.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../domain/javascript/electronActiveObservation.js";
CanonicalElectronActiveObservationInput,
ElectronActiveObservationPort,
} from "../application/javascript/ElectronActiveObservationPort.js";
import type { ElectronActiveObservationResult } from "../domain/javascript/electronActiveObservation.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
@@ -70,7 +68,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
}
async capture(
input: ElectronActiveObservationInput,
input: CanonicalElectronActiveObservationInput,
options: ExecutionOptions = {},
): Promise<Result<ElectronActiveObservationResult, AnalysisError>> {
let application: ElectronApplication | undefined;
@@ -89,7 +87,11 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
throw new BrowserObservationError(OPERATION, "cancelled");
await prepareProcessOwnershipInspection(options.signal);
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
paths = await canonicalPaths(input);
paths = {
executable: input.executable_path,
application: input.application_path,
root: input.application_root,
};
const captureBaseline =
await systemProcessOwnershipHost.captureBaseline?.(options.signal);
if (options.signal?.aborted)
@@ -353,20 +355,6 @@ export const cleanupElectronProcesses = async (
};
};
const canonicalPaths = async (
input: ElectronActiveObservationInput,
): Promise<ElectronPaths> => {
const [executable, application] = await Promise.all([
realpath(input.executable_path),
realpath(input.application_path),
]);
const root =
input.application_root === undefined
? dirname(application)
: await realpath(input.application_root);
return { executable, application, root };
};
const safeElectronEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
runId: string,
+73 -2
View File
@@ -5,6 +5,77 @@ import { browserScenarioSchema } from "../domain/browserScenario.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
describe("declared secrets in scenario events", () => {
it("redacts encoded declared secrets from text evidence and fingerprints", () => {
const listeners = new Map<string, (value: unknown) => void>();
const socketListeners = new Map<string, (value: unknown) => void>();
const page = {
on: (name: string, listener: (value: unknown) => void) => {
listeners.set(name, listener);
},
} as unknown as Page;
const secret = "a/b&c\n d";
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [
{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },
],
secrets: [
{ secret_id: "login_input", environment_variable: "REA_TEST_TOKEN" },
],
capture: { events: ["console", "page-errors", "websockets"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {
REA_TEST_TOKEN: secret,
});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
enabled: new Set(["console", "page-errors", "websockets"]),
secrets,
});
listeners.get("console")?.({
type: () => "log",
text: () => encodeURIComponent(secret),
location: () => ({ url: "https://app.example.test/app.js" }),
});
const escapedSecret = JSON.stringify(secret).slice(1, -1);
const error = new Error(`failure ${escapedSecret}`);
error.stack = `failure ${escapedSecret}`;
listeners.get("pageerror")?.(error);
listeners.get("websocket")?.({
url: () => "wss://app.example.test/socket",
on: (name: string, listener: (value: unknown) => void) => {
socketListeners.set(name, listener);
},
});
const formEncodedSecret = new URLSearchParams([["value", secret]])
.toString()
.slice("value=".length);
socketListeners.get("framesent")?.({ payload: formEncodedSecret });
const items = events.result().items;
expect(items).toMatchObject([
{ kind: "console", text: "[REDACTED:login_input]" },
{
kind: "page-error",
message: "failure [REDACTED:login_input]",
stack: "failure [REDACTED:login_input]",
},
{ kind: "websocket-opened" },
{
kind: "websocket-frame-sent",
payload_text: "[REDACTED:login_input]",
},
]);
expect(secrets.fingerprint(`stored ${encodeURIComponent(secret)}`)).toEqual(
{ value_state: "redacted-secret", value_sha256: null },
);
});
});
describe("PlaywrightScenarioEvents", () => {
it("observes requested popup page errors independently of popup lifecycle events", () => {
const listeners = new Map<string, (value: unknown) => void>();
@@ -42,7 +113,7 @@ describe("PlaywrightScenarioEvents", () => {
]);
});
it("bounds oversized page errors before validating captured events", () => {
it("retains oversized page errors without truncating their text", () => {
const listeners = new Map<string, (value: Error) => void>();
const page = {
url: () => "https://app.example.test/",
@@ -88,7 +159,7 @@ describe("PlaywrightScenarioEvents", () => {
const error = new Error("m".repeat(70_000));
error.stack = "s".repeat(300_000);
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
listeners.get("pageerror")?.(error);
expect(events.result().items[0]).toMatchObject({
kind: "page-error",
message: "m".repeat(70_000),
+78 -1
View File
@@ -82,6 +82,8 @@ const fixture = () => {
const page = Object.assign(new EventEmitter(), {
url: () => "about:blank",
goto: vi.fn(async () => undefined),
evaluate: vi.fn(async (_script: unknown) => false),
addInitScript: vi.fn(async (_script: unknown) => undefined),
context: () => context,
});
const context = Object.assign(new EventEmitter(), {
@@ -116,7 +118,7 @@ const fixture = () => {
settle: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
};
return { cleanup, storage: mocks.storage };
return { cleanup, page, storage: mocks.storage };
};
beforeEach(() => {
@@ -137,6 +139,81 @@ it("uses browser disconnect as terminal storage release after detach failure", a
expect(storage.close).toHaveBeenCalledTimes(1);
});
it("leaves attached service-worker state alone when the policy allows it", async () => {
const { cleanup, page } = fixture();
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "allow" },
});
const session = await PlaywrightScenarioSession.open(attached, {}, {});
expect(mocks.openBrowser).toHaveBeenCalledWith(
attached,
{},
expect.any(Object),
);
expect(page.evaluate).not.toHaveBeenCalled();
expect(page.addInitScript).not.toHaveBeenCalled();
await expect(session.close()).resolves.toBe("disconnected-external");
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("blocks new attached service-worker registration without removing existing registrations", async () => {
const { cleanup, page } = fixture();
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "block" },
});
const session = await PlaywrightScenarioSession.open(attached, {}, {});
expect(page.evaluate).toHaveBeenCalledTimes(2);
expect(page.addInitScript).toHaveBeenCalledTimes(1);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.stringContaining("service workers are blocked by scenario policy"),
);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.not.stringContaining("getRegistrations"),
);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.not.stringContaining("unregister"),
);
await expect(session.close()).resolves.toBe("disconnected-external");
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("rejects attached block when caller-owned registrations already exist", async () => {
const { cleanup, page } = fixture();
page.evaluate.mockResolvedValueOnce(true);
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "block" },
});
await expect(
PlaywrightScenarioSession.open(attached, {}, {}),
).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "target_not_allowed",
});
expect(page.addInitScript).not.toHaveBeenCalled();
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("preserves both cleanup failures and retries retained owners", async () => {
const { cleanup, storage } = fixture();
const detachFailure = new Error("CDP detach rejected");
+13 -7
View File
@@ -51,15 +51,18 @@ const installCookies = async (
};
const blockAttachedServiceWorkers = async (page: Page): Promise<void> => {
const controller = await page.evaluate(
"Boolean(navigator.serviceWorker?.controller)",
);
if (controller)
const hasServiceWorker = await page.evaluate(`(async () => {
if (!("serviceWorker" in navigator)) return false;
const serviceWorker = navigator.serviceWorker;
if (serviceWorker.controller !== null) return true;
return (await serviceWorker.getRegistrations()).length > 0;
})()`);
// An attached context belongs to the caller. Reject a block request when it
// already has a worker instead of unregistering that caller-owned resource.
if (hasServiceWorker)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
const blockRegistration = `(() => {
if (!("serviceWorker" in navigator)) return;
void navigator.serviceWorker.getRegistrations()
.then((registrations) => Promise.all(registrations.map((item) => item.unregister())));
Object.defineProperty(ServiceWorkerContainer.prototype, "register", {
configurable: false,
value: () => Promise.reject(new Error("service workers are blocked by scenario policy"))
@@ -77,7 +80,10 @@ const initializePage = async (
): Promise<void> => {
context.setDefaultTimeout(0);
context.setDefaultNavigationTimeout(0);
if (scenario.browser.mode === "connect")
if (
scenario.browser.mode === "connect" &&
scenario.environment.service_workers === "block"
)
await blockAttachedServiceWorkers(page);
await installCookies(context, scenario, secrets);
};
+494
View File
@@ -0,0 +1,494 @@
import {
readLinuxResourceLimits,
type LinuxResourceLimits,
} from "../process/LinuxResourceLimits.js";
import { parsePacketOutput } from "./parsePacketOutput.js";
import { randomUUID } from "node:crypto";
import { constants } from "node:fs";
import { access, mkdir, realpath, writeFile } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import {
createAnalysisExecution,
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import type { PacketCapturePort } from "../application/captures/PacketCaptureService.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
ArtifactAnalysisResources,
type ArtifactAnalysisRuntime,
} from "../process/ArtifactAnalysisResources.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { createEvidence } from "../domain/evidence.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import {
type InspectPacketCaptureInput,
packetCaptureSchema,
} from "../domain/captures/packetCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import {
runOwnedCommand,
OwnedCommandFailure,
} from "../process/OwnedCommand.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
const OPERATION = "inspect_packet_capture";
export const TSHARK_PROVIDER_IDENTITY = {
id: "tshark-capture",
name: "REA TShark capture adapter",
version: "tshark@4",
} as const;
// Bound the resident input copy and retained text before allocation/collection.
const LIMITS = {
input_bytes: 32 * 1024 * 1024,
output_bytes: 4 * 1024 * 1024,
command_timeout_ms: 30_000,
address_space_bytes: 1024 * 1024 * 1024,
file_bytes: 64 * 1024 * 1024,
cpu_seconds: 30,
} as const;
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
export class TsharkCaptureProvider implements PacketCapturePort {
readonly #resources: ArtifactAnalysisResources;
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<ArtifactAnalysisRuntime> = () =>
PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }),
readonly platform: NodeJS.Platform = process.platform,
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
) {
this.#resources = new ArtifactAnalysisResources(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
readArtifact,
readLimits,
{
message:
"A packet inspection is already active; retry after it completes.",
details: { max_concurrent_inspections: 1 },
},
);
}
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
return this.#resources.run(
() => this.#inspect(input, options),
options?.signal,
);
}
close(): Promise<void> {
return this.#resources.close();
}
async #inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
let phase:
| "configuration"
| "artifact"
| "workspace"
| "producer"
| "integrity" = "configuration";
let capturedOutput: AnalysisCapturedOutput | undefined;
let resourcePath = input.path;
let effectiveLimits: LinuxResourceLimits | undefined;
let root: ArtifactAnalysisRuntime | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
await this.#resources.release();
if (this.platform !== "linux")
throw new Error(
"Packet inspection requires Linux with util-linux prlimit and REA_TSHARK_COMMAND so expanded captures are processed under an enforced address-space limit.",
);
const configured = this.environment.REA_TSHARK_COMMAND ?? "";
if (!isAbsolute(configured))
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
const command = await realpath(configured);
await access(command, constants.X_OK);
const tool = await this.#resources.read(
command,
64 * 1024 * 1024,
options?.signal,
);
const configuredLimiter =
this.environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
if (!isAbsolute(configuredLimiter))
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
const limiter = await realpath(configuredLimiter);
await access(limiter, constants.X_OK);
const limiterIdentity = await this.#resources.read(
limiter,
64 * 1024 * 1024,
options?.signal,
);
effectiveLimits = await this.#resources.readLimits(LIMITS);
const limitArguments = [
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
"--core=0:0",
"--",
command,
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
const execute = async (args: readonly string[]) => {
const output = await runOwnedCommand(
{
command: limiter,
arguments: [...limitArguments, ...args],
...(root === undefined ? {} : { cwd: root.path }),
expectedCommand: null,
runId: `rea-tshark-${randomUUID()}`,
hostEnvironment: {
...this.environment,
WIRESHARK_CONFIG_DIR: configurationPath,
},
},
{
timeoutMs: LIMITS.command_timeout_ms,
diagnosticBytes: LIMITS.output_bytes,
acceptNonZeroExit: true,
},
{
...(options?.signal === undefined
? {}
: { signal: options.signal }),
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
},
);
capturedOutput = {
stdout: output.stdout.text,
stderr: output.stderr.text,
truncated: output.diagnosticTruncated ?? false,
exit_code: output.exitCode ?? null,
signal: output.signal ?? null,
};
// Finish bounded integrity checks after output; service handles late cancellation with Evidence.
const previousPhase = phase;
phase = "integrity";
resourcePath = command;
const current = await this.#resources.read(command, 64 * 1024 * 1024);
resourcePath = limiter;
const currentLimiter = await this.#resources.read(
limiter,
64 * 1024 * 1024,
);
if (currentLimiter.sha256 !== limiterIdentity.sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
limiter,
"Configured resource limiter changed during analysis.",
{ capturedOutput },
);
if (current.sha256 !== tool.sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
command,
"Configured TShark executable changed during analysis.",
{ capturedOutput },
);
phase = previousPhase;
resourcePath = input.path;
if (output.exitCode !== 0)
throw new ProviderAdapterError(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
{
diagnostics: {
exit_code: output.exitCode ?? null,
stdout: output.stdout.text,
stderr: output.stderr.text,
},
},
);
return output;
};
phase = "configuration";
const version = await execute(["--version"]);
if (
!/^TShark \(Wireshark\) 4\.[0-9]+\.[0-9]+(?:[ .(\r\n]|$)/u.test(
version.stdout.text,
)
)
throw new Error(
"Expected TShark 4.x; inspect the selected installation.",
);
phase = "artifact";
const selected = await this.#resources.read(
input.path,
LIMITS.input_bytes,
options?.signal,
);
phase = "workspace";
await writeFile(snapshotPath, selected.bytes, {
flag: "wx",
mode: 0o400,
});
phase = "producer";
const args = [
"-n",
"-r",
"capture",
"-T",
"json",
"--no-duplicate-keys",
"--temp-dir=.",
...(input.two_pass ? ["-2"] : []),
...(input.packet_limit === null
? []
: ["-c", String(input.packet_limit)]),
...(input.display_filter === null ? [] : ["-Y", input.display_filter]),
...input.decode_as.flatMap((value) => ["-d", value]),
...[...new Set(["frame.number", ...input.fields])].flatMap((field) => [
"-e",
field,
]),
];
const output = await execute(args);
phase = "integrity";
resourcePath = snapshotPath;
if (
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
.sha256 !== selected.sha256
)
throw new AnalysisArtifactChangedError(
OPERATION,
snapshotPath,
"TShark changed the private capture copy.",
capturedOutput === undefined ? {} : { capturedOutput },
);
phase = "producer";
resourcePath = input.path;
const matchingPackets = parsePacketOutput(
output.stdout.text,
input.fields,
);
const start = Math.min(input.match_offset, matchingPackets.length);
const end =
input.match_limit === null
? matchingPackets.length
: start + Math.min(input.match_limit, matchingPackets.length - start);
const packets = matchingPackets.slice(start, end);
const report = packetCaptureSchema.parse({
artifact: {
path: input.path,
sha256: selected.sha256,
bytes: selected.bytes.length,
},
selection: input,
packets,
output_window: {
matching_packets: matchingPackets.length,
returned_packets: packets.length,
has_more: end < matchingPackets.length,
},
read_scope:
input.packet_limit === null ? "to-eof" : "up-to-input-packet-limit",
configuration: "private-empty-personal-profile",
diagnostics: output.stderr.text,
tool: {
configured_path: configured,
path: command,
sha256: tool.sha256,
version_banner: version.stdout.text,
version_diagnostics: version.stderr.text,
arguments: args,
},
resource_limiter: {
configured_path: configuredLimiter,
path: limiter,
sha256: limiterIdentity.sha256,
arguments: limitArguments,
},
limits: { ...LIMITS, ...effectiveLimits },
hardware_acquisition: "not-performed",
});
result = ok(
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
subject: {
path: input.path,
sha256: selected.sha256,
format: "file",
},
locations: [{ kind: "artifact-path", path: input.path }],
limitations: [
"Fields are TShark dissector observations under the selected filter/decode-as/pass settings, not independently verified protocol semantics. Missing fields are absent from the producer output, not known zero or empty values.",
"Packet limits count input packets before display filtering. Filtered results do not establish whole-capture or device traffic absence. Two-pass reassembly cannot recover bytes missing from the recording or beyond the read limit.",
"Repeated field values remain ordered string arrays; raw packet bytes are included only when explicitly selected as a supported field. Export index/score metadata are omitted. All stderr, including warnings on exit zero, is retained.",
"A private empty personal configuration is used. Installed libraries, global configuration and dissector plugins are trusted and not fully fingerprinted. File-only analysis and disabled name resolution do not constitute an OS sandbox.",
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
],
}),
);
} catch (cause) {
if (
root !== undefined &&
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
phase,
resourcePath,
root?.path ?? null,
effectiveLimits,
capturedOutput,
),
);
}
return this.#resources.finish(result, (execution) =>
createEvidence(execution.subject ?? undefined, execution.provider, {
operation: OPERATION,
parameters: input,
result: execution.result,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
#failure(
cause: unknown,
phase:
| "configuration"
| "artifact"
| "workspace"
| "producer"
| "integrity",
path: string,
workspacePath: string | null,
effectiveLimits: LinuxResourceLimits | undefined,
observedOutput: AnalysisCapturedOutput | undefined,
): AnalysisError {
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return this.#resources.cleanupFailure(
cause.cleanup,
cause,
observedOutput,
);
if (
(cause instanceof Error && cause.name === "AbortError") ||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
)
return new AnalysisCancelledError(OPERATION, { cause });
const reason = cause instanceof Error ? cause.message : String(cause);
if (cause instanceof OwnedCommandFailure)
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
if (phase === "workspace") {
const code =
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
? cause.code
: null;
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
`Private analysis workspace failed (${code}): ${reason}`,
{ workspace_path: workspacePath, system_code: code },
{ cause },
);
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
cause,
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
diagnostics: {
stage: "workspace",
workspace_path: workspacePath,
system_code: code,
reason,
},
});
}
if (phase === "integrity") {
const detail = {
cause,
...(observedOutput === undefined
? {}
: { capturedOutput: observedOutput }),
};
if (
cause instanceof ArtifactReaderFailure &&
["limit", "integrity", "path"].includes(cause.reason)
)
return new AnalysisArtifactChangedError(
OPERATION,
path,
`Post-run identity verification failed for ${path}: ${reason}`,
detail,
);
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
...detail,
diagnostics: { stage: "integrity", resource_path: path, reason },
});
}
if (phase === "configuration")
return new AnalysisCapabilityUnavailableError(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
reason,
{
cause,
userMessage: `${reason} On Linux, configure TShark 4.x through REA_TSHARK_COMMAND and util-linux prlimit through REA_TSHARK_PRLIMIT_COMMAND (default /usr/bin/prlimit).`,
},
);
if (
phase === "artifact" &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "limit"
)
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
reason,
{ input_bytes: LIMITS.input_bytes },
{ cause },
);
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
cause,
});
if (
phase === "artifact" &&
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
if (phase === "artifact")
return new AnalysisInputError(OPERATION, { cause }, [
{ path: ["path"], reason: "invalid_value", message: reason },
]);
return new AnalysisOutputError(OPERATION, reason, { cause });
}
}
+29
View File
@@ -0,0 +1,29 @@
import { z } from "zod";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { packetFieldsSchema } from "../domain/captures/packetCapture.js";
// _index/_score are TShark export metadata, not captured packet fields.
const producerSchema = z.array(
z.object({ _source: z.object({ layers: packetFieldsSchema }) }),
);
export const parsePacketOutput = (text: string, fields: readonly string[]) => {
const decoded: unknown = JSON.parse(text);
const packets = producerSchema
.parse(decoded)
.map((packet) => packet._source.layers);
const selected = new Set(["frame.number", ...fields]);
let previous = 0n;
for (const packet of packets) {
const frame = BigInt(packet["frame.number"][0]);
if (
frame <= previous ||
Object.keys(packet).some((name) => !selected.has(name))
)
throw new AnalysisOutputError(
"inspect_packet_capture",
"TShark returned unordered frames or unselected fields.",
);
previous = frame;
}
return packets;
};
+27 -7
View File
@@ -5,20 +5,33 @@ import { z } from "zod";
import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";
import { TOOL_CONTRACTS } from "./contracts/toolContracts.js";
import type { ToolContract } from "./contracts/toolContractTypes.js";
import { CLI_COMMAND_NAMES } from "./cliCommandNames.js";
import { compareUnicodeCodePoints } from "./domain/unicodeCodePointOrder.js";
const sortedToolContracts = [...TOOL_CONTRACTS].sort((left, right) =>
compareUnicodeCodePoints(left.name, right.name),
);
const sortByName = (
contracts: readonly ToolContract[],
): readonly ToolContract[] =>
[...contracts].sort((left, right) =>
compareUnicodeCodePoints(left.name, right.name),
);
const createToolCatalog = () =>
sortedToolContracts.map((contract) => ({
const sortedToolContracts = sortByName(TOOL_CONTRACTS);
/**
* Digested per-tool projection. Every contract field that changes what a
* client receives belongs here, including `returns_target_content`: a server
* that predates the untrusted-content framing must not digest equal to one
* that emits `_meta.provenance`, or a stale process would report aligned.
*/
const createToolCatalog = (contracts: readonly ToolContract[]) =>
contracts.map((contract) => ({
name: contract.name,
title: contract.title,
surface: contract.kind,
description: contract.description,
effects: { ...contract.effects },
returns_target_content: contract.returnsTargetContent,
annotations: contract.annotations,
input_schema: {
type: "object",
@@ -49,8 +62,15 @@ const digest = (value: unknown): string => {
return createHash("sha256").update(encoded).digest("hex");
};
const createCatalogDigests = () => {
const tools = createToolCatalog();
/**
* Catalog digests over the given tool contracts. Exported so tests can prove
* which contract fields the identity covers; production uses
* {@link CATALOG_IDENTITY}.
*/
export const createCatalogDigests = (
contracts: readonly ToolContract[] = TOOL_CONTRACTS,
) => {
const tools = createToolCatalog(sortByName(contracts));
return {
tools_sha256: digest(tools),
prompts_sha256: digest(promptCatalog),
+5 -1
View File
@@ -1,3 +1,5 @@
import { registerCaptureCommands } from "./cli/captureCommands.js";
import { registerSignalCommands } from "./cli/signalCommands.js";
import { registerWasmCommands } from "./cli/wasmCommands.js";
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
@@ -44,7 +46,7 @@ import type { CliInstance } from "./cli/types.js";
import {
streamCliCommandResults,
type CliResultOutput,
} from "./cli/streamedJsonOutput.js";
} from "./cli/cliResultOutput.js";
/** Describe CLI settings that are invalid before any command runs, as MCP does. */
export const cliConfigurationError = (
@@ -94,6 +96,8 @@ export const createCli = (
registerCoreAnalysisCommands(cli, logger, analysis.runDirectAnalysis);
registerUtilityCommands(cli, logger, environment, analysis);
registerWasmCommands(cli, logger, environment);
registerCaptureCommands(cli, logger, environment);
registerSignalCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerGoCommands(cli, logger);
registerSqliteCommands(cli, logger, environment);
+99
View File
@@ -0,0 +1,99 @@
import { z } from "incur";
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { resolve } from "node:path";
import { createPacketCaptureService } from "../composition/captures.js";
import {
packetCaptureOptionsSchema,
packetCaptureSelectorBudgetIssue,
withinPacketCaptureSelectorBudget,
} from "../domain/captures/packetCapture.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
export const registerCaptureCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
service: Pick<
PacketCaptureService,
"inspect" | "close"
> = createPacketCaptureService(environment),
): void => {
cli.command(CLI_COMMANDS.inspectPacketCapture, {
description:
"Inspect an existing packet capture with caller-supplied TShark",
args: z.object({ path: z.string().describe("Local packet capture") }),
options: z
.object({
...packetCaptureOptionsSchema.shape,
match_limit: z
.number()
.int()
.positive()
.optional()
.describe("Returned matching frames per page; default 50"),
all_matches: z
.boolean()
.default(false)
.describe(
"Return all remaining matching frames instead of a bounded page",
),
})
.superRefine((options, context) => {
if (options.all_matches && options.match_limit !== undefined)
context.addIssue({
code: "custom",
path: ["all_matches"],
message: "all_matches and match_limit are mutually exclusive",
});
})
.refine(
withinPacketCaptureSelectorBudget,
packetCaptureSelectorBudgetIssue,
),
run: ({ args, options: { all_matches, ...options } }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectPacketCapture, async () => {
const result = await service.inspect(
{
...options,
...(all_matches ? { match_limit: null } : {}),
path: resolve(args.path),
},
{ signal },
);
// A one-shot command must retry retained cleanup before discarding its owner.
try {
await service.close();
} catch (cause) {
const cleanup =
cause instanceof AnalysisError
? cause
: new ProviderCleanupError(
"tshark-capture",
[],
{ reason: String(cause) },
{ cause, operation: "inspect_packet_capture" },
);
if (result.ok) cleanup.retainPartialObservation(result.value);
return projectAnalysisError(
result.ok
? cleanup
: analysisErrorWithCleanupFailure(
result.error,
cleanup,
"inspect_packet_capture",
),
);
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
@@ -1,15 +1,24 @@
import { constants } from "node:buffer";
import type { Writable } from "node:stream";
import { Cli, Filter } from "incur";
import { Cli, Filter, Formatter } from "incur";
import { estimateTokenCount, sliceByTokens } from "tokenx";
import { parseCliOutputArguments } from "../cliOutput.js";
import {
parseCliOutputArguments,
validateCliOutputArguments,
} from "../cliOutput.js";
import { cliOperationFailurePayload } from "../cliLogging.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
projectAnalysisError,
type AnalysisErrorProjection,
} from "../domain/analysisErrorProjection.js";
import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js";
import {
jsonOutputParts,
writeJsonOutput,
writeOutputText,
} from "./jsonOutput.js";
import type { CliInstance } from "./types.js";
/** Result metadata supplied by the command that actually ran. */
@@ -100,19 +109,15 @@ const wrapCommand = (
};
};
/** Preserve Incur's JSON controls while streaming the complete result. */
export const createStreamedCliJsonOutput = (
/** Preserve Incur output controls and stream JSON while framing failures. */
export const createCliResultOutput = (
arguments_: readonly string[],
destination: Writable,
): CliResultOutput | undefined => {
const options = parseCliOutputArguments(arguments_);
if (
options.parseError ||
options.tokenWindow ||
(options.format !== "json" && options.format !== "jsonl")
)
if (options.parseError || !validateCliOutputArguments(arguments_).ok)
return undefined;
const format = options.format;
const format = options.format as "json" | "jsonl" | "yaml" | "toon" | "md";
let handled = false;
let failed = false;
let error: AnalysisErrorProjection | undefined;
@@ -128,27 +133,53 @@ export const createStreamedCliJsonOutput = (
},
async write(value, metadata) {
if (metadata.format !== format) return false;
const failure = options.fullOutput
? cliOperationFailurePayload(value)
: undefined;
const filtered: unknown = options.filterOutput
? Filter.apply(value, Filter.parse(options.filterOutput))
: value;
const meta = {
command: metadata.command,
duration: metadata.duration,
};
// Leave successful YAML and bare YAML rendering to Incur. The custom
// boundary is needed only for a full failure envelope, whose error
// sentinel otherwise drops category, remediation, and details.
if (format !== "json" && format !== "jsonl" && failure === undefined)
return false;
if (options.tokenCount) {
// Incur/tokenx materialize the formatted value. Measure its UTF-16
// expansion before allowing that allocation, independently of UTF-8 bytes.
// Incur/tokenx materialize JSON. Measure its UTF-16 expansion before
// allowing that allocation, independently of UTF-8 bytes. Other formats
// retain Incur's materializing behavior.
const tokenValue = failure ?? filtered;
let characters = 0;
if (
filtered !== undefined &&
filtered !== null &&
typeof filtered !== "function" &&
typeof filtered !== "symbol"
)
for (const part of jsonOutputParts(filtered, format))
characters += part.length;
characters = Math.max(0, characters - 1);
if (characters <= constants.MAX_STRING_LENGTH) return false;
tokenValue !== undefined &&
tokenValue !== null &&
typeof tokenValue !== "function" &&
typeof tokenValue !== "symbol"
) {
if (format === "json" || format === "jsonl") {
for (const part of jsonOutputParts(
tokenValue,
format,
format === "json",
))
characters += part.length;
characters = Math.max(0, characters - 1);
}
}
if (characters <= constants.MAX_STRING_LENGTH) {
if (failure === undefined) return false;
handled = true;
try {
await writeOutputText(
destination,
`${estimateTokenCount(Formatter.format(failure, format))}\n`,
);
return true;
} catch (cause: unknown) {
failed = true;
throw cause;
}
}
error = projectAnalysisError(
new AnalysisResourceConstraintError(
metadata.command,
@@ -165,10 +196,26 @@ export const createStreamedCliJsonOutput = (
),
);
}
const meta = {
command: metadata.command,
duration: metadata.duration,
};
const errorDocument =
options.fullOutput && failure !== undefined
? fullFailureEnvelope(
failure,
meta,
format,
options.tokenLimit,
options.tokenOffset,
)
: undefined;
const document = options.fullOutput
? filtered === undefined
? { ok: true, meta }
: { ok: true, data: filtered, meta }
? failure !== undefined
? errorDocument
: filtered === undefined
? { ok: true, meta }
: { ok: true, data: filtered, meta }
: filtered === undefined ||
filtered === null ||
typeof filtered === "function" ||
@@ -179,15 +226,24 @@ export const createStreamedCliJsonOutput = (
// document from Incur's error formatter.
handled = true;
try {
await writeJsonOutput(
error === undefined
? document
: options.fullOutput
? { ok: false, error, meta }
: error,
destination,
format,
);
if (failure !== undefined && format !== "json" && format !== "jsonl") {
// Incur's error sentinel only carries code/message/retryable. Render
// the full caller-visible failure at this output boundary.
await writeOutputText(
destination,
`${Formatter.format(document, format)}\n`,
);
} else {
await writeJsonOutput(
error === undefined
? document
: options.fullOutput
? { ok: false, error, meta }
: error,
destination,
format as "json" | "jsonl",
);
}
} catch (cause: unknown) {
failed = true;
throw cause;
@@ -196,3 +252,26 @@ export const createStreamedCliJsonOutput = (
},
};
};
const fullFailureEnvelope = (
failure: unknown,
meta: Readonly<Record<string, unknown>>,
format: "json" | "jsonl" | "yaml" | "toon" | "md",
tokenLimit: number | undefined,
tokenOffset: number | undefined,
): Readonly<Record<string, unknown>> => {
if (tokenLimit === undefined && tokenOffset === undefined)
return { ok: false, error: failure, meta };
const formatted = Formatter.format(failure, format);
const total = estimateTokenCount(formatted);
const offset = tokenOffset ?? 0;
const end = tokenLimit === undefined ? total : offset + tokenLimit;
if (offset === 0 && end >= total) return { ok: false, error: failure, meta };
const actualEnd = Math.min(end, total);
const nextOffset = actualEnd < total ? actualEnd : undefined;
return {
ok: false,
error: `${sliceByTokens(formatted, offset, end)}\n[truncated: showing tokens ${offset}–${actualEnd} of ${total}]`,
meta: { ...meta, ...(nextOffset === undefined ? {} : { nextOffset }) },
};
};
+7
View File
@@ -82,6 +82,13 @@ export const renderSetupProgress = (event: SetupProgressEvent): void => {
writeLine(`${symbol} ${event.label}${suffix}`);
};
/** Show the resolved dry-run plan to a human at an interactive terminal. */
export const renderSetupDryRun = (actions: readonly SetupAction[]): void => {
intro("REA setup plan", promptStreams);
renderPreflight(actions);
outro("Dry run complete. No changes were made.", promptStreams);
};
/** Finish an interactive setup journey without exposing the full doctor catalog. */
export const renderInteractiveSetupResult = (
result: SetupResult,
+5 -2
View File
@@ -19,13 +19,16 @@ export const writeJsonOutput = async (
for (const part of bufferedJsonParts(
jsonOutputParts(value, format, isTerminal(destination)),
))
await writePart(destination, part);
await writeOutputText(destination, part);
};
const isTerminal = (destination: Writable): boolean =>
"isTTY" in destination && destination.isTTY === true;
const writePart = (destination: Writable, part: string): Promise<void> =>
export const writeOutputText = (
destination: Writable,
part: string,
): Promise<void> =>
new Promise((resolve, reject) => {
const onError = (cause: unknown): void => reject(cause);
destination.once("error", onError);
+6
View File
@@ -11,6 +11,7 @@ import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { isUpdateFailure } from "../application/UpdateFailure.js";
import {
confirmInteractiveSetup,
renderSetupDryRun,
renderInteractiveSetupResult,
renderSetupProgress,
} from "./interactiveSetup.js";
@@ -225,6 +226,8 @@ const runSetupCommand = async (
: undefined,
);
if (interactive) renderInteractiveSetupResult(result, environment);
else if (options.dryRun && !input.formatExplicit && hasInteractiveTerminal())
renderSetupDryRun(result.plannedActions);
return result;
};
@@ -282,6 +285,9 @@ const setupIsInteractive = (
!options.yes &&
!options.dryRun &&
!formatExplicit &&
hasInteractiveTerminal();
const hasInteractiveTerminal = (): boolean =>
process.stdin.isTTY === true &&
process.stdout.isTTY === true &&
process.stderr.isTTY === true;
+99
View File
@@ -0,0 +1,99 @@
import { z } from "incur";
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { resolve } from "node:path";
import { createSignalRecordingService } from "../composition/signals.js";
import {
signalRecordingOptionsSchema,
signalRecordingSelectorBudgetIssue,
withinSignalRecordingSelectorBudget,
} from "../domain/signals/signalRecording.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
export const registerSignalCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
service: Pick<
SignalRecordingService,
"decode" | "close"
> = createSignalRecordingService(environment),
): void => {
cli.command(CLI_COMMANDS.decodeSignalRecording, {
description:
"Decode an existing signal recording with caller-supplied sigrok",
args: z.object({ path: z.string().describe("Local signal recording") }),
options: z
.object({
...signalRecordingOptionsSchema.shape,
line_limit: z
.number()
.int()
.positive()
.optional()
.describe("Returned output lines per page; default 50"),
all_lines: z
.boolean()
.default(false)
.describe(
"Return all remaining output lines instead of a bounded page",
),
})
.superRefine((options, context) => {
if (options.all_lines && options.line_limit !== undefined)
context.addIssue({
code: "custom",
path: ["all_lines"],
message: "all_lines and line_limit are mutually exclusive",
});
})
.refine(
withinSignalRecordingSelectorBudget,
signalRecordingSelectorBudgetIssue,
),
run: ({ args, options: { all_lines, ...options } }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.decodeSignalRecording, async () => {
const result = await service.decode(
{
...options,
...(all_lines ? { line_limit: null } : {}),
path: resolve(args.path),
},
{ signal },
);
// A one-shot command must retry retained cleanup before discarding its owner.
try {
await service.close();
} catch (cause) {
const cleanup =
cause instanceof AnalysisError
? cause
: new ProviderCleanupError(
"sigrok-recording",
[],
{ reason: String(cause) },
{ cause, operation: "decode_signal_recording" },
);
if (result.ok) cleanup.retainPartialObservation(result.value);
return projectAnalysisError(
result.ok
? cleanup
: analysisErrorWithCleanupFailure(
result.error,
cleanup,
"decode_signal_recording",
),
);
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+1 -1
View File
@@ -255,7 +255,7 @@ const runReferenceSourceImport = async (
caller: "rea-cli",
policy,
importer: PRODUCT_IDENTITY.packageName,
importerVersion: null,
importerVersion: PRODUCT_IDENTITY.packageVersion,
},
resources,
),
+2
View File
@@ -1,5 +1,7 @@
/** Canonical names used by every one-shot CLI command registration. */
export const CLI_COMMANDS = Object.freeze({
inspectPacketCapture: "inspect-packet-capture",
decodeSignalRecording: "decode-signal-recording",
inspectWasmArtifact: "inspect-wasm-artifact",
inspectSqliteDatabase: "inspect-sqlite-database",
inspectEvmInterface: "inspect-evm-interface",
+63 -13
View File
@@ -12,20 +12,64 @@ import type { Logger } from "pino";
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Identify caller-visible CLI outcomes that mean the requested operation failed. */
export const isCliOperationFailure = (value: unknown): boolean => {
if (!isRecord(value)) return false;
if (
isRecord(value.error) &&
analysisErrorProjectionSchema.safeParse(value.error).success
)
return true;
if (analysisCliErrorEnvelopeSchema.safeParse(value).success) return true;
if (analysisErrorProjectionSchema.safeParse(value).success) return true;
if (value.healthy === false) return true;
return false;
const loggedFailures = new WeakMap<object, unknown>();
/** Return the canonical failure projection owned by the CLI result boundary. */
const projectCliOperationFailure = (
value: unknown,
): AnalysisErrorProjection | undefined => {
if (!isRecord(value)) return undefined;
const direct = analysisErrorProjectionSchema.safeParse(value);
if (direct.success) return value as AnalysisErrorProjection;
const envelope = analysisCliErrorEnvelopeSchema.safeParse(value);
if (envelope.success) {
const {
error: _label,
input_path: inputPath,
input_reason: inputReason,
...projection
} = value;
const parsed = projection as AnalysisErrorProjection;
if (typeof inputPath !== "string" && typeof inputReason !== "string")
return parsed;
return {
...parsed,
details: {
...parsed.details,
...(typeof inputPath === "string" ? { input_path: inputPath } : {}),
...(typeof inputReason === "string"
? { input_reason: inputReason }
: {}),
},
};
}
if (isRecord(value.error)) {
const nested = analysisErrorProjectionSchema.safeParse(value.error);
if (nested.success) return value.error as AnalysisErrorProjection;
}
return undefined;
};
/** Return the canonical projection or original record classified as failed. */
const inferCliOperationFailure = (value: unknown): unknown | undefined => {
const projection = projectCliOperationFailure(value);
if (projection !== undefined) return projection;
if (isRecord(value) && value.healthy === false) return value;
return undefined;
};
export const cliOperationFailurePayload = (
value: unknown,
): unknown | undefined => {
if (isRecord(value) && loggedFailures.has(value))
return loggedFailures.get(value);
return inferCliOperationFailure(value);
};
/** Identify caller-visible CLI outcomes that mean the requested operation failed. */
export const isCliOperationFailure = (value: unknown): boolean =>
cliOperationFailurePayload(value) !== undefined;
/** Log one CLI command with duration and a stable success or failure status. */
export const logCliCommand = async <Value>(
logger: Logger,
@@ -36,7 +80,13 @@ export const logCliCommand = async <Value>(
const startedAt = performance.now();
try {
const value = await execute();
const failed = isCommandFailure?.(value) ?? isCliOperationFailure(value);
const inferredFailure = inferCliOperationFailure(value);
const failed = isCommandFailure?.(value) ?? inferredFailure !== undefined;
if (isRecord(value))
loggedFailures.set(
value,
failed ? (inferredFailure ?? value) : undefined,
);
logger[failed ? "error" : "info"](
{
command,
+10 -3
View File
@@ -20,6 +20,8 @@ interface ParsedCliOutputArguments {
readonly parseError: boolean;
readonly tokenCount: boolean;
readonly tokenWindow: boolean;
readonly tokenLimit: number | undefined;
readonly tokenOffset: number | undefined;
}
/** Read effective Incur output controls at the executable boundary. */
@@ -30,14 +32,18 @@ export const parseCliOutputArguments = (
let filterOutput: string | undefined;
let fullOutput = false;
let tokenCount = false;
let tokenWindow = false;
let tokenLimit: number | undefined;
let tokenOffset: number | undefined;
const parsed = (parseError: boolean): ParsedCliOutputArguments => ({
filterOutput,
format,
fullOutput,
parseError,
tokenCount,
tokenWindow: parseError ? false : tokenWindow,
tokenWindow:
!parseError && (tokenLimit !== undefined || tokenOffset !== undefined),
tokenLimit: parseError ? undefined : tokenLimit,
tokenOffset: parseError ? undefined : tokenOffset,
});
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index];
@@ -71,7 +77,8 @@ export const parseCliOutputArguments = (
const numericValue = Number(value);
if (!Number.isFinite(numericValue) || value.trim() === "")
return parsed(true);
tokenWindow = true;
if (argument === "--token-limit") tokenLimit = numericValue;
else tokenOffset = numericValue;
index += 1;
}
continue;
+6
View File
@@ -0,0 +1,6 @@
import { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import { TsharkCaptureProvider } from "../captures/TsharkCaptureProvider.js";
export const createPacketCaptureService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): PacketCaptureService =>
new PacketCaptureService(new TsharkCaptureProvider(environment));
@@ -1,3 +1,4 @@
import { moduleKindForJavaScriptReference } from "../application/javascript/JavaScriptArtifactPathResolution.js";
import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js";
import { analyzeParsedJavaScriptStaticSourceSteps } from "../domain/javascript/javascriptStaticAnalysis.js";
import {
@@ -53,7 +54,10 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async (
);
await callbacks.phase("semantic");
const ir = await completeJavaScriptAnalysisSteps(
analyzeParsedJavaScriptSemanticsSteps(parsed),
analyzeParsedJavaScriptSemanticsSteps(
parsed,
moduleKindForJavaScriptReference(file.path, "static-import"),
),
);
parsed = null;
const module = projectJavaScriptModuleSemantics(ir);
+6
View File
@@ -0,0 +1,6 @@
import { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
import { SigrokRecordingProvider } from "../signals/SigrokRecordingProvider.js";
export const createSignalRecordingService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): SignalRecordingService =>
new SignalRecordingService(new SigrokRecordingProvider(environment));
+18 -6
View File
@@ -1,17 +1,29 @@
import { userInfo } from "node:os";
const firstNonempty = (...values: readonly (string | undefined)[]) =>
values.find(
(value): value is string => value !== undefined && value.length > 0,
);
/** Resolve the caller's selected home before consulting the host account. */
export const homeDirectoryFromEnvironment = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string => {
const windowsDriveHome =
environment.HOMEDRIVE !== undefined &&
environment.HOMEDRIVE.length > 0 &&
environment.HOMEPATH !== undefined &&
environment.HOMEPATH.length > 0
? `${environment.HOMEDRIVE}${environment.HOMEPATH}`
: undefined;
const selected =
platform === "win32"
? (environment.USERPROFILE ??
(environment.HOMEDRIVE !== undefined &&
environment.HOMEPATH !== undefined
? `${environment.HOMEDRIVE}${environment.HOMEPATH}`
: environment.HOME))
: (environment.HOME ?? environment.USERPROFILE);
? firstNonempty(
environment.USERPROFILE,
windowsDriveHome,
environment.HOME,
)
: firstNonempty(environment.HOME, environment.USERPROFILE);
return selected ?? userInfo().homedir;
};
+2 -2
View File
@@ -326,7 +326,7 @@ export const ADB_TOOL_CONTRACTS = [
name: "start_adb_app",
...toolContractMetadata("start_adb_app"),
description:
"Start one installed app by launching its declared launcher activity: the component is resolved through `cmd package resolve-activity --brief`, then started with `am start -n`. A device-mutating tool for dynamic-analysis workflows; pair with `read_adb_logcat` (pid filter) and `list_adb_processes` to observe the started app, and `stop_adb_app` to end the run.",
"Start one installed app's resolved launcher activity with `am start -W -n`. A device-mutating tool for dynamic analysis. The full wait report determines success; failures retain launch-attempt facts and raw output. Pair with `read_adb_logcat` (pid filter) and `list_adb_processes` to observe the app, and `stop_adb_app` to end the run.",
kind: "adb-provider",
inputSchema: adbInputSchemas.start_adb_app,
outputSchema: evidenceResultOf(adbResultSchemas.start_adb_app),
@@ -341,7 +341,7 @@ export const ADB_TOOL_CONTRACTS = [
name: "start_adb_activity",
...toolContractMetadata("start_adb_activity"),
description:
"Start an intent with `am start`: one action, optional data URI, optional explicit component, and up to 16 typed extras (string, boolean, int, long, float). A device-mutating tool; the activity manager's Starting/Error verdict is preserved verbatim.",
"Start an intent with `am start -W`: one action, optional data URI, optional explicit component, and up to 16 typed extras (string, boolean, int, long, float). A device-mutating tool; the full wait report determines success, with failed-attempt facts and raw output retained.",
kind: "adb-provider",
inputSchema: adbInputSchemas.start_adb_activity,
outputSchema: evidenceResultOf(adbResultSchemas.start_adb_activity),
+1 -1
View File
@@ -16,7 +16,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface or inspect_web_network_capture Evidence without repeating analysis. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, native, inventory, WASM and EVM sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface, inspect_managed_artifact or inspect_web_network_capture Evidence without repeating analysis. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, native, inventory, WASM, EVM and managed artifact sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
@@ -0,0 +1,31 @@
import {
inspectPacketCaptureInputSchema,
packetCaptureSchema,
} from "../../domain/captures/packetCapture.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
export const CAPTURE_TOOL_CONTRACTS = [
{
name: "inspect_packet_capture",
...toolContractMetadata("inspect_packet_capture"),
kind: "artifact-provider",
description:
"Inspect caller-selected fields in an existing local packet capture with TShark 4.x. Return 50 matching frames by default, with match_offset/match_limit paging and coverage counts; match_limit:null requests all remaining matches. Preserve repeated values, frame numbers, display filter, decode-as rules and pass mode in inline Evidence with source/tool identity and diagnostics. Optional packet_limit counts input packets before filtering; output paging does not shorten dissection or two-pass reassembly. Requires Linux, util-linux prlimit, and absolute REA_TSHARK_COMMAND. File-only analysis; no live capture or device communication. Missing fields or no matches do not establish absence of device traffic.",
inputSchema: inspectPacketCaptureInputSchema,
outputSchema: evidenceResultOf(packetCaptureSchema),
examples: [
{
title: "Inspect UDP exchanges in a recording",
input: {
path: "/artifacts/device.pcapng",
fields: ["ip.addr", "udp.port", "data.data"],
display_filter: "udp",
decode_as: [],
packet_limit: null,
two_pass: true,
},
},
],
},
] as const satisfies readonly ToolContract[];
+1 -1
View File
@@ -62,7 +62,7 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"binary_overview",
"Return native-binary metadata, every segment with its length, and exhaustive procedure/string counts. Use search_procedures, list_procedures, or analyze_function directly when you already know which procedure to inspect.",
"Return native-binary metadata, every segment with its length, and exhaustive procedure/string counts. When every provider-reported segment agrees on an analysis image base, return it as image_base so callers can relate provider addresses to their loader coordinates. Use search_procedures, list_procedures, or analyze_function directly when you already know which procedure to inspect.",
enhancedInputSchemas.binary_overview,
),
...FUNCTION_WORKFLOW_TOOL_CONTRACTS,
@@ -50,6 +50,7 @@ const observe = (digit: string, text: string) =>
result: dossier(text),
confidence: "derived",
authority: "shipped-artifact",
relationshipCoverage: { status: "complete" },
},
);
+13 -2
View File
@@ -6,6 +6,7 @@ import { managedOutputSchemas } from "../toolOutputSchemaGroups.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
import { localPathStringSchema } from "../../domain/localPath.js";
import { analysisDetailSchema } from "../analysisDetail.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
export const managedTargetInputSchema = z.strictObject({
@@ -20,6 +21,11 @@ export const managedTargetInputSchema = z.strictObject({
.optional(),
});
/** Delivery selection belongs only to artifact inspection, not member/native queries. */
export const managedArtifactInputSchema = managedTargetInputSchema.extend({
detail: analysisDetailSchema.unwrap().optional(),
});
/** Member inspection may select declaring types before members are decoded. */
export const managedMembersInputSchema = managedTargetInputSchema.extend({
type_names: z
@@ -61,15 +67,20 @@ export const MANAGED_TOOL_CONTRACTS = [
name: "inspect_managed_artifact",
...toolContractMetadata("inspect_managed_artifact"),
description:
"Open and classify an explicit managed PE/CLI path, or inspect the active managed target, then inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns complete inline inventories when metadata is admitted and explicit partial or malformed coverage otherwise.",
'Inspect an explicit PE/CLI path, or the selected managed target, without loading or executing target code. Omitted or complete detail returns complete metadata inventories with original coverage. Select detail: "summary" on the first call for complete identity, PE/CLI, classification with its evidence, module/MVID, assembly, frameworks, returned-collection counts, coverage/issues and limitations. It retains complete Evidence and returns a distinct linked inspect_analysis_view summary. Page original references/resources/attributes with view kind managed and normalized_result.parent_evidence_id. Counts cover producer-returned rows; partial, unavailable or malformed metadata remains explicit and tokens remain build-local.',
kind: "managed-provider",
inputSchema: managedTargetInputSchema,
inputSchema: managedArtifactInputSchema,
outputSchema,
examples: [
{
title: "Example inspect managed artifact request",
input: { path: "/tmp/Example.dll" },
},
{
title:
"Inspect identity and coverage without unrelated metadata inventories",
input: { path: "/tmp/Example.dll", detail: "summary" },
},
],
},
{
+1 -1
View File
@@ -139,7 +139,7 @@ export const SESSION_TOOL_CONTRACTS = [
),
session(
"list_unknowns",
"List every current residual-unknown head in deterministic ID order, with optional exact status, severity, and domain filters. Results are complete and inline. This is read-only; unresolved, contradicted, and non-truth dispositions remain distinct.",
"List current residual-unknown heads in deterministic ID order, with optional exact status, severity, and domain filters. Results are complete inline by default; supply offset and limit to page the filtered order. total is the matching-head count and next_offset is null when the page exhausts the result. This is read-only; unresolved, contradicted, and non-truth dispositions remain distinct.",
listUnknownsInputSchema,
),
session(
+16
View File
@@ -52,6 +52,22 @@ export const listUnknownsInputSchema = z.strictObject({
.optional(),
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
domain: z.string().trim().min(1).optional(),
offset: z
.number()
.int()
.min(0)
.max(Number.MAX_SAFE_INTEGER)
.default(0)
.describe("Zero-based offset in the stable filtered unknown ID order."),
limit: z
.number()
.int()
.positive()
.max(Number.MAX_SAFE_INTEGER)
.optional()
.describe(
"Optional maximum number of heads to return. Omit to return every matching head from offset.",
),
});
/** Exact residual-unknown identity to revalidate. */
@@ -0,0 +1,29 @@
import {
decodeSignalRecordingInputSchema,
signalRecordingSchema,
} from "../../domain/signals/signalRecording.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
export const SIGNAL_TOOL_CONTRACTS = [
{
name: "decode_signal_recording",
...toolContractMetadata("decode_signal_recording"),
kind: "artifact-provider",
description:
"Decode an existing local logic/signal recording on Linux with sigrok-cli 0.7.2 and util-linux prlimit. Supply decoder stack, channels and options explicitly; optionally select input format and annotation classes. Return 50 literal output lines by default, with line_offset/line_limit paging; line_limit:null requests all remaining lines. Output windows count display lines, not annotations or samples, and do not shorten decoding. Preserve selected text, sample ranges, stderr, source/tool identity and coverage inline. Configure absolute REA_SIGROK_COMMAND. File-only analysis; no hardware acquisition or device communication. Empty output does not prove absence of traffic.",
inputSchema: decodeSignalRecordingInputSchema,
outputSchema: evidenceResultOf(signalRecordingSchema),
examples: [
{
title: "Decode recorded UART RX bytes",
input: {
path: "/artifacts/uart.vcd",
input_format: "vcd",
decoders: "uart:rx=RX:baudrate=9600",
annotations: "uart=rx-data",
},
},
],
},
] as const satisfies readonly ToolContract[];
+5
View File
@@ -58,5 +58,10 @@ export interface ToolContract<
readonly outputSchema: OutputSchema;
readonly effects: ToolEffects;
readonly annotations: ToolAnnotations;
/**
* Results, successful or failed, can contain text that originates from the
* analysis target. MCP delivery marks such results as untrusted data.
*/
readonly returnsTargetContent: boolean;
readonly examples: readonly ToolExample[];
}
+4
View File
@@ -1,3 +1,5 @@
import { CAPTURE_TOOL_CONTRACTS } from "./captures/captureToolContracts.js";
import { SIGNAL_TOOL_CONTRACTS } from "./signals/signalToolContracts.js";
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
@@ -39,6 +41,8 @@ export const TOOL_CONTRACTS = [
...GO_TOOL_CONTRACTS,
...WASM_TOOL_CONTRACTS,
...SQLITE_TOOL_CONTRACTS,
...CAPTURE_TOOL_CONTRACTS,
...SIGNAL_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...APKTOOL_TOOL_CONTRACTS,
+36
View File
@@ -59,6 +59,16 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
writesFilesystem: true,
launchesProcess: true,
}),
inspect_packet_capture: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
decode_signal_recording: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
inspect_wasm_artifact: effects({
mutatesSession: true,
writesFilesystem: true,
@@ -628,6 +638,31 @@ export const annotationsFromEffects = (
openWorldHint: value.launchesProcess || value.accessesNetwork,
});
/**
* Tools whose results, successful or failed, carry only REA-authored session
* state or caller-supplied values, never text originating from an analysis
* target, a provider, a launcher or a device. Every other tool can return
* such text (strings, symbols, code, page text, scripts, captures, logs, file
* listings, provider diagnostics or captured process output), so a newly
* added tool is marked untrusted until it is audited into this set. A tool
* stays out when any error path can project external process output, as
* close_binary (provider cleanup diagnostics), binary_session (provider
* failure reasons and availability diagnostics) and the adb and apktool
* client probes (version output and stderr excerpts) can.
*/
export const TARGET_CONTENT_FREE_TOOLS: ReadonlySet<string> = new Set([
"export_evidence_bundle",
"record_unknown",
]);
/**
* Whether results of the named tool, successful or failed, can carry text that
* originates from the analysis target. Unknown names are treated as target
* content so an unaudited path never loses the untrusted marker.
*/
export const toolReturnsTargetContent = (name: string): boolean =>
!TARGET_CONTENT_FREE_TOOLS.has(name);
/** Resolve the audited metadata for one public tool. */
export const toolContractMetadata = (name: string) => {
const audited = TOOL_EFFECTS[name];
@@ -640,5 +675,6 @@ export const toolContractMetadata = (name: string) => {
.join(" "),
effects: audited,
annotations: annotationsFromEffects(audited),
returnsTargetContent: toolReturnsTargetContent(name),
};
};
+13 -2
View File
@@ -1,5 +1,8 @@
import { z } from "zod";
import { artifactInventorySummaryViewResultSchema } from "../domain/analysisView/analysisView.js";
import {
artifactInventorySummaryViewResultSchema,
managedArtifactSummaryViewResultSchema,
} from "../domain/analysisView/analysisView.js";
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
import {
@@ -364,6 +367,7 @@ export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
segment_count: z.number().int().min(0),
procedure_count: z.number().int().min(0),
string_count: z.number().int().min(0),
image_base: z.string().min(1).optional(),
}),
),
analyze_function: functionDossierOutput,
@@ -401,7 +405,12 @@ export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
/** Exact Evidence schema for execution-free managed static analysis. */
export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_artifact: evidenceResultOf(managedArtifactInspectionSchema),
inspect_managed_artifact: evidenceResultOf(
z.union([
managedArtifactInspectionSchema,
managedArtifactSummaryViewResultSchema,
]),
),
inspect_managed_members: evidenceResultOf(managedMemberInspectionSchema),
inspect_managed_native_boundaries: evidenceResultOf(
managedNativeBoundaryInspectionSchema,
@@ -546,6 +555,8 @@ export const sessionOutputSchemas = {
z.object({
items: z.array(residualUnknownSchema),
total: z.number().int().min(0),
offset: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
}),
),
record_unknown: lifecycleResultOf(residualUnknownSchema),
+1 -1
View File
@@ -2,7 +2,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
/** Exact example inputs for residual-unknown lifecycle contracts. */
export const UNKNOWN_CONTRACT_EXAMPLES = {
list_unknowns: {},
list_unknowns: { offset: 0, limit: 50 },
record_unknown: {
question: "Does this branch require an unavailable external service?",
severity: "medium",
+17
View File
@@ -679,6 +679,8 @@ export const adbResultSchemas = {
package_name: packageNameSchema,
component: z.string().min(1),
started_activity: z.string().nullable(),
reported_activity: z.string().nullable().optional(),
reported_status: z.string().nullable().optional(),
}),
start_adb_activity: z.strictObject({
client,
@@ -694,6 +696,8 @@ export const adbResultSchemas = {
}),
),
started_activity: z.string().nullable(),
reported_activity: z.string().nullable().optional(),
reported_status: z.string().nullable().optional(),
}),
stop_adb_app: z.strictObject({
client,
@@ -702,6 +706,19 @@ export const adbResultSchemas = {
}),
} as const;
/** Launch-attempt facts retained when Activity Manager does not report success. */
export type AdbActivityStartPartialObservation =
| {
readonly provider_id: "adb";
readonly operation: "start_adb_app";
readonly result: z.infer<typeof adbResultSchemas.start_adb_app>;
}
| {
readonly provider_id: "adb";
readonly operation: "start_adb_activity";
readonly result: z.infer<typeof adbResultSchemas.start_adb_activity>;
};
/** Acquired package facts retained when cancellation leaves caller-owned output. */
export type AdbPackagePullPartialObservation = {
readonly provider_id: "adb";
+2
View File
@@ -114,6 +114,7 @@ import type { Evidence } from "./evidence.js";
import type { AndroidPartialObservation } from "./android/androidPartialObservation.js";
import type { FirmwarePartialObservation } from "./firmware/firmwareAnalysis.js";
import type {
AdbActivityStartPartialObservation,
AdbAcquiredFilePartialObservation,
AdbPackagePullPartialObservation,
} from "./adb/adbDeviceAnalysis.js";
@@ -143,5 +144,6 @@ export type AnalysisPartialObservation =
| AndroidPartialObservation
| FirmwarePartialObservation
| NativeUiObservationResult
| AdbActivityStartPartialObservation
| AdbAcquiredFilePartialObservation
| AdbPackagePullPartialObservation;
@@ -733,6 +733,14 @@ it("does not match unavailable layout names using a display placeholder", () =>
});
it("rejects unsupported parent operations and incompatible collections", () => {
expect(
projectAnalysisView(layoutParent(), {
kind: "managed",
collection: "attributes",
offset: 0,
limit: 1,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const unsupported = projectAnalysisView(
{
evidenceId: `ev_${"d".repeat(64)}`,
+43 -15
View File
@@ -42,6 +42,13 @@ import {
evmSummarySchema,
} from "./evmInterfaceView.js";
import { projectArtifactInventoryView } from "./artifactInventoryView.js";
import {
projectManagedArtifactView,
managedViewRequestSchema,
managedViewItemSchema,
managedSummarySchema,
managedViewContextSchema,
} from "./managedArtifactView.js";
import {
projectWasmArtifactView,
wasmViewRequestSchema,
@@ -161,6 +168,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
inventoryViewSchema,
wasmViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
apiSurfaceViewSchema,
]);
@@ -274,6 +282,7 @@ const viewResultBase = {
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -324,6 +333,13 @@ export const evmInterfaceSummaryViewResultSchema = z.strictObject({
summary: evmSummarySchema,
});
/** Exact metadata overview for the managed artifact's selected delivery. */
export const managedArtifactSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_managed_artifact"),
summary: managedSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -345,6 +361,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
inventorySummarySchema,
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
]),
}),
z.strictObject({
@@ -385,6 +402,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_evm_interface"),
}),
z.strictObject({
kind: z.literal("managed"),
view: managedViewRequestSchema,
item: managedViewItemSchema,
...viewResultBase,
...managedViewContextSchema.shape,
parent_operation: z.literal("inspect_managed_artifact"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -451,7 +476,11 @@ export type UnsignedAnalysisView =
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">;
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
export const sealAnalysisView = (
@@ -496,7 +525,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -520,6 +549,15 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
return parent.evidenceId;
};
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
/** Project one selected view from authenticated parent analysis Evidence. */
export const projectAnalysisView = (
parent: AnalysisViewParent,
@@ -591,19 +629,9 @@ export const projectAnalysisView = (
const projected = projectNativeFunctionView(parent, native.data, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_wasm_artifact") {
const projected = projectWasmArtifactView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_evm_interface") {
const projected = projectEvmInterfaceView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (
parent.operation === "inspect_artifact" ||
parent.operation === "inventory_artifact"
) {
const projected = projectArtifactInventoryView(parent, view);
const project = retainedViewProjectors.get(parent.operation);
if (project !== undefined) {
const projected = project(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
return err(unsupportedParent(parent));
@@ -218,6 +218,12 @@ export const projectBinaryLayoutView = (
...shared,
});
}
if (view.kind !== "page")
return err(
layoutIncompatible(
"Layout views require summary, facet, item or page selections.",
),
);
if (view.collection === "modules")
return err(
layoutIncompatible(
@@ -0,0 +1,140 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../managed/managedArtifact.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
/** Original metadata rows; offsets count entries in the returned parent collection. */
export const managedViewRequestSchema = z.strictObject({
kind: z.literal("managed"),
collection: z.enum(["references", "resources", "attributes"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
export const managedViewItemSchema = z.union([
managedArtifactInspectionSchema.shape.references,
managedArtifactInspectionSchema.shape.resources,
managedArtifactInspectionSchema.shape.attributes,
]);
/** Keep complete classification and coverage; unrequested inventories remain retained. */
export const managedSummarySchema = managedArtifactInspectionSchema
.omit({ references: true, resources: true, attributes: true })
.extend({
reported_counts: z.strictObject({
references: z.number().int().nonnegative(),
resources: z.number().int().nonnegative(),
attributes: z.number().int().nonnegative(),
}),
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
});
export const managedViewContextSchema = z.strictObject({
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
source_metadata_status:
managedArtifactInspectionSchema.shape.metadata.shape.status,
source_coverage: managedArtifactInspectionSchema.shape.coverage,
});
/** Project authenticated metadata without reading a path or invoking a provider. */
export const projectManagedArtifactView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "managed")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Managed artifact inspection supports summary and managed views.",
},
]),
);
const parsed = managedArtifactInspectionSchema.safeParse(
parent.normalizedResult,
);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
const identity_scope = {
token_identity: "build-local" as const,
requires_artifact_sha256: report.artifact.sha256,
requires_mvid: report.module?.mvid ?? null,
};
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_managed_artifact" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: uniqueSorted([...parent.limitations, ...report.limitations]),
unknowns: [
"Collection counts and pages cover producer-returned rows; metadata completeness remains the original metadata status and coverage, not an absence claim about unreturned rows.",
"Metadata tokens are build-local coordinates bound to the recorded artifact SHA-256 and module MVID; this view does not load or execute the assembly.",
...(parent.subject == null
? [
"The parent has no recorded subject; its normalized artifact identity cannot be cross-checked against a subject digest.",
]
: []),
...(identity_scope.requires_mvid === null
? [
"The module MVID is unknown; tokens cannot establish a cross-observation module match.",
]
: []),
],
};
if (view.kind === "summary") {
const { references, resources, attributes, ...summary } = report;
const reported_counts = {
references: references.length,
resources: resources.length,
attributes: attributes.length,
};
const total = references.length + resources.length + attributes.length;
return ok({
kind: "summary",
view,
...shared,
summary: { ...summary, reported_counts, identity_scope },
coverage: completeWithinViewCoverage(total, total),
});
}
const collection = report[view.collection];
const item = collection.slice(view.offset, view.offset + view.limit);
return ok({
kind: "managed",
view,
item,
...shared,
identity_scope,
source_metadata_status: report.metadata.status,
source_coverage: report.coverage,
coverage: pageViewCoverage(view.offset, item.length, collection.length),
});
};
+7 -3
View File
@@ -1,6 +1,9 @@
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
} from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
@@ -62,6 +65,7 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
@@ -95,8 +99,8 @@ export const projectAndroidApplication = (
);
const components = classified;
const limitations = [
...(!inventory.complete
? ["Source inventory pages are incomplete; absence is unknown."]
...(!hasCompleteInventoryCoverage(inventory)
? ["Source inventory coverage is partial; absence is unknown."]
: []),
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.",
@@ -138,6 +138,7 @@ const inventoryEvidence = (
occurrences: sortedOccurrences,
edges: [],
provenance: [],
coverage_status: "complete",
limitations: [],
}),
},
+9 -4
View File
@@ -17,7 +17,10 @@ import {
isSwiftRuntimeLibrary,
nativeRuntimeConvention,
} from "../nativeConvention.js";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
} from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
@@ -88,6 +91,7 @@ export const appleApplicationProjectionResultSchema = z.strictObject({
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
// Count completeness is separate from the declared coverage status.
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
@@ -165,9 +169,10 @@ export const projectAppleApplication = (
);
const uninventoriedImage =
rootFormat === "dmg" && inventory.occurrences.length === 1;
const complete = inventory.complete && !uninventoriedImage;
const inventoryComplete = hasCompleteInventoryCoverage(inventory);
const complete = inventoryComplete && !uninventoriedImage;
const limitations = projectionLimitations({
complete: inventory.complete,
complete: inventoryComplete,
uninventoriedImage,
roots,
bundles,
@@ -390,7 +395,7 @@ const projectionLimitations = (facts: {
readonly bridgeCandidateCoverage: AppleApplicationProjectionResult["bridge_candidate_coverage"];
}): string[] => [
...(!facts.complete
? ["Source inventory pages are incomplete; absence is unknown."]
? ["Source inventory coverage is partial; absence is unknown."]
: []),
...(facts.uninventoriedImage
? [
+12
View File
@@ -0,0 +1,12 @@
const BINARY_PLIST_MAGIC = [0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30];
const NIB_ARCHIVE_MAGIC = [
0x4e, 0x49, 0x42, 0x41, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65,
];
/** Recognize the exact binary plist version supported by the decoder, without validating its body. */
export const hasBinaryPlistSignature = (bytes: Uint8Array): boolean =>
BINARY_PLIST_MAGIC.every((byte, index) => bytes[index] === byte);
/** Recognize the serialized signature without claiming a valid NIB object table. */
export const hasNibArchiveSignature = (bytes: Uint8Array): boolean =>
NIB_ARCHIVE_MAGIC.every((byte, index) => bytes[index] === byte);
+13 -3
View File
@@ -3,6 +3,7 @@ import type {
DylibTreeView,
MachoSlice,
} from "./dylibResolution.js";
import { machoCpuSubtypeBase } from "./machoCpuIdentity.js";
const MAX_SYMLINK_HOPS = 32;
@@ -105,10 +106,19 @@ const COMPATIBLE_ARCHITECTURES: Readonly<Record<string, readonly string[]>> = {
export const compatibleSlice = (
slices: readonly MachoSlice[],
process: string,
process: Pick<MachoSlice, "architecture" | "cpu_type" | "cpu_subtype">,
): MachoSlice | undefined => {
for (const architecture of COMPATIBLE_ARCHITECTURES[process] ?? [process]) {
const slice = slices.find((item) => item.architecture === architecture);
for (const architecture of COMPATIBLE_ARCHITECTURES[process.architecture] ?? [
process.architecture,
]) {
const slice = slices.find(
(item) =>
item.architecture === architecture &&
(process.architecture !== "arm64e" ||
(item.cpu_type === process.cpu_type &&
machoCpuSubtypeBase(item.cpu_subtype) ===
machoCpuSubtypeBase(process.cpu_subtype))),
);
if (slice !== undefined) return slice;
}
return undefined;
+14 -7
View File
@@ -220,7 +220,10 @@ interface LoadedImage {
interface ProcessContext {
readonly view: DylibTreeView;
readonly root: string;
readonly architecture: string;
readonly processIdentity: Pick<
MachoSlice,
"architecture" | "cpu_type" | "cpu_subtype"
>;
readonly searchOverrides: readonly DyldSearchOverride[];
readonly environmentRoots: Set<string>;
readonly platforms: readonly number[];
@@ -304,7 +307,7 @@ const evaluateCandidate = async (
let outcome: Candidate["outcome"];
if (facts.status !== "parsed") outcome = facts.status;
else {
const slice = compatibleSlice(facts.slices, context.architecture);
const slice = compatibleSlice(facts.slices, context.processIdentity);
if (slice === undefined) outcome = "architecture-missing";
// Dependency commands require a dylib; generic dyld image loadability
// also admits main executables and bundles for different operations.
@@ -314,7 +317,7 @@ const evaluateCandidate = async (
context.platforms,
slice.platforms,
slice.file_type_code,
context.architecture,
context.processIdentity.architecture,
);
outcome =
platformResult === "compatible"
@@ -470,11 +473,11 @@ const resolveDependency = async (
resolved.image === null ? undefined : context.images.get(resolved.image);
const slice =
image?.status === "parsed"
? compatibleSlice(image.slices, context.architecture)
? compatibleSlice(image.slices, context.processIdentity)
: undefined;
return {
root: context.root,
architecture: context.architecture,
architecture: context.processIdentity.architecture,
loader,
via: [...chain],
...dependency,
@@ -522,7 +525,7 @@ const traceProcess = async (
const facts = context.images.get(image);
const slice =
facts?.status === "parsed"
? compatibleSlice(facts.slices, context.architecture)
? compatibleSlice(facts.slices, context.processIdentity)
: undefined;
if (slice === undefined) continue;
context.loaded.set(image, {
@@ -593,7 +596,11 @@ export const traceDylibLoading = async (
{
view,
root,
architecture: slice.architecture,
processIdentity: {
architecture: slice.architecture,
cpu_type: slice.cpu_type,
cpu_subtype: slice.cpu_subtype,
},
searchOverrides,
environmentRoots,
platforms: slice.platforms,
@@ -34,6 +34,16 @@ const connection = z.strictObject({
type InterfaceBuilderObject = z.infer<typeof objectNode>;
type InterfaceBuilderConnection = z.infer<typeof connection>;
/** UIKit runtime connection classes store their endpoints and labels under UI-prefixed keys. */
export const isUIKitRuntimeConnectionClass = (className: string): boolean =>
/^UIRuntime\w*Connection$/u.test(className);
/** The connection class selects the source archive field namespace. */
export const interfaceBuilderConnectionFieldNames = (className: string) =>
isUIKitRuntimeConnectionClass(className)
? { source: "UISource", destination: "UIDestination", label: "UILabel" }
: { source: "NSSource", destination: "NSDestination", label: "NSLabel" };
/** Parse ibtool dictionaries or compiled keyed archives into typed records. */
export const parseInterfaceBuilderRecords = (
value: unknown,
@@ -349,35 +359,41 @@ const parseKeyedArchive = (
)
) {
const controlAction = /ControlConnector/iu.test(className);
// AppKit connectors (NSNibOutletConnector, NSNibControlConnector)
// archive NSSource as the outlet owner or sending control and
// NSDestination as the outlet value or action target, so they are read
// in that order without the inversion the unprefixed fields use.
const source = firstObjectReference(
controlAction ? fields.destination : fields.source,
archivedObjectReference(fields.NSSource),
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
const uiKit = isUIKitRuntimeConnectionClass(className);
// AppKit and UIKit archive the same endpoint roles under their own
// class-specific field namespaces; the source is the outlet owner.
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = uiKit
? archivedObjectReference(fields[connectionFields.source])
: firstObjectReference(
controlAction ? fields.destination : fields.source,
archivedObjectReference(fields[connectionFields.source]),
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
kind,
source_id: source,
destination_id: firstObjectReference(
controlAction ? fields.source : fields.destination,
archivedObjectReference(fields.NSDestination),
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: firstString(
fields.label,
fields.NSLabel,
fields.selector,
fields.identifier,
fields.action,
),
destination_id: uiKit
? archivedObjectReference(fields[connectionFields.destination])
: firstObjectReference(
controlAction ? fields.source : fields.destination,
archivedObjectReference(fields[connectionFields.destination]),
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: uiKit
? firstString(fields[connectionFields.label])
: firstString(
fields.label,
fields[connectionFields.label],
fields.selector,
fields.identifier,
fields.action,
),
attributes: jsonSafeRecord(fields),
});
if (connections.length < 40_000) connections.push(parsedConnection);
+170 -11
View File
@@ -8,6 +8,136 @@ export interface FatSliceDeclaration {
readonly cpuSubtype: number;
}
export interface FatSliceRangeIssue {
readonly category: "malformed" | "unsupported";
readonly reason: string;
}
export type FatContainerHeader =
| { readonly state: "not-fat" }
| { readonly state: "needs-data"; readonly requiredBytes: number }
| { readonly state: "malformed"; readonly reason: string }
| {
readonly state: "parsed";
readonly magic: number;
readonly count: number;
readonly wide: boolean;
readonly littleEndian: boolean;
readonly tableEnd: number;
readonly slices: readonly FatSliceDeclaration[];
readonly rangeIssues: readonly (FatSliceRangeIssue | null)[];
};
export type FatContainerIdentity =
| { readonly state: "mach-o" }
| { readonly state: "not-mach-o" }
| {
readonly state: "needs-slice-header";
readonly offsets: readonly number[];
}
| {
readonly state: "malformed";
readonly category: "malformed" | "unsupported";
readonly reason: string;
};
const FAT_MAGIC = 0xcafebabe;
const FAT_MAGIC_64 = 0xcafebabf;
const FAT_CIGAM = 0xbebafeca;
const FAT_CIGAM_64 = 0xbfbafeca;
const MAX_FAT_ARCHITECTURES = 128;
const KNOWN_MACHO_CPU_TYPES: readonly number[] = [
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
];
const MACHO_HEADER_MAGICS: readonly number[] = [
0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe,
];
/** Parse a bounded FAT header and table without treating the magic alone as proof. */
export const readFatContainerHeader = (
bytes: Uint8Array,
fileSize: number,
): FatContainerHeader => {
if (bytes.byteLength < 4) return { state: "not-fat" };
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const magic = view.getUint32(0, false);
if (![FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic))
return { state: "not-fat" };
if (bytes.byteLength < 8) {
return fileSize < 8
? { state: "malformed", reason: "FAT header is truncated" }
: { state: "needs-data", requiredBytes: 8 };
}
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
const count = view.getUint32(4, littleEndian);
if (count === 0)
return {
state: "malformed",
reason: "FAT header declares no architectures",
};
if (count > MAX_FAT_ARCHITECTURES) return { state: "not-fat" };
const tableEnd = 8 + count * (wide ? 32 : 20);
if (tableEnd > fileSize) return { state: "not-fat" };
if (tableEnd > bytes.byteLength)
return { state: "needs-data", requiredBytes: tableEnd };
const declarations = readFatSliceDeclarations(bytes.subarray(8, tableEnd), {
count,
wide,
littleEndian,
});
return declarations.status === "parsed"
? {
state: "parsed",
magic,
count,
wide,
littleEndian,
tableEnd,
slices: declarations.slices,
rangeIssues: declarations.slices.map((slice) =>
inspectFatSliceRange(slice, fileSize, tableEnd),
),
}
: { state: "malformed", reason: declarations.reason };
};
/** Confirm FAT identity from architecture records and observed slice headers. */
export const classifyFatContainerIdentity = (
header: Extract<FatContainerHeader, { readonly state: "parsed" }>,
sliceHeaderAt: (offset: number) => number | null | undefined,
): FatContainerIdentity => {
const hasKnownCpu = header.slices.some(({ cpuType }) =>
KNOWN_MACHO_CPU_TYPES.includes(cpuType),
);
const invalidRange = header.rangeIssues.find(
(issue): issue is FatSliceRangeIssue => issue !== null,
);
if (hasKnownCpu)
return invalidRange === undefined
? { state: "mach-o" }
: { state: "malformed", ...invalidRange };
const validRanges = header.slices.filter(
(_slice, index) => header.rangeIssues[index] === null,
);
const missingHeaders: number[] = [];
let observedMachO = false;
for (const slice of validRanges) {
const magic = sliceHeaderAt(slice.offset);
if (magic === undefined) missingHeaders.push(slice.offset);
else if (magic !== null && MACHO_HEADER_MAGICS.includes(magic))
observedMachO = true;
}
if (observedMachO) {
return invalidRange === undefined
? { state: "mach-o" }
: { state: "malformed", ...invalidRange };
}
if (missingHeaders.length > 0)
return { state: "needs-slice-header", offsets: missingHeaders };
return { state: "not-mach-o" };
};
/** Decode FAT table entries once so artifact and native readers share identity facts. */
export const readFatSliceDeclarations = (
tableBytes: Uint8Array,
@@ -64,32 +194,61 @@ export const validateFatSlice = (
tableEnd: number,
embedded?: { readonly cpuType: number; readonly cpuSubtype: number },
): string | null => {
const { index, offset, size, alignmentExponent, cpuType, cpuSubtype } =
declaration;
const rangeIssue = inspectFatSliceRange(declaration, containerSize, tableEnd);
if (rangeIssue !== null) return rangeIssue.reason;
return embedded === undefined
? null
: validateFatSliceIdentity(declaration, embedded);
};
/** Validate table placement, container bounds, and alignment with a typed failure. */
export const inspectFatSliceRange = (
declaration: FatSliceDeclaration,
containerSize: number,
tableEnd: number,
): FatSliceRangeIssue | null => {
const { index, offset, size, alignmentExponent } = declaration;
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(size) ||
size <= 0 ||
offset < tableEnd
)
return `FAT architecture ${index} has an invalid slice range`;
return {
category: "malformed",
reason: `FAT architecture ${index} has an invalid slice range`,
};
if (offset > containerSize || size > containerSize - offset)
return `FAT architecture ${index} slice range extends beyond the file`;
return {
category: "malformed",
reason: `FAT architecture ${index} slice range extends beyond the file`,
};
if (
!Number.isInteger(alignmentExponent) ||
alignmentExponent < 0 ||
alignmentExponent > 52
)
return `FAT architecture ${index} alignment exponent ${alignmentExponent} is unsupported`;
return {
category: "unsupported",
reason: `FAT architecture ${index} alignment exponent ${alignmentExponent} is unsupported`,
};
if (offset % 2 ** alignmentExponent !== 0)
return `FAT architecture ${index} offset is not aligned to 2^${alignmentExponent}`;
if (
embedded !== undefined &&
(embedded.cpuType !== cpuType || embedded.cpuSubtype !== cpuSubtype)
)
return `FAT architecture ${index} CPU type/subtype disagrees with its Mach-O header`;
return {
category: "malformed",
reason: `FAT architecture ${index} offset is not aligned to 2^${alignmentExponent}`,
};
return null;
};
/** Validate only the identity claim after the owner has validated its range. */
export const validateFatSliceIdentity = (
declaration: FatSliceDeclaration,
embedded: { readonly cpuType: number; readonly cpuSubtype: number },
): string | null =>
embedded.cpuType === declaration.cpuType &&
embedded.cpuSubtype === declaration.cpuSubtype
? null
: `FAT architecture ${declaration.index} CPU type/subtype disagrees with its Mach-O header`;
const safeNumber = (value: bigint): number | null =>
value > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(value);
+6
View File
@@ -0,0 +1,6 @@
/** CPU subtype bits reserved for ABI/capability flags, not the base subtype. */
const CPU_SUBTYPE_CAPABILITY_MASK = 0xff000000;
/** Return the CPU subtype identity shared across capability-flag variations. */
export const machoCpuSubtypeBase = (cpuSubtype: number): number =>
cpuSubtype & ~CPU_SUBTYPE_CAPABILITY_MASK;
+3 -12
View File
@@ -8,12 +8,12 @@ import type {
} from "./artifactGraph.js";
import { evidenceSchema } from "./evidence.js";
import {
hasCompleteInventoryCoverage,
parseArtifactInventoryEvidence,
type InventorySet,
} from "./artifactInventoryEvidence.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJson } from "./comparisonSemantics.js";
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "./zipPackageFormat.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const comparisonStatusSchema = z.enum([
@@ -104,10 +104,8 @@ export const compareArtifacts = (
const right = parseArtifactInventoryEvidence(rightEvidence);
const leftComplete = left.inventory.complete;
const rightComplete = right.inventory.complete;
const leftCovered =
leftComplete && !hasCoverageLimitation(left.inventory.limitations);
const rightCovered =
rightComplete && !hasCoverageLimitation(right.inventory.limitations);
const leftCovered = hasCompleteInventoryCoverage(left.inventory);
const rightCovered = hasCompleteInventoryCoverage(right.inventory);
const limitations = [
...left.inventory.limitations.map((item) => `Left: ${item}`),
...right.inventory.limitations.map((item) => `Right: ${item}`),
@@ -433,13 +431,6 @@ const summarize = (
};
};
const hasCoverageLimitation = (limitations: readonly string[]): boolean =>
limitations.some(
(limitation) =>
limitation !== ZIP_NON_ENTRY_TAIL_LIMITATION &&
!/integrity contradiction\(s\) were recorded/u.test(limitation),
);
// Differing manifest root digests prove a root content change even when node
// details are unavailable. Fold that fact into an existing root row so one
// logical path keeps one classification.

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