fix(docs): reconcile canonical layout and verify new pages
This commit is contained in:
@@ -84,6 +84,24 @@ describe("parseAdbDevicesOutput", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts complete multiword states and rejects state prefixes", () => {
|
||||
const output = [
|
||||
"serial-no-permission no permissions usb:1-1",
|
||||
"serial-bad-device deviceXYZ ",
|
||||
"serial-bad-offline offline-ish",
|
||||
"serial-bad-auth unauthorizedXYZ",
|
||||
].join("\n");
|
||||
const { devices, unparsedLines } = parseAdbDevicesOutput(output);
|
||||
expect(devices.map(({ serial, state }) => [serial, state])).toEqual([
|
||||
["serial-no-permission", "no permissions"],
|
||||
]);
|
||||
expect(unparsedLines).toEqual([
|
||||
"serial-bad-device deviceXYZ ",
|
||||
"serial-bad-offline offline-ish",
|
||||
"serial-bad-auth unauthorizedXYZ",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns unrecognized lines instead of dropping them", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
@@ -194,10 +212,10 @@ describe("parsePackageListOutput", () => {
|
||||
|
||||
it("keeps unrecognized lines for partial coverage reporting", () => {
|
||||
const { packages, unparsedLines } = parsePackageListOutput(
|
||||
"package:/data/app/x/base.apk=com.ok\ngarbage line\n",
|
||||
"package:/data/app/x/base.apk=com.ok\n garbage line \n",
|
||||
);
|
||||
expect(packages).toHaveLength(1);
|
||||
expect(unparsedLines).toEqual(["garbage line"]);
|
||||
expect(unparsedLines).toEqual([" garbage line "]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+14
-25
@@ -10,11 +10,15 @@ import {
|
||||
adbHostFileName,
|
||||
type AdbHostFileNameReason,
|
||||
} from "./AdbHostFileName.js";
|
||||
import {
|
||||
ADB_DEVICE_STATES,
|
||||
type AdbDeviceState,
|
||||
} from "../domain/adb/adbDeviceAnalysis.js";
|
||||
|
||||
/** One device exactly as `adb devices -l` reports it. */
|
||||
export interface AdbDeviceEntry {
|
||||
readonly serial: string;
|
||||
readonly state: string;
|
||||
readonly state: AdbDeviceState;
|
||||
readonly transport: "usb" | "tcp" | "unknown";
|
||||
readonly product: string | null;
|
||||
readonly model: string | null;
|
||||
@@ -24,25 +28,6 @@ export interface AdbDeviceEntry {
|
||||
readonly kind_basis: "emulator_serial_prefix" | "usb_transport" | "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* Device states adb prints after the serial, longest first so two-word
|
||||
* states match before their single-word prefixes. A line whose remainder
|
||||
* starts with none of them is not a device line.
|
||||
*/
|
||||
const DEVICE_STATES = [
|
||||
"no permissions",
|
||||
"unauthorized",
|
||||
"authorizing",
|
||||
"offline",
|
||||
"recovery",
|
||||
"sideload",
|
||||
"connecting",
|
||||
"bootloader",
|
||||
"device",
|
||||
"unknown",
|
||||
"host",
|
||||
] as const;
|
||||
|
||||
const DEVICE_LINE = /^(\S+)\s+(.*)$/u;
|
||||
|
||||
const metadataValue = (remainder: string, key: string): string | null => {
|
||||
@@ -73,11 +58,15 @@ export const parseAdbDevicesOutput = (
|
||||
continue;
|
||||
}
|
||||
const match = DEVICE_LINE.exec(line);
|
||||
const state = DEVICE_STATES.find((candidate) =>
|
||||
match?.[2]?.startsWith(candidate),
|
||||
);
|
||||
const state = ADB_DEVICE_STATES.find((candidate) => {
|
||||
const remainder = match?.[2];
|
||||
if (remainder === undefined || !remainder.startsWith(candidate))
|
||||
return false;
|
||||
const next = remainder[candidate.length];
|
||||
return next === undefined || /\s/u.test(next);
|
||||
});
|
||||
if (match === null || state === undefined) {
|
||||
if (line.trim() !== "") unparsedLines.push(line);
|
||||
if (rawLine.trim() !== "") unparsedLines.push(rawLine);
|
||||
continue;
|
||||
}
|
||||
const serial = match[1]!;
|
||||
@@ -192,7 +181,7 @@ export const parsePackageListOutput = (
|
||||
if (line === "") continue;
|
||||
const match = PACKAGE_LINE.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(line);
|
||||
unparsedLines.push(rawLine);
|
||||
continue;
|
||||
}
|
||||
packages.push({
|
||||
|
||||
@@ -121,6 +121,52 @@ fi`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses device listings with an invalid state token", async () => {
|
||||
const malformedLine = "serial deviceXYZ ";
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "devices" ]; then
|
||||
printf 'List of devices attached\\n${malformedLine}\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await providerOver(binary).execute({
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisProtocolError");
|
||||
expect(result.error.message).toContain(malformedLine);
|
||||
});
|
||||
|
||||
it("lists rescue and detached transports alongside online devices", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "devices" ]; then
|
||||
printf 'List of devices attached\\n'
|
||||
printf 'serial-online device transport_id:1\\n'
|
||||
printf 'serial-rescue rescue transport_id:2\\n'
|
||||
printf 'serial-detached detached transport_id:3\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.devices).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ serial: "serial-online", state: "device" }),
|
||||
expect.objectContaining({ serial: "serial-rescue", state: "rescue" }),
|
||||
expect.objectContaining({
|
||||
serial: "serial-detached",
|
||||
state: "detached",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("inspects a device through the getprop whitelist", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
@@ -580,6 +626,34 @@ it("projects package details from dumpsys package output", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Android 10 and 11 append ": restricted=true" to hard- and soft-restricted
|
||||
// entries of the requested-permissions list (Settings.dumpPackageLPr).
|
||||
it("counts requested permissions that the device marks as restricted", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"dumpsys:package": `Packages:
|
||||
Package [com.example] (abcdef):
|
||||
userId=10234
|
||||
versionName=1.2.3
|
||||
requested permissions:
|
||||
android.permission.INTERNET
|
||||
android.permission.WRITE_EXTERNAL_STORAGE: restricted=true
|
||||
android.permission.CAMERA
|
||||
install permissions:
|
||||
android.permission.INTERNET: granted=true
|
||||
`,
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
requested_permissions_count: 3,
|
||||
coverage: "complete",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an uninstalled package from dumpsys refusal output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({ "dumpsys:package": "Unable to find package: com.absent\n" }),
|
||||
|
||||
@@ -236,7 +236,11 @@ export const parseDumpsysPackageOutput = (
|
||||
inPermissions = true;
|
||||
continue;
|
||||
}
|
||||
if (inPermissions && /^\s{2,}[A-Za-z0-9._]+$/.test(line)) {
|
||||
// Android 10 and 11 mark restricted entries as "NAME: restricted=true".
|
||||
if (
|
||||
inPermissions &&
|
||||
/^\s{2,}[A-Za-z0-9._]+(?:: restricted=true)?$/u.test(line)
|
||||
) {
|
||||
permissions += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -199,9 +199,11 @@ export class JadxMcpTransport implements Transport {
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
this.#appendFrame(fragment, frameBytes);
|
||||
if (newline === -1) return;
|
||||
const line = this.#frameBuffer
|
||||
.subarray(0, this.#frameLength)
|
||||
.toString("utf8");
|
||||
const line = new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
// Preserve a leading BOM so the JSON-RPC parser can reject it.
|
||||
ignoreBOM: true,
|
||||
}).decode(this.#frameBuffer.subarray(0, this.#frameLength));
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
this.onmessage?.(deserializeMessage(line));
|
||||
|
||||
@@ -96,6 +96,7 @@ const decodeStub = (
|
||||
readonly withStrings?: boolean;
|
||||
readonly withGerman?: boolean;
|
||||
readonly failDecode?: boolean;
|
||||
readonly ymlFile?: string;
|
||||
readonly manifestFile?: string;
|
||||
readonly stringsFile?: string;
|
||||
readonly stringsXml?: string;
|
||||
@@ -104,6 +105,10 @@ const decodeStub = (
|
||||
const withStrings = options.withStrings ?? true;
|
||||
const withGerman = options.withGerman ?? true;
|
||||
const stringsXml = options.stringsXml ?? REAL_STRINGS;
|
||||
const ymlWrite =
|
||||
options.ymlFile === undefined
|
||||
? `printf '%s\\n' '${REAL_YML.replace(/'/gu, "'\\''")}' > "$5/apktool.yml"`
|
||||
: `cp '${options.ymlFile}' "$5/apktool.yml"`;
|
||||
const manifestWrite =
|
||||
options.manifestFile === undefined
|
||||
? `printf '%s\\n' '${REAL_MANIFEST.replace(/'/gu, "'\\''")}' > "$5/AndroidManifest.xml"`
|
||||
@@ -117,7 +122,7 @@ if [ "$1" = "d" ]; then
|
||||
${
|
||||
options.failDecode === true
|
||||
? `printf 'Exception in thread "main" brut.androlib.AndrolibException: Could not decode the APK\\n' >&2; exit 1;`
|
||||
: `printf '%s\\n' '${REAL_YML.replace(/'/gu, "'\\''")}' > "$5/apktool.yml"
|
||||
: `${ymlWrite}
|
||||
${manifestWrite}
|
||||
mkdir -p "$5/res/values"${withGerman ? ' "$5/res/values-de"' : ""}
|
||||
${withStrings ? stringsWrite : ""}
|
||||
@@ -192,6 +197,47 @@ it("decodes resources with target identity, metadata, and strings", async () =>
|
||||
expect(result.coverage).toBe("complete");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "malformed UTF-8",
|
||||
bytes: Buffer.concat([
|
||||
Buffer.from("versionInfo:\n versionName: com."),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from(".app\n"),
|
||||
]),
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "a literal replacement character",
|
||||
bytes: Buffer.from("versionInfo:\n versionName: com.�.app\n", "utf8"),
|
||||
valid: true,
|
||||
},
|
||||
])("handles $name in producer metadata", async ({ bytes, valid }) => {
|
||||
const { command, root } = await writeApktoolStub((root) =>
|
||||
decodeStub({ ymlFile: join(root, "malformed-apktool.yml") })(root),
|
||||
);
|
||||
await writeFile(join(root, "malformed-apktool.yml"), bytes);
|
||||
const apk = await apkFixture(root);
|
||||
if (valid) {
|
||||
const result = await evidenceResult(providerOver(command), {
|
||||
operation: "decode_android_resources",
|
||||
input: { path: apk.path, include_strings: false },
|
||||
});
|
||||
expect(result.metadata).toMatchObject({ version_name: "com.�.app" });
|
||||
expect(result.coverage).toBe("complete");
|
||||
return;
|
||||
}
|
||||
const result = await providerOver(command).execute({
|
||||
operation: "decode_android_resources",
|
||||
input: { path: apk.path, include_strings: false },
|
||||
});
|
||||
if (result.ok) throw new Error("expected invalid producer output");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected).toMatchObject({ code: "unreadable_output" });
|
||||
expect(result.error.message).toContain("invalid UTF-8");
|
||||
expect(result.error.message).toContain("apktool.yml");
|
||||
});
|
||||
|
||||
it("preserves empty resource strings and reports markup omissions as partial", async () => {
|
||||
const stringsXml =
|
||||
'<resources><string name="empty"/><string name="raw"> A & B </string><string name="styled">Hello <b>world</b></string></resources>';
|
||||
|
||||
@@ -117,13 +117,20 @@ const readBoundedText = async (
|
||||
throwIfCancelled(operation, signal);
|
||||
const truncated = length > budget;
|
||||
// A prefix may end within a UTF-8 character; omit those trailing bytes.
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
return {
|
||||
text: decoder.decode(bytes.subarray(0, Math.min(length, budget)), {
|
||||
stream: truncated,
|
||||
}),
|
||||
truncated,
|
||||
};
|
||||
try {
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
return {
|
||||
text: decoder.decode(bytes.subarray(0, Math.min(length, budget)), {
|
||||
stream: truncated,
|
||||
}),
|
||||
truncated,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
throw new AnalysisProtocolError(
|
||||
`apktool produced invalid UTF-8 in ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
|
||||
@@ -54,6 +54,15 @@ export interface AnalysisExecution {
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
}
|
||||
|
||||
interface CreateAnalysisExecutionOptions {
|
||||
readonly rawResult?: unknown;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relationshipCoverage?: RelationshipCoverage;
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a validated atomic provider observation at an adapter boundary.
|
||||
*
|
||||
@@ -61,38 +70,43 @@ export interface AnalysisExecution {
|
||||
* `result`. Omitting it records `null` rather than a second complete copy of
|
||||
* the normalized result in every Evidence record and tool response.
|
||||
*/
|
||||
export const createAnalysisExecution = (
|
||||
export function createAnalysisExecution<Subject extends EvidenceSubjectTarget>(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options: {
|
||||
readonly rawResult?: unknown;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relationshipCoverage?: RelationshipCoverage;
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
} = {},
|
||||
): AnalysisExecution => ({
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult:
|
||||
options.rawResult === undefined
|
||||
? null
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
...(options.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: structuredClone(options.analysisProfile) }),
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
...(options.relationshipCoverage === undefined
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage: relationshipCoverageSchema.parse(
|
||||
options.relationshipCoverage,
|
||||
),
|
||||
}),
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
});
|
||||
options: CreateAnalysisExecutionOptions & { readonly subject: Subject },
|
||||
): Omit<AnalysisExecution, "subject"> & { readonly subject: Subject };
|
||||
export function createAnalysisExecution(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options?: CreateAnalysisExecutionOptions,
|
||||
): AnalysisExecution;
|
||||
export function createAnalysisExecution(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options: CreateAnalysisExecutionOptions = {},
|
||||
): AnalysisExecution {
|
||||
return {
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult:
|
||||
options.rawResult === undefined
|
||||
? null
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
...(options.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: structuredClone(options.analysisProfile) }),
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
...(options.relationshipCoverage === undefined
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage: relationshipCoverageSchema.parse(
|
||||
options.relationshipCoverage,
|
||||
),
|
||||
}),
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Provider-neutral application capability for one analysis operation. */
|
||||
export interface AnalysisOperationPort {
|
||||
|
||||
@@ -397,7 +397,7 @@ 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")
|
||||
if (name === "inspect_packet_capture" || name === "inspect_packet_fields")
|
||||
return policy.packetCaptureEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
@@ -405,7 +405,7 @@ const workflowAvailabilityFor = ({
|
||||
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")
|
||||
if (name === "decode_signal_recording" || name === "inspect_signal_decoders")
|
||||
return policy.signalRecordingEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
@@ -481,7 +481,7 @@ const workflowAvailabilityFor = ({
|
||||
remediation: "Run process capture on a supported Linux or macOS host.",
|
||||
};
|
||||
if (kind === "application") return { reason: "available", remediation: null };
|
||||
if (kind === "flutter-provider")
|
||||
if (kind === "pcap-provider" || kind === "flutter-provider")
|
||||
return { reason: "available", remediation: null };
|
||||
const electron = electronProviderAvailability(name, kind, policy);
|
||||
if (electron !== null) return electron;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
clientServerForcedEnabled,
|
||||
clientServerListedDisabled,
|
||||
effectiveClientServer,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { access } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
@@ -74,24 +75,48 @@ const registrationSchema = z
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
/** Inspect supported client registrations without reading their environment. */
|
||||
interface ClientRegistrationReadOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
}
|
||||
|
||||
/** Registration facts shared by diagnostics and update maintenance. */
|
||||
export interface ClientRegistrationInspection {
|
||||
readonly status: ClientRegistrationStatus;
|
||||
readonly activation: "enabled" | "disabled" | "unknown";
|
||||
}
|
||||
|
||||
/** Project diagnostics from the same inspection used to select maintenance. */
|
||||
export const readClientRegistrationStatuses = async (
|
||||
home: string,
|
||||
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
|
||||
options: {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
} = {},
|
||||
): Promise<readonly ClientRegistrationStatus[]> => {
|
||||
const statuses: ClientRegistrationStatus[] = [];
|
||||
options: ClientRegistrationReadOptions = {},
|
||||
): Promise<readonly ClientRegistrationStatus[]> =>
|
||||
(
|
||||
await readClientRegistrationInspections(home, currentCommandPath, options)
|
||||
).map(({ status }) => status);
|
||||
|
||||
/** Parse effective registrations and their client-specific activation once. */
|
||||
export const readClientRegistrationInspections = async (
|
||||
home: string,
|
||||
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
|
||||
options: ClientRegistrationReadOptions = {},
|
||||
): Promise<readonly ClientRegistrationInspection[]> => {
|
||||
const inspections: ClientRegistrationInspection[] = [];
|
||||
const record = (
|
||||
status: ClientRegistrationStatus,
|
||||
activation: ClientRegistrationInspection["activation"] = "unknown",
|
||||
): void => {
|
||||
inspections.push({ status, activation });
|
||||
};
|
||||
for (const client of supportedClients(
|
||||
home,
|
||||
options.platform,
|
||||
options.environment,
|
||||
)) {
|
||||
if (client.configPathError !== undefined) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -104,7 +129,7 @@ export const readClientRegistrationStatuses = async (
|
||||
const manualRemediation = manualRegistrationRemediation(client.name);
|
||||
if (client.format === "unsupported") {
|
||||
if (manualRemediation !== undefined)
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.markerPath ?? client.configPath,
|
||||
command: [],
|
||||
@@ -119,7 +144,7 @@ export const readClientRegistrationStatuses = async (
|
||||
options.resources,
|
||||
);
|
||||
if (!files.ok) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -130,9 +155,7 @@ export const readClientRegistrationStatuses = async (
|
||||
}
|
||||
const parsed = effectiveClientConfiguration(files.value);
|
||||
if (parsed === undefined) {
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
record(unavailableStatus(client.name, client.configPath, "missing"));
|
||||
continue;
|
||||
}
|
||||
const policy = await readClientPolicyBlock(
|
||||
@@ -142,7 +165,7 @@ export const readClientRegistrationStatuses = async (
|
||||
options.resources,
|
||||
);
|
||||
if (!policy.ok) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -159,7 +182,7 @@ export const readClientRegistrationStatuses = async (
|
||||
? dshDocument(parsed.document).editabilityError
|
||||
: undefined;
|
||||
if (editabilityError !== undefined) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -168,9 +191,7 @@ export const readClientRegistrationStatuses = async (
|
||||
});
|
||||
continue;
|
||||
}
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
record(unavailableStatus(client.name, client.configPath, "missing"));
|
||||
continue;
|
||||
}
|
||||
const registration = parseRegistration(raw, client);
|
||||
@@ -178,21 +199,18 @@ export const readClientRegistrationStatuses = async (
|
||||
registration.command,
|
||||
...registration.args,
|
||||
];
|
||||
statuses.push(
|
||||
const activation = registrationActivation(registration, client, parsed);
|
||||
record(
|
||||
configuredStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
command,
|
||||
registrationAligned(
|
||||
registration,
|
||||
client,
|
||||
currentCommandPath,
|
||||
options.platform ?? process.platform,
|
||||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey),
|
||||
) &&
|
||||
!clientServerListedDisabled(
|
||||
parsed,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
activation === "enabled" &&
|
||||
registrationAligned(
|
||||
registration,
|
||||
client,
|
||||
currentCommandPath,
|
||||
options.platform ?? process.platform,
|
||||
) &&
|
||||
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
|
||||
policyBlock === undefined
|
||||
@@ -200,9 +218,10 @@ export const readClientRegistrationStatuses = async (
|
||||
: "stale",
|
||||
policyBlock,
|
||||
),
|
||||
activation,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
statuses.push(
|
||||
record(
|
||||
unavailableStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
@@ -211,26 +230,31 @@ export const readClientRegistrationStatuses = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
return statuses.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.client, right.client),
|
||||
return inspections.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.status.client, right.status.client),
|
||||
);
|
||||
};
|
||||
|
||||
const registrationActivation = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: SetupClient,
|
||||
parsed: ClientConfigurationDocument,
|
||||
): "enabled" | "disabled" =>
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false &&
|
||||
!clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) ||
|
||||
(client.format === "zcode" && registration.enable === false) ||
|
||||
clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
|
||||
? "disabled"
|
||||
: "enabled";
|
||||
|
||||
const registrationAligned = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: SetupClient,
|
||||
currentCommandPath: string,
|
||||
platform: NodeJS.Platform,
|
||||
forcedEnabled = false,
|
||||
): boolean => {
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false && !forcedEnabled) ||
|
||||
// ZCode's native flag is `enable`; other dialects leave that field opaque.
|
||||
(client.format === "zcode" && registration.enable === false)
|
||||
)
|
||||
return false;
|
||||
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
|
||||
return false;
|
||||
if (
|
||||
|
||||
@@ -21,8 +21,8 @@ import {
|
||||
parseFunctionDossier,
|
||||
parseListCount,
|
||||
parseRelatedAddresses,
|
||||
parseSegmentImageBase,
|
||||
parseSegments,
|
||||
parseSegmentImageBase,
|
||||
} from "../domain/hopperValues.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -46,6 +46,7 @@ import { traceCallPath } from "./CallPathTracing.js";
|
||||
import { resolveProcedureAddress } from "./ProcedureAddressResolution.js";
|
||||
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
|
||||
import { projectNativeApiInspection } from "./native/NativeApiInspection.js";
|
||||
|
||||
/**
|
||||
* Composes direct provider operations into bounded reverse-engineering tools.
|
||||
* Direct callers use `execute`; adapters that own validation use
|
||||
@@ -528,24 +529,29 @@ 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");
|
||||
if (!stringCount.ok) return stringCount;
|
||||
|
||||
const imageBase = parseSegmentImageBase(segments.value);
|
||||
|
||||
return ok({
|
||||
document: document.value,
|
||||
segments: segments.value.map(({ name, start, end }) => ({
|
||||
name,
|
||||
start,
|
||||
end,
|
||||
length: addressDistance(start, end),
|
||||
})),
|
||||
...(imageBase === undefined ? {} : { image_base: imageBase }),
|
||||
segments: segments.value.map(
|
||||
({ name, start, end, image_base, address_space }) => ({
|
||||
name,
|
||||
start,
|
||||
end,
|
||||
length: addressDistance(start, end),
|
||||
...(image_base === undefined ? {} : { image_base }),
|
||||
...(address_space === undefined ? {} : { address_space }),
|
||||
}),
|
||||
),
|
||||
segment_count: segments.value.length,
|
||||
procedure_count: procedureCount.value,
|
||||
string_count: stringCount.value,
|
||||
...(imageBase === undefined ? {} : { image_base: imageBase }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -18,11 +18,11 @@ export const workflowAnalysisProfile = (
|
||||
): AnalysisProfileCommitment =>
|
||||
createAnalysisProfile(REA_WORKFLOW_PROVIDER, {
|
||||
upstream_analysis_profile: upstream,
|
||||
...(operation === "binary_overview" ||
|
||||
operation === "batch_decompile" ||
|
||||
operation === "get_call_graph"
|
||||
? { workflow_revision: 2 }
|
||||
: {}),
|
||||
...(operation === "binary_overview"
|
||||
? { workflow_revision: 3 }
|
||||
: operation === "batch_decompile" || operation === "get_call_graph"
|
||||
? { workflow_revision: 2 }
|
||||
: {}),
|
||||
});
|
||||
|
||||
/** Provider identity for deterministic artifact inventories. */
|
||||
|
||||
@@ -78,7 +78,9 @@ export const readJsonObjectFile = (
|
||||
value === null ||
|
||||
Array.isArray(value)
|
||||
)
|
||||
throw new TypeError("JSON document root must be an object");
|
||||
return err(
|
||||
invalidJson(operation, "JSON document root must be an object"),
|
||||
);
|
||||
for (const members of scans)
|
||||
for (const [key, member] of members) {
|
||||
if (!Object.hasOwn(value, key)) continue;
|
||||
@@ -177,7 +179,9 @@ export const readJsonObjectFile = (
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
if (!rootObject)
|
||||
throw new TypeError("JSON document root must be an object");
|
||||
return err(
|
||||
invalidJson(operation, "JSON document root must be an object"),
|
||||
);
|
||||
const digest = hash.digest("hex");
|
||||
if (previousDigest !== undefined && digest !== previousDigest)
|
||||
throw new RegularFileChangedError(path);
|
||||
|
||||
@@ -2,12 +2,16 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
|
||||
import {
|
||||
installMacHopper,
|
||||
type MacHopperBundleVerification,
|
||||
type MacHopperInstallHost,
|
||||
} from "./MacHopper.js";
|
||||
|
||||
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||
archiveOk = true;
|
||||
valid = true;
|
||||
verification: MacHopperBundleVerification = "verified";
|
||||
existing = false;
|
||||
mountSucceeds = true;
|
||||
copySucceeds = true;
|
||||
@@ -15,6 +19,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
badHash = false;
|
||||
unmounts = 0;
|
||||
cleanups = 0;
|
||||
installs = 0;
|
||||
opens = 0;
|
||||
replaces = false;
|
||||
|
||||
@@ -47,7 +52,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
return Promise.resolve();
|
||||
};
|
||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||
validBundle = () => Promise.resolve(this.valid);
|
||||
validBundle = () => Promise.resolve(this.verification);
|
||||
destinationExists = () => Promise.resolve(this.existing);
|
||||
installBundle = (
|
||||
_source: string,
|
||||
@@ -55,6 +60,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
_stage: string,
|
||||
replaceExisting: boolean,
|
||||
) => {
|
||||
this.installs += 1;
|
||||
this.replaces = replaceExisting;
|
||||
return Promise.resolve(this.copySucceeds);
|
||||
};
|
||||
@@ -115,7 +121,7 @@ describe("macOS Hopper installation", () => {
|
||||
|
||||
it("cleans and detaches after bundle validation fails", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.valid = false;
|
||||
host.verification = "invalid_signature";
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "bundle",
|
||||
@@ -123,4 +129,17 @@ describe("macOS Hopper installation", () => {
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it("reports a publisher mismatch without copying or launching the bundle", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.verification = "unverified_publisher";
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "publisher_verification_failed",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
expect(host.opens).toBe(0);
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,7 +24,35 @@ const execFileAsync = promisify(execFile);
|
||||
const RELEASES_URL =
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
||||
const BUNDLE_IDENTIFIER = "com.cryptic-apps.hopper-web-4";
|
||||
|
||||
/**
|
||||
* Apple publisher identity pinned for the official Hopper macOS bundle. The
|
||||
* team identifier was captured from `Hopper-6.6.0-demo.dmg` at
|
||||
* `https://www.hopperapp.com:443/downloader/public/Hopper-6.6.0-demo.dmg`
|
||||
* (34846271 bytes, SHA-1 0be530f038249742590992199c7b042ea20ca955) with
|
||||
* `codesign -dvvv`, which reported
|
||||
* `Authority=Developer ID Application: Cryptic Apps (2AMA2753NF)`.
|
||||
*/
|
||||
export const HOPPER_PUBLISHER = Object.freeze({
|
||||
bundleIdentifier: "com.cryptic-apps.hopper-web-4",
|
||||
teamIdentifier: "2AMA2753NF",
|
||||
});
|
||||
|
||||
/**
|
||||
* Code requirement enforcing the bundle identifier and signing team together.
|
||||
* The identifier is read from the sealed CodeDirectory, so it cannot be changed
|
||||
* by editing `Info.plist` the way the previous string comparison could.
|
||||
*/
|
||||
const HOPPER_PUBLISHER_REQUIREMENT =
|
||||
`= identifier "${HOPPER_PUBLISHER.bundleIdentifier}"` +
|
||||
` and anchor apple generic` +
|
||||
` and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"`;
|
||||
|
||||
/** Outcome of reading a mounted bundle's signature and publisher identity. */
|
||||
export type MacHopperBundleVerification =
|
||||
| "verified"
|
||||
| "invalid_signature"
|
||||
| "unverified_publisher";
|
||||
|
||||
/** Stable network and command effects disclosed before macOS Hopper setup. */
|
||||
export const macHopperInstallDisclosure = {
|
||||
@@ -32,6 +60,7 @@ export const macHopperInstallDisclosure = {
|
||||
commands: [
|
||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||
"codesign --verify --deep --strict <mounted-hopper.app>",
|
||||
`codesign --verify --strict '-R${HOPPER_PUBLISHER_REQUIREMENT}' <mounted-hopper.app>`,
|
||||
"ditto <mounted-hopper.app> <user-Applications-stage>",
|
||||
"open <installed-hopper.app>",
|
||||
] as const,
|
||||
@@ -52,6 +81,7 @@ export type MacHopperInstallResult =
|
||||
| "integrity"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "destination_exists"
|
||||
| "copy"
|
||||
| "launcher_missing";
|
||||
@@ -69,7 +99,7 @@ export interface MacHopperInstallHost {
|
||||
mount(packagePath: string, mountPath: string): Promise<boolean>;
|
||||
unmount(mountPath: string): Promise<void>;
|
||||
appBundle(mountPath: string): Promise<string | undefined>;
|
||||
validBundle(appPath: string): Promise<boolean>;
|
||||
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
|
||||
destinationExists(path: string): Promise<boolean>;
|
||||
installBundle(
|
||||
source: string,
|
||||
@@ -124,8 +154,12 @@ export const installMacHopper = async (
|
||||
return { status: "failed", reason: "mount" };
|
||||
mounted = true;
|
||||
const source = await host.appBundle(mountPath);
|
||||
if (source === undefined || !(await host.validBundle(source)))
|
||||
if (source === undefined) return { status: "failed", reason: "bundle" };
|
||||
const verification = await host.validBundle(source);
|
||||
if (verification === "invalid_signature")
|
||||
return { status: "failed", reason: "bundle" };
|
||||
if (verification === "unverified_publisher")
|
||||
return { status: "failed", reason: "publisher_verification_failed" };
|
||||
const stage = `${destination}.rea-stage`;
|
||||
if (
|
||||
!(await host.installBundle(
|
||||
@@ -222,25 +256,21 @@ export const systemMacHopperInstallHost = (
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
const identifier = (
|
||||
await execFileAsync(
|
||||
"/usr/libexec/PlistBuddy",
|
||||
[
|
||||
"-c",
|
||||
"Print :CFBundleIdentifier",
|
||||
join(appPath, "Contents/Info.plist"),
|
||||
],
|
||||
{ env: environment },
|
||||
)
|
||||
).stdout.trim();
|
||||
return identifier === BUNDLE_IDENTIFIER;
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: optional bundle probing; unreadable means invalid.
|
||||
void cause;
|
||||
return false;
|
||||
}
|
||||
return "invalid_signature";
|
||||
if (
|
||||
!(await commandSucceeds(
|
||||
"codesign",
|
||||
[
|
||||
"--verify",
|
||||
"--strict",
|
||||
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
|
||||
appPath,
|
||||
],
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return "unverified_publisher";
|
||||
return "verified";
|
||||
},
|
||||
async destinationExists(path) {
|
||||
try {
|
||||
|
||||
@@ -23,7 +23,7 @@ export const createProgressReporter = (
|
||||
} = {},
|
||||
): ProgressReporter => {
|
||||
const minimumIntervalMs = options.minimumIntervalMs ?? 100;
|
||||
const now = options.now ?? Date.now;
|
||||
const now = options.now ?? (() => performance.now());
|
||||
let lastCompleted = -1;
|
||||
let lastSentAt = Number.NEGATIVE_INFINITY;
|
||||
let sequence = 0;
|
||||
|
||||
@@ -12,12 +12,14 @@ import {
|
||||
detectReferenceSourceLanguage,
|
||||
} from "../domain/referenceSourceClassification.js";
|
||||
import type { HistoricalSourceGraphInput } from "../domain/referenceSourceGraph.js";
|
||||
import { parseReferenceSourceImports } from "../domain/referenceSourceImportParsing.js";
|
||||
import {
|
||||
parseReferenceSourceImports,
|
||||
PARSEABLE_REFERENCE_SOURCE_LANGUAGES,
|
||||
} from "../domain/referenceSourceImportParsing.js";
|
||||
import type {
|
||||
ReferenceSourceEntry,
|
||||
ReferenceSourceRead,
|
||||
} from "../reference/ReferenceSourceReaderTypes.js";
|
||||
import { PARSEABLE_REFERENCE_SOURCE_LANGUAGES } from "./ReferenceSourceImportTypes.js";
|
||||
import { typescriptEmittedSourceCandidates } from "./TypeScriptEmittedSourceCandidates.js";
|
||||
|
||||
export interface ParsedReferenceSourceEntries {
|
||||
@@ -102,7 +104,11 @@ const resolveInternalSpecifier = (
|
||||
]);
|
||||
// Retain present runtime files first; substitute only a missing counterpart.
|
||||
// Counterparts cover explicit filenames, not directory/index resolution.
|
||||
candidates.push(...typescriptEmittedSourceCandidates(fromPath, normalized));
|
||||
candidates.push(
|
||||
...typescriptEmittedSourceCandidates(fromPath, normalized).map(
|
||||
({ path }) => path,
|
||||
),
|
||||
);
|
||||
const match = lookupPath.resolveCandidates(candidates);
|
||||
return match === undefined
|
||||
? { to: normalized, resolution: "unresolved" }
|
||||
|
||||
@@ -87,6 +87,3 @@ export const DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS = [
|
||||
".coverage",
|
||||
"*.log",
|
||||
] as const;
|
||||
|
||||
export const PARSEABLE_REFERENCE_SOURCE_LANGUAGES: ReadonlySet<string> =
|
||||
new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
|
||||
|
||||
@@ -19,6 +19,17 @@ export interface RegularFileReadOptions {
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
}
|
||||
|
||||
export class InvalidUtf8FileError extends TypeError {
|
||||
readonly _tag = "InvalidUtf8FileError";
|
||||
constructor(
|
||||
readonly path: string,
|
||||
cause: unknown,
|
||||
) {
|
||||
super(`File is not valid UTF-8: ${path}`, { cause });
|
||||
this.name = this._tag;
|
||||
}
|
||||
}
|
||||
|
||||
export type RegularFileReadOutcome<Value> =
|
||||
| { readonly kind: "completed"; readonly value: Value }
|
||||
| { readonly kind: "failed"; readonly cause: unknown };
|
||||
@@ -142,7 +153,34 @@ const withRegularFileOwned = async <Value>(
|
||||
export const readRegularFile = (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<Buffer> =>
|
||||
): Promise<Buffer> => readRegularFileContent(path, (bytes) => bytes, options);
|
||||
|
||||
/** Read valid UTF-8 without replacing source bytes or stripping an initial BOM. */
|
||||
export const readRegularFileText = (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<string> =>
|
||||
readRegularFileContent(
|
||||
path,
|
||||
(bytes) => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
ignoreBOM: true,
|
||||
}).decode(bytes);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof TypeError)) throw cause;
|
||||
throw new InvalidUtf8FileError(path, cause);
|
||||
}
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
const readRegularFileContent = <Value>(
|
||||
path: string,
|
||||
decode: (bytes: Buffer) => Value,
|
||||
options: RegularFileReadOptions,
|
||||
): Promise<Value> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
async (handle, stats) => {
|
||||
@@ -153,30 +191,7 @@ export const readRegularFile = (
|
||||
);
|
||||
if (bytes === undefined || bytes.length !== stats.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
return bytes;
|
||||
return decode(bytes);
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
/** Read one admitted regular file as UTF-8 without waiting on a pipe. */
|
||||
export const readRegularFileText = async (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<string> => {
|
||||
try {
|
||||
return (await readRegularFile(path, options)).toString("utf8");
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof RegularFileCleanupFailure &&
|
||||
cause.outcome.kind === "completed" &&
|
||||
Buffer.isBuffer(cause.outcome.value)
|
||||
)
|
||||
throw new RegularFileCleanupFailure(
|
||||
cause.path,
|
||||
cause.owner,
|
||||
{ kind: "completed", value: cause.outcome.value.toString("utf8") },
|
||||
cause.cleanupCause,
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -54,6 +54,40 @@ describe("setup workflow", () => {
|
||||
expect(result.remediation).toContain("could not be updated");
|
||||
});
|
||||
|
||||
it("reports a failed config rollback with its destination and recovery backup", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [{ name: "codex", configPath: "/fixture/codex.json" }];
|
||||
host.clientResults.set("codex", {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: "/fixture/codex.json.rea.backup",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path: "/fixture/codex.json",
|
||||
detail: "permission denied",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.clients.codex).toEqual({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: "/fixture/codex.json.rea.backup",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path: "/fixture/codex.json",
|
||||
detail: "permission denied",
|
||||
},
|
||||
});
|
||||
expect(result.remediation).toContain("permission denied");
|
||||
expect(result.remediation).toContain("/fixture/codex.json.rea.backup");
|
||||
});
|
||||
|
||||
it("explains skill installation recovery", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
@@ -29,6 +30,7 @@ import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import {
|
||||
readRegularFile,
|
||||
readRegularFileText,
|
||||
RegularFileCleanupFailure,
|
||||
} from "./RegularFileRead.js";
|
||||
@@ -40,6 +42,26 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure<string> {
|
||||
constructor(
|
||||
failure: RegularFileCleanupFailure<string>,
|
||||
readonly configurationFailure: Extract<
|
||||
ClientConfigurationResult,
|
||||
{ readonly status: "failed"; readonly reason: "rollback" }
|
||||
>,
|
||||
) {
|
||||
super(
|
||||
failure.path,
|
||||
failure.owner,
|
||||
failure.outcome,
|
||||
new AggregateError(
|
||||
[failure.cleanupCause, new Error(configurationFailure.failure.detail)],
|
||||
`Configuration readback cleanup and rollback failed: ${configurationFailure.failure.path}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Configure one supported client's native stdio MCP registration shape. */
|
||||
export const configureClientConfiguration = (
|
||||
client: SetupClient,
|
||||
@@ -167,11 +189,23 @@ const persistClientConfiguration = async ({
|
||||
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
if (
|
||||
backupPath !== undefined &&
|
||||
!(await preserveConfigBackup(transactionPath, backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
let recoveryBackupPath: string | undefined;
|
||||
if (backupPath !== undefined && original !== undefined) {
|
||||
const selection = await selectCurrentRecoveryBackup(backupPath, original);
|
||||
if (!selection.ok) return { status: "failed", reason: "backup" };
|
||||
if (
|
||||
!(await preserveConfigBackup(transactionPath, selection.value.backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
const verified = await selectCurrentRecoveryBackup(backupPath, original);
|
||||
if (
|
||||
!verified.ok ||
|
||||
verified.value.backupPath !== selection.value.backupPath ||
|
||||
!verified.value.present
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
recoveryBackupPath = verified.value.backupPath;
|
||||
}
|
||||
// A native OpenCode V2 entry replaces REA's legacy V1 entry, which would
|
||||
// otherwise conflict with it.
|
||||
const legacyPath = legacyClientServerPath(
|
||||
@@ -239,19 +273,39 @@ const persistClientConfiguration = async ({
|
||||
!clientConfigurationValuesEqual(readback.servers[name], entry),
|
||||
)
|
||||
) {
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
return rollbackOrReadbackFailure(
|
||||
transactionPath,
|
||||
original,
|
||||
recoveryBackupPath,
|
||||
);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (cause instanceof RegularFileCleanupFailure) {
|
||||
const rollback = await restoreConfig(transactionPath, original);
|
||||
if (!rollback.ok)
|
||||
throw new ClientConfigurationCleanupRollbackFailure(cause, {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
...(recoveryBackupPath === undefined
|
||||
? {}
|
||||
: { backupPath: recoveryBackupPath }),
|
||||
failure: rollback.error,
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
// Readback failure restores the transaction before reporting.
|
||||
void cause;
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
return rollbackOrReadbackFailure(
|
||||
transactionPath,
|
||||
original,
|
||||
recoveryBackupPath,
|
||||
);
|
||||
}
|
||||
return {
|
||||
status: "configured",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
...(recoveryBackupPath === undefined
|
||||
? {}
|
||||
: { backupPath: recoveryBackupPath }),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -406,9 +460,18 @@ export const inspectClientConfiguration = async (
|
||||
"The existing configuration is malformed. Repair it before setup applies any other changes.",
|
||||
};
|
||||
}
|
||||
const backupSelection = await selectCurrentRecoveryBackup(
|
||||
`${client.configPath}.rea.backup`,
|
||||
original,
|
||||
);
|
||||
if (!backupSelection.ok)
|
||||
return {
|
||||
status: "invalid",
|
||||
remediation: backupSelection.error.detail,
|
||||
};
|
||||
return {
|
||||
status: "update",
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
backupPath: backupSelection.value.backupPath,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -473,19 +536,101 @@ const preserveConfigBackup = async (
|
||||
}
|
||||
};
|
||||
|
||||
interface RecoveryBackupSelection {
|
||||
readonly backupPath: string;
|
||||
readonly present: boolean;
|
||||
}
|
||||
|
||||
interface RecoveryBackupSelectionFailure {
|
||||
readonly kind: "unreadable" | "occupied";
|
||||
readonly path: string;
|
||||
readonly detail: string;
|
||||
}
|
||||
|
||||
const selectCurrentRecoveryBackup = async (
|
||||
firstBackupPath: string,
|
||||
original: string,
|
||||
): Promise<Result<RecoveryBackupSelection, RecoveryBackupSelectionFailure>> => {
|
||||
const expected = Buffer.from(original, "utf8");
|
||||
let firstBackup: Buffer | undefined;
|
||||
try {
|
||||
firstBackup = await readRegularFile(firstBackupPath, {
|
||||
symlinks: "reject",
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (!isMissing(cause))
|
||||
return err({
|
||||
kind: "unreadable",
|
||||
path: firstBackupPath,
|
||||
detail: `The recovery backup could not be checked: ${errorDetail(cause)}`,
|
||||
});
|
||||
}
|
||||
if (firstBackup === undefined)
|
||||
return ok({ backupPath: firstBackupPath, present: false });
|
||||
if (firstBackup.equals(expected))
|
||||
return ok({ backupPath: firstBackupPath, present: true });
|
||||
|
||||
const digest = createHash("sha256").update(original, "utf8").digest("hex");
|
||||
const recoveryPath = `${firstBackupPath}.${digest}.recovery`;
|
||||
let recovery: Buffer | undefined;
|
||||
try {
|
||||
recovery = await readRegularFile(recoveryPath, { symlinks: "reject" });
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (!isMissing(cause))
|
||||
return err({
|
||||
kind: "unreadable",
|
||||
path: recoveryPath,
|
||||
detail: `The recovery backup could not be checked: ${errorDetail(cause)}`,
|
||||
});
|
||||
}
|
||||
if (recovery !== undefined && !recovery.equals(expected))
|
||||
return err({
|
||||
kind: "occupied",
|
||||
path: recoveryPath,
|
||||
detail: `The recovery path already contains different data: ${recoveryPath}`,
|
||||
});
|
||||
return ok({ backupPath: recoveryPath, present: recovery !== undefined });
|
||||
};
|
||||
|
||||
const restoreConfig = async (
|
||||
path: string,
|
||||
original: string | undefined,
|
||||
): Promise<void> => {
|
||||
): Promise<
|
||||
Result<
|
||||
void,
|
||||
{ readonly kind: "restore"; readonly path: string; readonly detail: string }
|
||||
>
|
||||
> => {
|
||||
try {
|
||||
if (original === undefined) await rm(path, { force: true });
|
||||
else await writeFile(path, original, { encoding: "utf8", mode: 0o600 });
|
||||
return ok(undefined);
|
||||
} catch (cause: unknown) {
|
||||
// The backup remains available for the remediation reported by setup.
|
||||
void cause;
|
||||
return err({ kind: "restore", path, detail: errorDetail(cause) });
|
||||
}
|
||||
};
|
||||
|
||||
const rollbackOrReadbackFailure = async (
|
||||
targetPath: string,
|
||||
original: string | undefined,
|
||||
backupPath: string | undefined,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const rollback = await restoreConfig(targetPath, original);
|
||||
return rollback.ok
|
||||
? { status: "failed", reason: "readback" }
|
||||
: {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
failure: rollback.error,
|
||||
};
|
||||
};
|
||||
|
||||
const errorDetail = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
/** Whether REA's entry matches, no legacy entry remains, and no client disable list suppresses it. */
|
||||
const registrationCurrent = (
|
||||
parsed: ClientConfigurationDocument,
|
||||
|
||||
@@ -6,15 +6,19 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
const failedConfigurationMessage = (
|
||||
reason: "path" | "backup" | "write" | "readback",
|
||||
export const failedConfigurationMessage = (
|
||||
result: Extract<ClientConfigurationResult, { readonly status: "failed" }>,
|
||||
): string => {
|
||||
if (reason === "path")
|
||||
if (result.reason === "path")
|
||||
return "Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.";
|
||||
if (reason === "backup")
|
||||
if (result.reason === "backup")
|
||||
return "Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.";
|
||||
if (reason === "write")
|
||||
if (result.reason === "write")
|
||||
return "Agent configuration could not be updated. Check file permissions, then rerun setup.";
|
||||
if (result.reason === "rollback")
|
||||
return result.backupPath === undefined
|
||||
? `Agent configuration rollback failed at ${result.failure.path}: ${result.failure.detail}; the failed first-run file may remain. Remove or repair it before rerunning setup.`
|
||||
: `Agent configuration rollback failed at ${result.failure.path}: ${result.failure.detail}. Inspect the preserved backup at ${result.backupPath} and restore the intended configuration, then rerun setup.`;
|
||||
return "Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.";
|
||||
};
|
||||
|
||||
@@ -40,12 +44,12 @@ export const configureDetectedClients = async (options: {
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed") {
|
||||
failure ??= failedConfigurationMessage(result.reason);
|
||||
failure ??= failedConfigurationMessage(result);
|
||||
options.onProgress?.({
|
||||
actionId,
|
||||
label,
|
||||
state: "failed",
|
||||
detail: failedConfigurationMessage(result.reason),
|
||||
detail: failedConfigurationMessage(result),
|
||||
});
|
||||
} else if (result.status === "configured") {
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
|
||||
@@ -33,9 +33,11 @@ import {
|
||||
} from "./SetupSkill.js";
|
||||
import {
|
||||
clientConfigurationAligned,
|
||||
ClientConfigurationCleanupRollbackFailure,
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "./SetupClientConfiguration.js";
|
||||
import { failedConfigurationMessage } from "./SetupClients.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
import {
|
||||
RegularFileCleanupFailure,
|
||||
@@ -275,8 +277,12 @@ const runClientConfigurationOperation = async <Value>(
|
||||
cleanup.outcome.kind === "failed"
|
||||
? cleanup.outcome.cause
|
||||
: cause.cleanupCause;
|
||||
const rollbackMessage =
|
||||
cause instanceof ClientConfigurationCleanupRollbackFailure
|
||||
? ` ${failedConfigurationMessage(cause.configurationFailure)}`
|
||||
: "";
|
||||
throw configurationCleanupError(
|
||||
`Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}`,
|
||||
`Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}.${rollbackMessage}`,
|
||||
cause,
|
||||
cleanup.cleanup,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
|
||||
describe("macOS Hopper setup failure projection", () => {
|
||||
it("projects a publisher mismatch onto its own code and recovery", () => {
|
||||
expect(setupInstallFailure("publisher_verification_failed")).toEqual({
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a broken bundle distinct from a publisher mismatch", () => {
|
||||
expect(setupInstallFailure("bundle")).toEqual({
|
||||
status: "failed",
|
||||
code: "bundle_invalid",
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
|
||||
export type SetupFailureCode =
|
||||
| "unsupported_host"
|
||||
| "download_failed"
|
||||
@@ -10,6 +12,7 @@ export type SetupFailureCode =
|
||||
| "destination_exists"
|
||||
| "mount_failed"
|
||||
| "bundle_invalid"
|
||||
| "publisher_verification_failed"
|
||||
| "copy_failed"
|
||||
| "skill_install_failed"
|
||||
| "cleanup_failed";
|
||||
@@ -39,6 +42,7 @@ export type HopperInstallFailureReason =
|
||||
| "destination_exists"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "copy";
|
||||
|
||||
/** Map provider installer failures to stable setup codes and safe recovery. */
|
||||
@@ -115,6 +119,12 @@ export const setupInstallFailure = (
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
};
|
||||
case "publisher_verification_failed":
|
||||
return {
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
};
|
||||
case "copy":
|
||||
return {
|
||||
status: "failed",
|
||||
|
||||
@@ -320,5 +320,5 @@ const clientConfigurationDetail = (
|
||||
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
|
||||
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
|
||||
: "";
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
|
||||
};
|
||||
|
||||
@@ -26,6 +26,16 @@ export type ClientConfigurationResult =
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly reason: "path" | "backup" | "write" | "readback";
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly reason: "rollback";
|
||||
readonly backupPath?: string;
|
||||
readonly failure: {
|
||||
readonly kind: "restore";
|
||||
readonly path: string;
|
||||
readonly detail: string;
|
||||
};
|
||||
};
|
||||
|
||||
/** Read-only state used to block unsafe setup plans before any mutation. */
|
||||
|
||||
@@ -8,6 +8,11 @@ const EMITTED_SUFFIXES: ReadonlyArray<
|
||||
[".jsx", [".tsx", ".d.ts"]],
|
||||
];
|
||||
|
||||
export interface TypeScriptEmittedSourceCandidate {
|
||||
readonly path: string;
|
||||
readonly kind: "implementation" | "declaration";
|
||||
}
|
||||
|
||||
/**
|
||||
* Return TypeScript source counterparts for an explicit emitted filename.
|
||||
* Callers retain exact runtime-file precedence and must not use these for
|
||||
@@ -16,7 +21,7 @@ const EMITTED_SUFFIXES: ReadonlyArray<
|
||||
export const typescriptEmittedSourceCandidates = (
|
||||
sourcePath: string,
|
||||
candidate: string,
|
||||
): readonly string[] => {
|
||||
): readonly TypeScriptEmittedSourceCandidate[] => {
|
||||
if (!/\.(?:ts|tsx|mts|cts)$/u.test(sourcePath)) return [];
|
||||
const emitted = EMITTED_SUFFIXES.find(([suffix]) =>
|
||||
candidate.endsWith(suffix),
|
||||
@@ -25,5 +30,8 @@ export const typescriptEmittedSourceCandidates = (
|
||||
// Strip the matched suffix by length. posix.extname would miss dotfile
|
||||
// names such as ".js", whose whole basename is the emitted suffix itself.
|
||||
const stem = candidate.slice(0, candidate.length - emitted[0].length);
|
||||
return emitted[1].map((suffix) => `${stem}${suffix}`);
|
||||
return emitted[1].map((suffix) => ({
|
||||
path: `${stem}${suffix}`,
|
||||
kind: suffix.startsWith(".d.") ? "declaration" : "implementation",
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -25,7 +25,11 @@ import {
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { dshDocument } from "./DshCordisPatch.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import {
|
||||
InvalidUtf8FileError,
|
||||
RegularFileCleanupFailure,
|
||||
readRegularFileText,
|
||||
} from "./RegularFileRead.js";
|
||||
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import {
|
||||
manualRegistrationRemediation,
|
||||
@@ -269,13 +273,17 @@ const readClientConfiguration = async (
|
||||
try {
|
||||
original = await fileSystem.readText(transactionPath);
|
||||
} catch (cause: unknown) {
|
||||
const readFailure =
|
||||
cause instanceof RegularFileCleanupFailure ? cause.cause : cause;
|
||||
return itemRead(
|
||||
isMissing(cause)
|
||||
? item(client.name, "skipped", "Configuration does not exist.")
|
||||
: item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
readFailure instanceof InvalidUtf8FileError
|
||||
? "Configuration is not valid UTF-8 and was not changed. Repair it, then rerun uninstall."
|
||||
: "Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { readClientRegistrationStatuses } from "./ClientRegistrationStatus.js";
|
||||
import {
|
||||
clientServerForcedEnabled,
|
||||
clientServerListedDisabled,
|
||||
effectiveClientServer,
|
||||
parseClientConfiguration,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
import { readClientRegistrationInspections } from "./ClientRegistrationStatus.js";
|
||||
import { existingSkillDestinations } from "./SetupSkill.js";
|
||||
import type { SetupAction } from "./SetupTypes.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
|
||||
/** Existing REA integrations selected for maintenance, without discovering new targets. */
|
||||
@@ -61,41 +52,23 @@ export const existingMaintenanceScope = async (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<MaintenanceScope> => {
|
||||
const registrations = await readClientRegistrationStatuses(home, entryPoint, {
|
||||
environment,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
});
|
||||
const supported = supportedClients(home, process.platform, environment);
|
||||
const registrations = await readClientRegistrationInspections(
|
||||
home,
|
||||
entryPoint,
|
||||
{
|
||||
environment,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
},
|
||||
);
|
||||
const clients: string[] = [];
|
||||
for (const registration of registrations) {
|
||||
for (const { status: registration, activation } of registrations) {
|
||||
if (
|
||||
activation !== "enabled" ||
|
||||
(registration.state !== "aligned" && registration.state !== "stale") ||
|
||||
!isOwnedClientRegistrationCommand(registration.command, entryPoint)
|
||||
)
|
||||
continue;
|
||||
const client = supported.find(({ name }) => name === registration.client);
|
||||
if (client === undefined) continue;
|
||||
const parsed = parseClientConfiguration(
|
||||
await readRegularFileText(
|
||||
client.configPath,
|
||||
resources === undefined ? {} : { resources },
|
||||
),
|
||||
client.format,
|
||||
);
|
||||
const enabled = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
})
|
||||
.parse(effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey));
|
||||
// Root disable lists override enabled entries and OMP's force-on allowlist.
|
||||
if (
|
||||
(enabled.enabled !== false ||
|
||||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) &&
|
||||
enabled.disabled !== true &&
|
||||
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
|
||||
)
|
||||
clients.push(client.name);
|
||||
clients.push(registration.client);
|
||||
}
|
||||
const skillDestinations = await existingSkillDestinations(
|
||||
home,
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface WebModuleArtifacts extends SelectedWebScriptArtifacts {
|
||||
|
||||
/** Read selected local artifacts without refetching website assets. */
|
||||
export interface WebModuleArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: WebModuleTraceInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { closeOwnedWebResources } from "./closeOwnedWebResources.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -70,7 +71,13 @@ export class WebModuleTraceService {
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.resolver.close?.() ?? Promise.resolve();
|
||||
return closeOwnedWebResources(
|
||||
[
|
||||
this.artifacts.close?.bind(this.artifacts),
|
||||
this.resolver.close?.bind(this.resolver),
|
||||
],
|
||||
"Web module trace cleanup failed",
|
||||
);
|
||||
}
|
||||
|
||||
async trace(
|
||||
|
||||
@@ -12,4 +12,6 @@ export interface WebNetworkCapturePort {
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>>;
|
||||
/** Retry retained reader/runtime cleanup when the owning service shuts down. */
|
||||
close?(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createAnalysisProfile } from "../domain/analysisProfile.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
captureSensitiveValues,
|
||||
webNetworkCaptureSchema,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
@@ -25,6 +27,11 @@ const OPERATION = "inspect_web_network_capture";
|
||||
export class WebNetworkCaptureService {
|
||||
constructor(readonly port: WebNetworkCapturePort) {}
|
||||
|
||||
/** Release resources retained by the selected capture adapter. */
|
||||
close(): Promise<void> {
|
||||
return this.port.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Return selected complete records inline, without inventing live browser attribution. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
@@ -32,21 +39,8 @@ export class WebNetworkCaptureService {
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const declarations =
|
||||
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
|
||||
typeof rawInput === "object" &&
|
||||
rawInput !== null &&
|
||||
"sensitive_values" in rawInput
|
||||
? rawInput.sensitive_values
|
||||
: undefined,
|
||||
);
|
||||
const failure = (error: AnalysisError): Result<never, AnalysisError> =>
|
||||
err(
|
||||
redactExplicitFailure(
|
||||
error,
|
||||
declarations.success ? declarations.data : [],
|
||||
),
|
||||
);
|
||||
err(redactExplicitFailure(error, captureSensitiveValues(rawInput)));
|
||||
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return failure(
|
||||
@@ -187,6 +181,15 @@ export class WebNetworkCaptureService {
|
||||
? [...limitations, subjectUnavailableReason]
|
||||
: limitations,
|
||||
},
|
||||
...(safeValue.format !== "qlog"
|
||||
? {}
|
||||
: {
|
||||
analysisProfile: createAnalysisProfile(value.decoder, {
|
||||
qlog_profile: safeValue.qlog.profile,
|
||||
clock: safeValue.qlog.clock,
|
||||
scope: safeValue.qlog.scope,
|
||||
}),
|
||||
}),
|
||||
confidence: "observed",
|
||||
authority: "historical-reference",
|
||||
limitations,
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
|
||||
/** Read the caller-selected capture export and verify the selected source identity. */
|
||||
export interface WebScriptArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: SelectedWebScriptInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface WebSourceLocationArtifacts extends SelectedWebScriptArtifacts {
|
||||
|
||||
/** Replaceable artifact acquisition boundary for a caller-selected pairing. */
|
||||
export interface WebSourceLocationArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: WebSourceLocationInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { closeOwnedWebResources } from "./closeOwnedWebResources.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
@@ -71,7 +72,13 @@ export class WebSourceLocationService {
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.decoder.close?.() ?? Promise.resolve();
|
||||
return closeOwnedWebResources(
|
||||
[
|
||||
this.artifacts.close?.bind(this.artifacts),
|
||||
this.decoder.close?.bind(this.decoder),
|
||||
],
|
||||
"Web source-location cleanup failed",
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared CLI/MCP workflow preserves raw declarations and every equal-position match. */
|
||||
@@ -174,6 +181,7 @@ export class WebSourceLocationService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const invalidOutput = (message: string): Result<never, AnalysisError> =>
|
||||
err(new AnalysisOutputError(OPERATION, message));
|
||||
const invalid = (
|
||||
|
||||
@@ -47,14 +47,8 @@ export const inspectAnalysisViewValidated = (
|
||||
input: InspectAnalysisViewInput,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
const inline = input.source.kind === "inline" ? input.source.evidence : null;
|
||||
const inlineCapture =
|
||||
typeof inline === "object" &&
|
||||
inline !== null &&
|
||||
Object.getOwnPropertyDescriptor(inline, "operation")?.value ===
|
||||
"inspect_web_network_capture";
|
||||
const accumulator =
|
||||
input.view.kind === "api-surface" || inlineCapture
|
||||
input.view.kind === "api-surface"
|
||||
? new WebNetworkApiSurfaceAccumulator()
|
||||
: undefined;
|
||||
if (input.source.kind === "inline" && accumulator !== undefined) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { AndroidAnalysisService } from "./AndroidAnalysisService.js";
|
||||
import {
|
||||
requireAnalysisViewRetention,
|
||||
summarizeRetainedAnalysis,
|
||||
type AnalysisViewRetention,
|
||||
} from "../analysisView/AnalysisViewService.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import { androidPackageInspectionInputSchema } from "../../domain/android/androidAnalysis.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, type Result } from "../../domain/result.js";
|
||||
|
||||
/** Preserve the complete provider request; select retained delivery explicitly. */
|
||||
export const inspectAndroidPackage = async (
|
||||
service: AndroidAnalysisService,
|
||||
rawInput: unknown,
|
||||
retention: AnalysisViewRetention,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const operation = "inspect_android_package";
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const parsed = androidPackageInspectionInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, parsed.error.issues, rawInput, {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
if (parsed.data.detail === "summary") {
|
||||
const ready = requireAnalysisViewRetention(operation, retention);
|
||||
if (!ready.ok) return ready;
|
||||
}
|
||||
const executed = await service.execute(
|
||||
operation,
|
||||
{ path: parsed.data.path },
|
||||
options,
|
||||
);
|
||||
if (!executed.ok || parsed.data.detail !== "summary") return executed;
|
||||
return summarizeRetainedAnalysis(executed.value, retention);
|
||||
};
|
||||
@@ -12,6 +12,7 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Stable read and PE decoding boundary, independent of an active disassembler session. */
|
||||
export interface PeResourcesPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectPeResourcesInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -21,6 +21,10 @@ import { err, ok, type Result } from "../../domain/result.js";
|
||||
export class PeResourcesService {
|
||||
constructor(readonly provider: PeResourcesPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
inspectPacketFieldsInputSchema,
|
||||
packetFieldsCatalogSchema,
|
||||
type InspectPacketFieldsInput,
|
||||
} from "../../domain/captures/packetFields.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -24,6 +30,10 @@ export interface PacketCapturePort {
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
inspectFields(
|
||||
input: InspectPacketFieldsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -74,14 +84,58 @@ export class PacketCaptureService {
|
||||
"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 this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
async inspectFields(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_packet_fields";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectPacketFieldsInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
const decoded = await this.provider.inspectFields(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = packetFieldsCatalogSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data) ||
|
||||
execution.subject?.path !== report.data.tool.path ||
|
||||
execution.subject.sha256 !== report.data.tool.sha256
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Field discovery returned malformed data or changed the selected installation/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
#evidence(
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
options?: ExecutionOptions,
|
||||
): Result<Evidence, AnalysisError> {
|
||||
const evidence = createEvidence(
|
||||
execution.subject ?? undefined,
|
||||
execution.provider,
|
||||
{
|
||||
operation,
|
||||
parameters,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
},
|
||||
);
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Attempt every web workflow cleanup owner and report all failures. */
|
||||
export const closeOwnedWebResources = async (
|
||||
close: readonly ((() => Promise<void>) | undefined)[],
|
||||
message: string,
|
||||
): Promise<void> => {
|
||||
const results = await Promise.allSettled(
|
||||
close.flatMap((owner) =>
|
||||
owner === undefined ? [] : [Promise.resolve().then(owner)],
|
||||
),
|
||||
);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
if (failures.length > 0) throw new AggregateError(failures, message);
|
||||
};
|
||||
@@ -4,13 +4,19 @@ import type {
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { InspectEvmInterfaceInput } from "../../domain/evm/evmInterface.js";
|
||||
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Successful EVM interface recovery must identify the selected local file. */
|
||||
export type EvmInterfaceExecution = Omit<AnalysisExecution, "subject"> & {
|
||||
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
|
||||
};
|
||||
|
||||
/** Replaceable offline interface-recovery engine, independent of wallets and chain clients. */
|
||||
export interface EvmInterfacePort {
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectEvmInterfaceInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
): Promise<Result<EvmInterfaceExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { EvmInterfaceService } from "./EvmInterfaceService.js";
|
||||
import type { EvmInterfaceExecution } from "./EvmInterfacePort.js";
|
||||
import {
|
||||
evmInterfaceExecution,
|
||||
evmInterfaceFixture,
|
||||
@@ -43,7 +44,8 @@ it.each(["carrier", "encoding", "digest", "no-subject"])(
|
||||
},
|
||||
};
|
||||
const service = new EvmInterfaceService({
|
||||
inspect: () => Promise.resolve(ok(execution)),
|
||||
inspect: () =>
|
||||
Promise.resolve(ok(execution as unknown as EvmInterfaceExecution)),
|
||||
});
|
||||
expect(
|
||||
await service.inspect({
|
||||
|
||||
@@ -67,6 +67,7 @@ export class EvmInterfaceService {
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
report.data.artifact.encoding !== input.data.encoding ||
|
||||
execution.subject?.format !== "file" ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256
|
||||
)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { FlutterBuildAnalysisService } from "./FlutterBuildAnalysisService.js";
|
||||
import {
|
||||
requireAnalysisViewRetention,
|
||||
summarizeRetainedAnalysis,
|
||||
type AnalysisViewRetention,
|
||||
} from "../analysisView/AnalysisViewService.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import { dartAotInspectionInputSchema } from "../../domain/flutter/flutterBuildAnalysis.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, type Result } from "../../domain/result.js";
|
||||
|
||||
/** Keep the caller's ABI choice and complete analysis; select only its delivery. */
|
||||
export const inspectDartAot = async (
|
||||
service: FlutterBuildAnalysisService,
|
||||
rawInput: unknown,
|
||||
retention: AnalysisViewRetention,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const operation = "inspect_dart_aot";
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const parsed = dartAotInspectionInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, parsed.error.issues, rawInput, {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
if (parsed.data.detail === "summary") {
|
||||
const ready = requireAnalysisViewRetention(operation, retention);
|
||||
if (!ready.ok) return ready;
|
||||
}
|
||||
const { detail, ...providerInput } = parsed.data;
|
||||
const executed = await service.execute(operation, providerInput, options);
|
||||
if (!executed.ok || detail !== "summary") return executed;
|
||||
return summarizeRetainedAnalysis(executed.value, retention);
|
||||
};
|
||||
@@ -809,6 +809,42 @@ it("keeps an active script message bucket after its last message is evicted", as
|
||||
await manager.closeAll();
|
||||
});
|
||||
|
||||
it("retains the newest contiguous messages across repeated budget evictions", async () => {
|
||||
const { bindings, manager, started } = await startLocalAttachedSession();
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
bindings.device.session.nextPayload = { index: -1 };
|
||||
const loaded = await manager.loadScript(started.value.sessionId, {
|
||||
sourceKind: "inline",
|
||||
source: "send({index: -1});",
|
||||
});
|
||||
expect(loaded.ok).toBe(true);
|
||||
const script = bindings.device.session.scripts[0];
|
||||
expect(script).toBeDefined();
|
||||
if (script === undefined) return;
|
||||
|
||||
// About 500 of these fit the 16 MiB budget, so 2,000 sends evict and
|
||||
// compact the queue several times.
|
||||
const filler = "x".repeat(32_000);
|
||||
for (let index = 0; index < 2_000; index += 1)
|
||||
script.message.emit({ type: "send", payload: { index, filler } }, null);
|
||||
|
||||
const status = manager.status(started.value.sessionId);
|
||||
expect(status?.messagesTruncated).toBe(true);
|
||||
const indexes = (status?.messages ?? []).map(
|
||||
(message) => (message as { payload: { index: number } }).payload.index,
|
||||
);
|
||||
expect(indexes.length).toBeGreaterThan(400);
|
||||
expect(indexes.at(-1)).toBe(1_999);
|
||||
expect(indexes).toEqual(
|
||||
Array.from(
|
||||
{ length: indexes.length },
|
||||
(_, offset) => 2_000 - indexes.length + offset,
|
||||
),
|
||||
);
|
||||
await manager.closeAll();
|
||||
});
|
||||
|
||||
it("serializes a final remote release against a new same-endpoint session", async () => {
|
||||
const bindings = new FakeDeviceManager();
|
||||
let enteredRemoval: (() => void) | undefined;
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Replaceable offline build-information reader with no target-execution authority. */
|
||||
export interface GoBinaryPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -34,6 +34,10 @@ const architectureForSubject = (architecture: string) => {
|
||||
export class GoBinaryService {
|
||||
constructor(readonly provider: GoBinaryPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Inspect one explicitly selected file without acquiring a binary session. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
|
||||
@@ -78,6 +78,51 @@ const update = (
|
||||
});
|
||||
|
||||
describe("residual unknown registry reads and identity", () => {
|
||||
it("seals mutation Evidence without freezing caller-owned inputs", () => {
|
||||
const store = ledger();
|
||||
const recordMutation = mutation("mutable-record-mutation");
|
||||
const recorded = store.recordUnknown(
|
||||
input("Does record mutation evidence stay stable?"),
|
||||
recordMutation,
|
||||
);
|
||||
if (!recorded.ok) throw recorded.error;
|
||||
|
||||
const updateMutation = mutation("mutable-update-mutation");
|
||||
const updated = store.updateUnknown(update(recorded.value), updateMutation);
|
||||
if (!updated.ok) throw updated.error;
|
||||
const atomicEvidence = evidence("mutable-atomic-evidence");
|
||||
const atomicMutation = mutation("mutable-atomic-mutation");
|
||||
const atomicallyRecorded = store.recordWithUnknown(
|
||||
atomicEvidence,
|
||||
input("Does atomic evidence stay stable?"),
|
||||
atomicMutation,
|
||||
);
|
||||
if (!atomicallyRecorded.ok) throw atomicallyRecorded.error;
|
||||
|
||||
for (const callerEvidence of [
|
||||
recordMutation,
|
||||
updateMutation,
|
||||
atomicEvidence,
|
||||
atomicMutation,
|
||||
]) {
|
||||
expect(Object.isFrozen(callerEvidence)).toBe(false);
|
||||
const retained = store.forAnalysis(callerEvidence.evidence_id);
|
||||
if (retained === undefined) throw new Error("Missing retained Evidence");
|
||||
const originalResult = structuredClone(retained.normalized_result);
|
||||
expect(Object.isFrozen(retained)).toBe(true);
|
||||
Reflect.set(callerEvidence, "operation", "caller mutation");
|
||||
expect(
|
||||
Reflect.set(
|
||||
callerEvidence.normalized_result as object,
|
||||
"label",
|
||||
"caller nested mutation",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(retained.operation).not.toBe("caller mutation");
|
||||
expect(retained.normalized_result).toEqual(originalResult);
|
||||
}
|
||||
});
|
||||
|
||||
it("merges record-only bundles without changing retained unknown history", () => {
|
||||
const store = ledger();
|
||||
const created = store.recordUnknown(
|
||||
|
||||
@@ -11,11 +11,7 @@ import {
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import {
|
||||
immutableEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../../domain/evidence.js";
|
||||
import { immutableEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
updateResidualUnknown,
|
||||
@@ -220,7 +216,7 @@ export class EvidenceLedger {
|
||||
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
|
||||
let parsedMutation: Evidence;
|
||||
try {
|
||||
parsedMutation = parseEvidence(mutationEvidence);
|
||||
parsedMutation = immutableEvidence(mutationEvidence);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
@@ -255,8 +251,8 @@ export class EvidenceLedger {
|
||||
let evidence: Evidence;
|
||||
let mutation: Evidence;
|
||||
try {
|
||||
evidence = parseEvidence(evidenceInput);
|
||||
mutation = parseEvidence(mutationInput);
|
||||
evidence = immutableEvidence(evidenceInput);
|
||||
mutation = immutableEvidence(mutationInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Atomic Evidence validation failed", {
|
||||
@@ -394,7 +390,7 @@ export class EvidenceLedger {
|
||||
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
|
||||
let mutationEvidence: Evidence;
|
||||
try {
|
||||
mutationEvidence = parseEvidence(mutationEvidenceInput);
|
||||
mutationEvidence = immutableEvidence(mutationEvidenceInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { TraceMap } from "@jridgewell/trace-mapping";
|
||||
|
||||
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
|
||||
|
||||
const HASH = "a".repeat(64);
|
||||
|
||||
it("retains batched TraceMap-resolved paths and null source positions", () => {
|
||||
const sourceMapText = JSON.stringify({
|
||||
version: 3,
|
||||
file: "main.js",
|
||||
sourceRoot: "../src/",
|
||||
sources: ["cafe\u0301.ts", null, "other.ts"],
|
||||
sourcesContent: ["export const value = 1;", null, "export {};"],
|
||||
names: [],
|
||||
mappings: "",
|
||||
});
|
||||
const analysis = analyzeJavaScriptArtifactFiles({
|
||||
files: [
|
||||
{
|
||||
path: "dist/main.js.map",
|
||||
container_sha256: HASH,
|
||||
sha256: HASH,
|
||||
bytes: Buffer.byteLength(sourceMapText),
|
||||
inventory_artifact_id: "artifact_test",
|
||||
kind: "source-map",
|
||||
unpacked: false,
|
||||
text: { included: true, value: sourceMapText },
|
||||
},
|
||||
],
|
||||
containers: [],
|
||||
text_bytes_read: Buffer.byteLength(sourceMapText),
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
const originals = analysis.source_maps[0]?.sources;
|
||||
const original = originals?.[0];
|
||||
const producerPath = new TraceMap(
|
||||
{
|
||||
version: 3,
|
||||
file: "main.js",
|
||||
sourceRoot: "../src/",
|
||||
sources: ["cafe\u0301.ts", "", "other.ts"],
|
||||
names: [],
|
||||
mappings: "",
|
||||
},
|
||||
"file:///artifact/dist/main.js.map",
|
||||
).resolvedSources[0];
|
||||
|
||||
if (producerPath === undefined)
|
||||
throw new Error("TraceMap should resolve its single source declaration");
|
||||
expect(originals?.[1]?.reference).toBeNull();
|
||||
expect(originals?.[2]?.reference?.resolution).toEqual({
|
||||
kind: "artifact-relative",
|
||||
path: "src/other.ts",
|
||||
});
|
||||
expect(original?.reference).toMatchObject({
|
||||
source_name: "cafe\u0301.ts",
|
||||
source_root: "../src/",
|
||||
map_path: "dist/main.js.map",
|
||||
resolution: {
|
||||
kind: "artifact-relative",
|
||||
path: "src/cafe\u0301.ts",
|
||||
},
|
||||
});
|
||||
expect(original?.reference?.resolution).toEqual({
|
||||
kind: "artifact-relative",
|
||||
path: decodeURIComponent(
|
||||
new URL(producerPath).pathname.slice("/artifact/".length),
|
||||
),
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
import { resolveJavaScriptSourceMapReferences } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
import { analyzeParsedJavaScriptStaticSourceSteps } from "../../domain/javascript/javascriptStaticAnalysis.js";
|
||||
import {
|
||||
analyzeParsedJavaScriptSemanticsSteps,
|
||||
@@ -384,7 +384,10 @@ function* analyzeArtifactFileSteps<
|
||||
analysis.parse_status === "complete" || analysis.parse_status === "partial"
|
||||
? yield* analyzeParsedJavaScriptSemanticsSteps(
|
||||
parsed,
|
||||
moduleKindForJavaScriptReference(file.path, "static-import"),
|
||||
moduleResolutionModeForJavaScriptReference(
|
||||
file.path,
|
||||
"static-import",
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const projected =
|
||||
@@ -561,21 +564,27 @@ const collectSourceMapOriginals = (
|
||||
"Source map sourceRoot must be a string or null.",
|
||||
);
|
||||
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : null;
|
||||
for (const [index, raw] of names.entries()) {
|
||||
const sourceNames: (string | null)[] = [];
|
||||
for (const raw of names) {
|
||||
if (raw !== null && typeof raw !== "string")
|
||||
return invalidSourceMap(
|
||||
file,
|
||||
"Source map contains a non-string source name.",
|
||||
);
|
||||
sourceNames.push(raw);
|
||||
}
|
||||
const references = resolveJavaScriptSourceMapReferences(
|
||||
sourceNames,
|
||||
root,
|
||||
file.path,
|
||||
);
|
||||
for (const [index, reference] of references.entries()) {
|
||||
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
|
||||
const content = typeof rawContent === "string" ? rawContent : null;
|
||||
sources.push({
|
||||
source_index: index,
|
||||
declaration_index: declarationIndex++,
|
||||
reference:
|
||||
typeof raw === "string"
|
||||
? resolveJavaScriptSourceMapReference(raw, root, file.path)
|
||||
: null,
|
||||
reference,
|
||||
content,
|
||||
content_sha256: content === null ? null : sha256(content),
|
||||
});
|
||||
|
||||
@@ -66,6 +66,7 @@ export interface AstEdgeInput {
|
||||
|
||||
/** Inferred static relationship edge values. */
|
||||
export interface InferenceEdgeInput extends AstEdgeInput {
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relation:
|
||||
| "imports"
|
||||
| "loads"
|
||||
@@ -162,6 +163,9 @@ export const addStaticInferenceEdge = (
|
||||
range: input.range,
|
||||
operation: "map-static-relationship",
|
||||
coverage: input.coverage,
|
||||
...(input.limitations === undefined
|
||||
? {}
|
||||
: { limitations: input.limitations }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -347,7 +351,7 @@ export const resolveArtifactPath = (
|
||||
specifier: string,
|
||||
sourcePath: string,
|
||||
files: ReadonlyMap<string, JavaScriptArtifactFile>,
|
||||
moduleKind?: "import" | "require",
|
||||
moduleKind?: "import" | "require" | "compiler-dependent",
|
||||
): string | null =>
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
javascriptAnalysisCoverage,
|
||||
linkElectronRoleToAsset,
|
||||
moduleLookupKey,
|
||||
resolveArtifactPath,
|
||||
selfReferenceOmissions,
|
||||
sourceNodeFor,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
@@ -23,9 +22,11 @@ import {
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
moduleKindForJavaScriptReference,
|
||||
artifactPathResolutionProperties,
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
} from "./JavaScriptArtifactPathResolution.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
|
||||
type StaticReference = JavaScriptStaticAnalysis["references"][number];
|
||||
type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number];
|
||||
@@ -41,9 +42,12 @@ interface FindingInput<Value> {
|
||||
}
|
||||
|
||||
interface ResolvedReference {
|
||||
readonly path: string;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly path: string | null;
|
||||
readonly file: JavaScriptArtifactFile | null;
|
||||
readonly node: ApplicationNode;
|
||||
readonly limitations: readonly string[];
|
||||
readonly resolutionStatus?: string;
|
||||
readonly resolution?: ArtifactPathResolution;
|
||||
}
|
||||
|
||||
/** Project imports, workers, roles, endpoints, storage, and source-map links. */
|
||||
@@ -90,7 +94,7 @@ const addReference = (
|
||||
const resolved =
|
||||
input.value.specifier === null
|
||||
? null
|
||||
: resolveReference(context, input.file.path, input.value);
|
||||
: resolveReference(context, input.file.path, input.value, input.coverage);
|
||||
if (input.value.kind === "worker" || input.value.kind === "service-worker") {
|
||||
const worker = context.accumulator.addNode({
|
||||
kind: input.value.kind === "worker" ? "worker" : "service-worker",
|
||||
@@ -126,7 +130,7 @@ const addReference = (
|
||||
relation: "loads",
|
||||
properties: { kind: input.value.kind },
|
||||
});
|
||||
if (resolved !== null)
|
||||
if (resolved !== null && resolved.path !== null)
|
||||
addStaticInferenceEdge(context, {
|
||||
source: worker,
|
||||
target: resolved.node,
|
||||
@@ -135,6 +139,7 @@ const addReference = (
|
||||
coverage: input.coverage,
|
||||
relation: "maps_to",
|
||||
properties: { resolved_path: resolved.path },
|
||||
limitations: resolved.limitations,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -154,13 +159,25 @@ const addReference = (
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: resolved?.file.kind === "native-addon" ? "loads" : "imports",
|
||||
relation: resolved?.file?.kind === "native-addon" ? "loads" : "imports",
|
||||
properties: {
|
||||
kind: input.value.kind,
|
||||
specifier: input.value.specifier,
|
||||
expression: input.value.expression,
|
||||
resolution_mode:
|
||||
input.value.kind === "static-import" ||
|
||||
input.value.kind === "dynamic-import" ||
|
||||
input.value.kind === "require"
|
||||
? moduleResolutionModeForJavaScriptReference(
|
||||
input.file.path,
|
||||
input.value.kind,
|
||||
)
|
||||
: null,
|
||||
resolved_path: resolved?.path ?? null,
|
||||
resolution_status: resolved?.resolutionStatus ?? null,
|
||||
...artifactPathResolutionProperties(resolved?.resolution),
|
||||
},
|
||||
...(resolved === null ? {} : { limitations: resolved.limitations }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -373,6 +390,7 @@ const resolveReference = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
sourcePath: string,
|
||||
reference: StaticReference,
|
||||
coverage: JavaScriptArtifactGraphCoverage,
|
||||
): ResolvedReference | null => {
|
||||
const specifier = reference.specifier;
|
||||
if (specifier === null) return null;
|
||||
@@ -392,30 +410,70 @@ const resolveReference = (
|
||||
const file = context.filesByPath.get(sourcePath);
|
||||
return file === undefined
|
||||
? null
|
||||
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
|
||||
: {
|
||||
path: `${sourcePath}#module:${specifier}`,
|
||||
file,
|
||||
node: module,
|
||||
limitations: [],
|
||||
};
|
||||
}
|
||||
// Worker scripts are URLs relative to the script, not module specifiers.
|
||||
const path = isWorker
|
||||
const resolution = isWorker
|
||||
? resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
sourcePath,
|
||||
context: "url-reference",
|
||||
files: context.filesByPath,
|
||||
}).resolved_path
|
||||
: resolveArtifactPath(
|
||||
specifier,
|
||||
})
|
||||
: resolveArtifactPathByContext({
|
||||
declaredPath: 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;
|
||||
context: "module-specifier",
|
||||
files: context.filesByPath,
|
||||
...("require" === reference.kind ||
|
||||
"static-import" === reference.kind ||
|
||||
"dynamic-import" === reference.kind
|
||||
? {
|
||||
moduleKind: moduleResolutionModeForJavaScriptReference(
|
||||
sourcePath,
|
||||
reference.kind,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const path = resolution.resolved_path;
|
||||
if (path === null) {
|
||||
if (isWorker) return null;
|
||||
const source = context.filesByPath.get(sourcePath);
|
||||
return source === undefined
|
||||
? null
|
||||
: {
|
||||
path: null,
|
||||
file: null,
|
||||
node: unresolvedReferenceNode(
|
||||
context,
|
||||
source,
|
||||
reference,
|
||||
coverage,
|
||||
resolution,
|
||||
),
|
||||
limitations: resolution.limitations,
|
||||
resolutionStatus: resolution.resolution_status,
|
||||
resolution,
|
||||
};
|
||||
}
|
||||
const file = context.filesByPath.get(path);
|
||||
const node = context.fileNodes.get(path);
|
||||
return file === undefined || node === undefined ? null : { path, file, node };
|
||||
return file === undefined || node === undefined
|
||||
? null
|
||||
: {
|
||||
path,
|
||||
file,
|
||||
node,
|
||||
limitations: resolution.limitations,
|
||||
resolutionStatus: resolution.resolution_status,
|
||||
resolution,
|
||||
};
|
||||
};
|
||||
|
||||
const resolveBundlerChunkReference = (
|
||||
@@ -453,7 +511,7 @@ const resolveBundlerChunkReference = (
|
||||
const node = unique[0];
|
||||
return node === undefined
|
||||
? null
|
||||
: { path: `${sourcePath}#chunk:${key}`, file, node };
|
||||
: { path: `${sourcePath}#chunk:${key}`, file, node, limitations: [] };
|
||||
};
|
||||
|
||||
const unresolvedReferenceNode = (
|
||||
@@ -461,6 +519,7 @@ const unresolvedReferenceNode = (
|
||||
file: JavaScriptArtifactFile,
|
||||
reference: StaticReference,
|
||||
coverage: JavaScriptArtifactGraphCoverage,
|
||||
resolution?: ArtifactPathResolution,
|
||||
): ApplicationNode =>
|
||||
context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
@@ -477,6 +536,10 @@ const unresolvedReferenceNode = (
|
||||
specifier: reference.specifier,
|
||||
expression: reference.expression,
|
||||
resolution: "unresolved",
|
||||
...(resolution === undefined
|
||||
? {}
|
||||
: { resolution_status: resolution.resolution_status }),
|
||||
...artifactPathResolutionProperties(resolution),
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: file.sha256,
|
||||
@@ -487,6 +550,7 @@ const unresolvedReferenceNode = (
|
||||
confidence: "low",
|
||||
limitations: [
|
||||
"The static reference could not be resolved within the inventoried artifact.",
|
||||
...(resolution?.limitations ?? []),
|
||||
],
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -1890,21 +1890,40 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
|
||||
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("TypeScript declaration fallback ownership", () => {
|
||||
const container = "container";
|
||||
|
||||
it.each([
|
||||
["./dep.js", "src/dep.d.ts"],
|
||||
["./cfg.mjs", "src/cfg.d.mts"],
|
||||
["./legacy.cjs", "src/legacy.d.cts"],
|
||||
] as const)(
|
||||
"resolves %s to a declaration counterpart",
|
||||
"retains %s as compile-time evidence without inventing a runtime target",
|
||||
(specifier, target) => {
|
||||
const files = fileMap([
|
||||
file("src/main.ts", container),
|
||||
file(target, container, "export const value = 1;"),
|
||||
]);
|
||||
for (const moduleKind of ["import", "require"] as const) {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: specifier,
|
||||
sourcePath: "src/main.ts",
|
||||
context: "module-specifier",
|
||||
moduleKind,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "unavailable",
|
||||
resolved_path: null,
|
||||
candidate_path: target,
|
||||
});
|
||||
}
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: specifier,
|
||||
declaredPath: "./" + target.slice(4),
|
||||
sourcePath: "src/main.ts",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
|
||||
@@ -19,7 +19,13 @@ import {
|
||||
classifyPackageImportTargetString,
|
||||
lookupExactPackageImport,
|
||||
} from "../../domain/javascript/javascriptPackageImportAliases.js";
|
||||
import { typescriptEmittedSourceCandidates } from "../TypeScriptEmittedSourceCandidates.js";
|
||||
import {
|
||||
typescriptEmittedSourceCandidates,
|
||||
type TypeScriptEmittedSourceCandidate,
|
||||
} from "../TypeScriptEmittedSourceCandidates.js";
|
||||
import { isRelativeJavaScriptModuleSpecifier } from "../../domain/javascript/javascriptModuleSpecifier.js";
|
||||
import type { JavaScriptModuleResolutionMode } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
type ArtifactPathResolutionContext =
|
||||
| "package-entrypoint"
|
||||
@@ -38,6 +44,16 @@ interface ArtifactPathResolutionBase {
|
||||
readonly declared_path: string;
|
||||
readonly resolution_context: ArtifactPathResolutionContext;
|
||||
readonly limitations: readonly string[];
|
||||
readonly conditional_resolutions?: readonly ConditionalModuleResolution[];
|
||||
readonly candidate_path?: string;
|
||||
}
|
||||
|
||||
export interface ConditionalModuleResolution {
|
||||
readonly mode: "import" | "require";
|
||||
readonly resolution_status: UnresolvedArtifactPathStatus | "resolved";
|
||||
readonly resolved_path: string | null;
|
||||
readonly candidate_path?: string;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Explicit outcome of artifact-confined path resolution. */
|
||||
@@ -61,26 +77,13 @@ export interface ResolveArtifactPathInput {
|
||||
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
|
||||
readonly htmlBaseHref?: string | null;
|
||||
/** Import/require semantics; runtime resource paths omit this provenance. */
|
||||
readonly moduleKind?: "import" | "require";
|
||||
readonly moduleKind?: JavaScriptModuleResolutionMode;
|
||||
}
|
||||
|
||||
/** Loader selected by a source-level JavaScript module reference. */
|
||||
export const moduleKindForJavaScriptReference = (
|
||||
sourcePath: string,
|
||||
referenceKind: "static-import" | "dynamic-import" | "require",
|
||||
resolutionMode?: "import" | "require",
|
||||
): "import" | "require" =>
|
||||
resolutionMode ??
|
||||
(referenceKind === "require" ||
|
||||
(referenceKind === "static-import" &&
|
||||
posix.extname(sourcePath).toLowerCase() === ".cts")
|
||||
? "require"
|
||||
: "import");
|
||||
|
||||
/** Preserve an explicitly retained loader mode on graph relationships. */
|
||||
export const moduleResolutionModeProperties = (
|
||||
mode: "import" | "require" | undefined,
|
||||
): Readonly<Record<string, "import" | "require">> =>
|
||||
mode: JavaScriptModuleResolutionMode | undefined,
|
||||
): Readonly<Record<string, JavaScriptModuleResolutionMode>> =>
|
||||
mode === undefined ? {} : { resolution_mode: mode };
|
||||
|
||||
const EXTENSIONS = [
|
||||
@@ -109,43 +112,116 @@ interface PackageFileTarget {
|
||||
readonly url: URL;
|
||||
}
|
||||
|
||||
type CandidateResolution =
|
||||
| {
|
||||
readonly resolvedPath: string;
|
||||
readonly status: "resolved";
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
type CandidateResolution = {
|
||||
readonly limitations: readonly string[];
|
||||
readonly candidatePath?: string;
|
||||
readonly conditionalResolutions?: readonly ConditionalModuleResolution[];
|
||||
} & (
|
||||
| { readonly resolvedPath: string; readonly status: "resolved" }
|
||||
| {
|
||||
readonly resolvedPath: null;
|
||||
readonly status: UnresolvedArtifactPathStatus;
|
||||
readonly limitations: readonly string[];
|
||||
/** A truthy package main failed, so Node must not try ancestor packages. */
|
||||
readonly stopsAncestorLookup?: true;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
/** Resolve one declaration while preserving its original input identity. */
|
||||
export const resolveArtifactPathByContext = (
|
||||
input: ResolveArtifactPathInput,
|
||||
): ArtifactPathResolution => {
|
||||
const resolution = resolvePath(input);
|
||||
const facts = {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
limitations: resolution.limitations,
|
||||
...(resolution.candidatePath === undefined
|
||||
? {}
|
||||
: { candidate_path: resolution.candidatePath }),
|
||||
...(resolution.conditionalResolutions === undefined
|
||||
? {}
|
||||
: { conditional_resolutions: resolution.conditionalResolutions }),
|
||||
};
|
||||
return resolution.status === "resolved"
|
||||
? {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
...facts,
|
||||
resolved_path: resolution.resolvedPath,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
}
|
||||
: {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
resolved_path: null,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
};
|
||||
: { ...facts, resolved_path: null, resolution_status: resolution.status };
|
||||
};
|
||||
|
||||
/** Project retained conditional identities without flattening them into display text. */
|
||||
export const artifactPathResolutionProperties = (
|
||||
resolution: ArtifactPathResolution | undefined,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
...(resolution?.candidate_path === undefined
|
||||
? {}
|
||||
: { candidate_path: resolution.candidate_path }),
|
||||
...(resolution?.conditional_resolutions === undefined
|
||||
? {}
|
||||
: {
|
||||
conditional_resolutions: resolution.conditional_resolutions.map(
|
||||
(branch) => ({
|
||||
mode: branch.mode,
|
||||
resolution_status: branch.resolution_status,
|
||||
resolved_path: branch.resolved_path,
|
||||
limitations: [...branch.limitations],
|
||||
...(branch.candidate_path === undefined
|
||||
? {}
|
||||
: { candidate_path: branch.candidate_path }),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
const conditionalResolution = (
|
||||
mode: "import" | "require",
|
||||
result: CandidateResolution,
|
||||
): ConditionalModuleResolution => ({
|
||||
mode,
|
||||
resolution_status: result.status,
|
||||
resolved_path: result.resolvedPath,
|
||||
limitations: result.limitations,
|
||||
...(result.candidatePath === undefined
|
||||
? {}
|
||||
: { candidate_path: result.candidatePath }),
|
||||
});
|
||||
|
||||
const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
if (input.moduleKind === "compiler-dependent") {
|
||||
const imported = resolvePath({ ...input, moduleKind: "import" });
|
||||
const required = resolvePath({ ...input, moduleKind: "require" });
|
||||
const sameOutcome =
|
||||
imported.status === required.status &&
|
||||
imported.resolvedPath === required.resolvedPath &&
|
||||
imported.candidatePath === required.candidatePath;
|
||||
const limitation =
|
||||
"Static TypeScript loader mode is compiler-dependent without retained compiler options. " +
|
||||
(sameOutcome
|
||||
? "Node import and require resolution agree on this outcome."
|
||||
: "Node import and require resolution disagree; neither branch is an established target.");
|
||||
return sameOutcome
|
||||
? {
|
||||
...imported,
|
||||
limitations: [
|
||||
...new Set([
|
||||
...imported.limitations,
|
||||
...required.limitations,
|
||||
limitation,
|
||||
]),
|
||||
],
|
||||
}
|
||||
: {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
limitations: [limitation],
|
||||
conditionalResolutions: [
|
||||
conditionalResolution("import", imported),
|
||||
conditionalResolution("require", required),
|
||||
],
|
||||
};
|
||||
}
|
||||
// Package import keys are literal lookup identities, not artifact paths.
|
||||
// The selected target is admitted separately by resolveExportTarget.
|
||||
if (
|
||||
@@ -166,7 +242,7 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
);
|
||||
const isModuleUrlPath =
|
||||
input.context === "module-specifier" &&
|
||||
(input.declaredPath.startsWith(".") ||
|
||||
(isRelativeJavaScriptModuleSpecifier(input.declaredPath) ||
|
||||
input.declaredPath.startsWith("/") ||
|
||||
fileUrlPath(input.declaredPath) !== undefined);
|
||||
const emittedSourceCandidates =
|
||||
@@ -175,12 +251,47 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
: [];
|
||||
if (isModuleUrlPath && input.moduleKind === "import")
|
||||
return (
|
||||
resolveFileCandidates(input, [confined, ...emittedSourceCandidates]) ??
|
||||
notFoundCandidate()
|
||||
resolveRuntimeSourceCandidates(
|
||||
input,
|
||||
confined,
|
||||
emittedSourceCandidates,
|
||||
) ?? notFoundCandidate()
|
||||
);
|
||||
return resolveCandidate(input, confined, new Set(), emittedSourceCandidates);
|
||||
};
|
||||
|
||||
const resolveRuntimeSourceCandidates = (
|
||||
input: ResolveArtifactPathInput,
|
||||
exactPath: string,
|
||||
sourceCandidates: readonly TypeScriptEmittedSourceCandidate[],
|
||||
): CandidateResolution | null => {
|
||||
const source = input.files.get(input.sourcePath);
|
||||
const exactCandidate: TypeScriptEmittedSourceCandidate = {
|
||||
path: exactPath,
|
||||
kind: "implementation",
|
||||
};
|
||||
for (const candidate of [exactCandidate, ...sourceCandidates]) {
|
||||
const target = input.files.get(candidate.path);
|
||||
if (
|
||||
target === undefined ||
|
||||
(source !== undefined &&
|
||||
target.container_sha256 !== source.container_sha256)
|
||||
)
|
||||
continue;
|
||||
return candidate.kind === "declaration"
|
||||
? {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
candidatePath: candidate.path,
|
||||
limitations: [
|
||||
"Only a TypeScript declaration fallback was found; it does not establish the requested runtime module.",
|
||||
],
|
||||
}
|
||||
: { resolvedPath: candidate.path, status: "resolved", limitations: [] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const rejectDeclaration = (declared: string): CandidateResolution | null => {
|
||||
if (declared.length === 0)
|
||||
return unresolvedCandidate("rejected", ["The declared path is empty."]);
|
||||
@@ -229,7 +340,10 @@ const contextualCandidate = (
|
||||
return unresolvedCandidate("external", [
|
||||
"URL and Node builtin schemes are outside static artifact module resolution.",
|
||||
]);
|
||||
if (!declared.startsWith(".") && !declared.startsWith("/"))
|
||||
if (
|
||||
!isRelativeJavaScriptModuleSpecifier(declared) &&
|
||||
!declared.startsWith("/")
|
||||
)
|
||||
return bareModuleCandidate(input);
|
||||
if (input.moduleKind !== "require") {
|
||||
const decoded = decodeModuleUrlPath(stripQueryAndFragment(declared));
|
||||
@@ -275,7 +389,10 @@ const contextualCandidate = (
|
||||
"URL",
|
||||
);
|
||||
}
|
||||
return relativeCandidate(input.sourcePath, declared);
|
||||
const candidate = relativeCandidate(input.sourcePath, declared);
|
||||
return context === "module-specifier" && input.moduleKind === "import"
|
||||
? exactUrlPathCandidate(declared, candidate, "module URL")
|
||||
: candidate;
|
||||
};
|
||||
|
||||
const decodeModuleUrlPath = (
|
||||
@@ -310,9 +427,12 @@ const bareModuleCandidate = (
|
||||
return unresolvedCandidate("external", [
|
||||
"The bare specifier is a Node builtin or invalid package name.",
|
||||
]);
|
||||
if (input.moduleKind === "import" && request.packageName.includes("%"))
|
||||
if (
|
||||
input.moduleKind === "import" &&
|
||||
(request.packageName.startsWith(".") || request.packageName.includes("%"))
|
||||
)
|
||||
return unresolvedCandidate("rejected", [
|
||||
"Percent signs are not admitted in ES module package names.",
|
||||
"ES module package names cannot start with a dot or contain percent signs.",
|
||||
]);
|
||||
const self = packageSelfCandidate(input, request);
|
||||
if (self !== null) return self;
|
||||
@@ -735,7 +855,7 @@ const htmlCandidate = (
|
||||
const exactUrlPathCandidate = (
|
||||
declared: string,
|
||||
candidate: string,
|
||||
kind: "HTML" | "URL",
|
||||
kind: "HTML" | "URL" | "module URL",
|
||||
): string | CandidateResolution => {
|
||||
if (!urlPathIsDirectory(declared)) return candidate;
|
||||
const confined = confineCandidate(candidate);
|
||||
@@ -839,12 +959,10 @@ const resolveCandidate = (
|
||||
input: ResolveArtifactPathInput,
|
||||
candidate: string,
|
||||
packageChain: ReadonlySet<string>,
|
||||
emittedSourceCandidates: readonly string[] = [],
|
||||
emittedSourceCandidates: readonly TypeScriptEmittedSourceCandidate[] = [],
|
||||
): CandidateResolution =>
|
||||
resolveFileCandidates(input, [
|
||||
...fileCandidates(candidate, input.moduleKind),
|
||||
...emittedSourceCandidates,
|
||||
]) ??
|
||||
resolveFileCandidates(input, fileCandidates(candidate, input.moduleKind)) ??
|
||||
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates) ??
|
||||
resolveDirectory(
|
||||
input,
|
||||
candidate,
|
||||
@@ -930,11 +1048,26 @@ const resolveFileCandidates = (
|
||||
(source === undefined ||
|
||||
target.container_sha256 === source.container_sha256)
|
||||
)
|
||||
return { resolvedPath: path, status: "resolved", limitations: [] };
|
||||
return isRuntimeDeclarationPath(input, path)
|
||||
? {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
candidatePath: path,
|
||||
limitations: [
|
||||
`The TypeScript declaration ${path} is compile-time evidence and cannot identify a runtime module implementation.`,
|
||||
],
|
||||
}
|
||||
: { resolvedPath: path, status: "resolved", limitations: [] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const isRuntimeDeclarationPath = (
|
||||
input: ResolveArtifactPathInput,
|
||||
path: string,
|
||||
): boolean =>
|
||||
input.moduleKind !== undefined && /\.d\.(?:ts|mts|cts)$/iu.test(path);
|
||||
|
||||
const NODE_MODULE_EXTENSIONS = [".js", ".json", ".node"] as const;
|
||||
|
||||
const fileCandidates = (
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticModuleLink,
|
||||
} from "../../domain/javascript/javascriptSemanticIr.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
|
||||
import {
|
||||
addAstContainsEdge,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
moduleKindForJavaScriptReference,
|
||||
artifactPathResolutionProperties,
|
||||
moduleResolutionModeProperties,
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
@@ -54,6 +55,7 @@ interface RelationshipInput {
|
||||
type ResolvedModuleTarget = {
|
||||
readonly node: ApplicationNode;
|
||||
readonly limitations: readonly string[];
|
||||
readonly resolution?: ArtifactPathResolution;
|
||||
} & (
|
||||
| {
|
||||
readonly path: string;
|
||||
@@ -81,8 +83,13 @@ export const addJavaScriptSourceModules = (
|
||||
if (asset === undefined || semantic === null || program === undefined)
|
||||
continue;
|
||||
const exports = semantic.ir.moduleLinks
|
||||
.flatMap(({ exportedName }) =>
|
||||
exportedName === null ? [] : [exportedName],
|
||||
.flatMap(({ exportedName, kind }) =>
|
||||
exportedName === null || kind === "type-import" ? [] : [exportedName],
|
||||
)
|
||||
.sort(compareUnicodeCodePoints);
|
||||
const typeExports = semantic.ir.moduleLinks
|
||||
.flatMap(({ exportedName, kind }) =>
|
||||
exportedName === null || kind !== "type-import" ? [] : [exportedName],
|
||||
)
|
||||
.sort(compareUnicodeCodePoints);
|
||||
const retainedExports = [...new Set(exports)];
|
||||
@@ -105,8 +112,12 @@ export const addJavaScriptSourceModules = (
|
||||
import_relationships: semantic.ir.moduleLinks.filter(
|
||||
({ kind }) => kind === "import" || kind === "require",
|
||||
).length,
|
||||
type_relationships: semantic.ir.moduleLinks.filter(
|
||||
({ kind }) => kind === "type-import",
|
||||
).length,
|
||||
export_relationships: exports.length,
|
||||
export_names: retainedExports,
|
||||
type_export_names: [...new Set(typeExports)],
|
||||
omitted_export_names: 0,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
@@ -152,6 +163,7 @@ export function* addJavaScriptModuleRelationshipsSteps(
|
||||
for (const link of semantic.ir.moduleLinks) {
|
||||
// One module can export thousands of bindings, each with return shapes.
|
||||
yield;
|
||||
if (link.kind === "type-import") continue;
|
||||
const input = { context, file, semantic, source, link };
|
||||
if (isExportLink(link)) addExportRelationship(input, omissions);
|
||||
else if (link.specifier !== null)
|
||||
@@ -277,7 +289,7 @@ const resolveModuleTarget = (
|
||||
sourcePath: input.file.path,
|
||||
context: "module-specifier",
|
||||
files: input.context.filesByPath,
|
||||
moduleKind: moduleKindForJavaScriptReference(
|
||||
moduleKind: moduleResolutionModeForJavaScriptReference(
|
||||
input.file.path,
|
||||
input.link.kind === "require" || input.link.kind === "commonjs-export"
|
||||
? "require"
|
||||
@@ -287,15 +299,12 @@ const resolveModuleTarget = (
|
||||
});
|
||||
if (resolution.resolution_status !== "resolved")
|
||||
return {
|
||||
node: unresolvedModuleNode(
|
||||
input,
|
||||
specifier,
|
||||
resolution.resolution_status,
|
||||
),
|
||||
node: unresolvedModuleNode(input, specifier, resolution),
|
||||
path: null,
|
||||
file: null,
|
||||
status: resolution.resolution_status,
|
||||
limitations: resolution.limitations,
|
||||
resolution,
|
||||
};
|
||||
const path = resolution.resolved_path;
|
||||
const file = input.context.filesByPath.get(path);
|
||||
@@ -312,20 +321,24 @@ const resolveModuleTarget = (
|
||||
file,
|
||||
status: "resolved",
|
||||
limitations: resolution.limitations,
|
||||
resolution,
|
||||
};
|
||||
};
|
||||
|
||||
const unresolvedModuleNode = (
|
||||
input: RelationshipInput,
|
||||
specifier: string,
|
||||
status: Exclude<ResolvedModuleTarget["status"], "resolved">,
|
||||
resolution: Extract<
|
||||
ArtifactPathResolution,
|
||||
{ resolution_status: Exclude<ResolvedModuleTarget["status"], "resolved"> }
|
||||
>,
|
||||
): ApplicationNode =>
|
||||
input.context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
"unresolved-semantic-module",
|
||||
`${status}:${specifier}`,
|
||||
`${resolution.resolution_status}:${specifier}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
@@ -333,7 +346,8 @@ const unresolvedModuleNode = (
|
||||
properties: {
|
||||
semantic_role: "module-reference",
|
||||
declared_specifier: specifier,
|
||||
resolution_status: status,
|
||||
resolution_status: resolution.resolution_status,
|
||||
...artifactPathResolutionProperties(resolution),
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.file.sha256,
|
||||
@@ -354,6 +368,9 @@ const moduleOriginForExport = (
|
||||
): JavaScriptModuleOrigin | null => {
|
||||
if (link.specifier !== null)
|
||||
return {
|
||||
...(link.resolutionMode === undefined
|
||||
? {}
|
||||
: { resolutionMode: link.resolutionMode }),
|
||||
specifier: link.specifier,
|
||||
importedPath: link.importedName === null ? [] : [link.importedName],
|
||||
};
|
||||
@@ -383,6 +400,7 @@ const relationshipProperties = (
|
||||
exported_name: link.exportedName,
|
||||
resolved_path: target?.path ?? null,
|
||||
resolution_status: target?.status ?? null,
|
||||
...artifactPathResolutionProperties(target?.resolution),
|
||||
target_file_kind: target?.file?.kind ?? null,
|
||||
target_json_status:
|
||||
target?.file?.kind === "json" || target?.file?.kind === "package-json"
|
||||
@@ -431,6 +449,7 @@ const moduleFormat = (
|
||||
const extension = posix.extname(path).toLowerCase();
|
||||
if (extension === ".mjs" || extension === ".mts") return "esm";
|
||||
if (extension === ".cjs" || extension === ".cts") return "commonjs";
|
||||
if (extension === ".ts" || extension === ".tsx") return "unknown";
|
||||
const esm = ir.moduleLinks.some(({ kind }) =>
|
||||
["import", "export", "re-export"].includes(kind),
|
||||
);
|
||||
|
||||
@@ -22,6 +22,26 @@ const exampleMethod = () => {
|
||||
};
|
||||
|
||||
describe("managed decompiler reconstruction import", () => {
|
||||
it("reports UTF-8 byte totals while preserving UTF-16 text lengths", () => {
|
||||
const text = 'return "é"; // 😀';
|
||||
const method = exampleMethod();
|
||||
const result = importManagedReconstructionEvidence({
|
||||
...MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
|
||||
methods: [
|
||||
{
|
||||
...method,
|
||||
reconstruction: { ...method.reconstruction, text },
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
summary: { total_text_bytes: 20 },
|
||||
methods: [{ reconstruction: { text, text_length: 17 } }],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects reconstruction text hash drift", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { PcapRequest } from "../../domain/pcap/pcapAnalysis.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/**
|
||||
* Packet-capture analysis boundary over caller-supplied tshark/capinfos.
|
||||
* Implementation details belong to the provider adapter.
|
||||
*/
|
||||
export interface PcapAnalysisPort {
|
||||
/** Probe both tools without reading any capture file. */
|
||||
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
|
||||
/** Retry cleanup of retained owned commands and capture snapshots. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
request: PcapRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PcapAnalysisPort } from "./PcapAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import {
|
||||
pcapRequestSchema,
|
||||
type PcapOperation,
|
||||
} from "../../domain/pcap/pcapAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { createPcapEvidence } from "../../domain/pcap/pcapEvidence.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP admission, execution, and Evidence composition for pcap. */
|
||||
export class PcapAnalysisService {
|
||||
constructor(readonly provider: PcapAnalysisPort) {}
|
||||
|
||||
/** Run one caller-selected pcap request and retain capture identity inline. */
|
||||
async execute(
|
||||
operation: PcapOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const request = pcapRequestSchema.safeParse({ operation, input });
|
||||
if (!request.success)
|
||||
return err(new AnalysisInputError(operation, { cause: request.error }));
|
||||
const executed = await this.provider.execute(request.data, options);
|
||||
if (!executed.ok) return executed;
|
||||
const execution = executed.value;
|
||||
return ok(createPcapEvidence(request.data, execution));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
inspectSignalDecodersInputSchema,
|
||||
signalDecodersSchema,
|
||||
type InspectSignalDecodersInput,
|
||||
} from "../../domain/signals/signalDecoders.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -24,6 +30,10 @@ export interface SignalRecordingPort {
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
inspectDecoders(
|
||||
input: InspectSignalDecodersInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -74,14 +84,58 @@ export class SignalRecordingService {
|
||||
"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 this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
async inspectDecoders(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_signal_decoders";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectSignalDecodersInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
const decoded = await this.provider.inspectDecoders(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = signalDecodersSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data) ||
|
||||
execution.subject?.path !== report.data.tool.path ||
|
||||
execution.subject.sha256 !== report.data.tool.sha256
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Decoder discovery returned malformed data or changed the selected installation/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
#evidence(
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
options?: ExecutionOptions,
|
||||
): Result<Evidence, AnalysisError> {
|
||||
const evidence = createEvidence(
|
||||
execution.subject ?? undefined,
|
||||
execution.provider,
|
||||
{
|
||||
operation,
|
||||
parameters,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
},
|
||||
);
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
|
||||
@@ -4,8 +4,14 @@ import type {
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { InspectWasmArtifactInput } from "../../domain/wasm/wasmArtifact.js";
|
||||
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Successful WASM inspection must identify the selected local file. */
|
||||
export type WasmArtifactExecution = Omit<AnalysisExecution, "subject"> & {
|
||||
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
|
||||
};
|
||||
|
||||
/** Replaceable offline WASM inspection engine, independent of target execution and network clients. */
|
||||
export interface WasmArtifactPort {
|
||||
/** Retry removal of retained workspaces; failures preserve ownership for another attempt. */
|
||||
@@ -13,5 +19,5 @@ export interface WasmArtifactPort {
|
||||
inspect(
|
||||
input: InspectWasmArtifactInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
): Promise<Result<WasmArtifactExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
@@ -57,6 +57,10 @@ export class ArtifactResourceScope {
|
||||
#draining: Promise<void> | undefined;
|
||||
#closed = false;
|
||||
|
||||
get hasPending(): boolean {
|
||||
return this.#pending.size > 0;
|
||||
}
|
||||
|
||||
/** Admit a resource operation while the scope remains open. */
|
||||
async run<T>(operation: () => Promise<T>): Promise<T> {
|
||||
while (true) {
|
||||
|
||||
@@ -8,11 +8,11 @@ import {
|
||||
type NativeCommandRunner,
|
||||
} from "../native/CommandRunner.js";
|
||||
import {
|
||||
lipoSubtypeBits,
|
||||
parseLipoArchitectures,
|
||||
type LipoArchitecture,
|
||||
} from "../native/parsers/lipo.js";
|
||||
import type { MachoSlice } from "../domain/apple/dylibResolution.js";
|
||||
import { machoCpuSubtypeBase } from "../domain/apple/machoCpuIdentity.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readMachoImage, type ReadAt } from "./apple/MachoLoadCommandReader.js";
|
||||
import {
|
||||
@@ -81,7 +81,9 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
if (!captured.ok)
|
||||
throw new ArtifactReaderFailure(
|
||||
captured.error.reason === "cancelled" ? "cancelled" : "unavailable",
|
||||
"lipo could not enumerate universal Mach-O slices",
|
||||
captured.error.detail === null
|
||||
? "lipo could not enumerate universal Mach-O slices"
|
||||
: `lipo could not enumerate universal Mach-O slices: ${captured.error.detail}`,
|
||||
{
|
||||
cause: captured.error,
|
||||
...(captured.error.cleanupFailure === null &&
|
||||
@@ -469,8 +471,10 @@ const lipoSubtypeMatches = (
|
||||
): boolean => {
|
||||
if (reported.cpu_subtype_code !== null)
|
||||
return reported.cpu_subtype_code === observedCpuSubtype;
|
||||
const bits = lipoSubtypeBits(reported.cpu_subtype);
|
||||
return bits === null || bits === (observedCpuSubtype & 0x00ffffff);
|
||||
return (
|
||||
reported.cpu_subtype_base === null ||
|
||||
reported.cpu_subtype_base === machoCpuSubtypeBase(observedCpuSubtype)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type NativeDmgInfo,
|
||||
} from "./NativeDmgOwnership.js";
|
||||
const HDIUTIL_COMMAND_TIMEOUT_MS = 120_000;
|
||||
const VERIFY_SETTLE_DELAYS_MS = [250, 500] as const;
|
||||
// APFS ejects and busy reporting can lag a detach attempt.
|
||||
const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const;
|
||||
const delay = (milliseconds: number): Promise<void> =>
|
||||
@@ -44,22 +45,30 @@ export interface NativeDmgHost {
|
||||
|
||||
class NativeDmgCommandFailure extends ArtifactReaderFailure {
|
||||
readonly processNotStarted: boolean;
|
||||
readonly verifyDiagnostic: string | undefined;
|
||||
readonly exitCode: number | null;
|
||||
|
||||
constructor(
|
||||
reason: ArtifactReaderFailure["reason"],
|
||||
failure: {
|
||||
readonly reason: ArtifactReaderFailure["reason"];
|
||||
readonly verifyDiagnostic?: string;
|
||||
},
|
||||
message: string,
|
||||
readonly stdout: string,
|
||||
options?: {
|
||||
readonly cause?: unknown;
|
||||
readonly processNotStarted?: boolean;
|
||||
readonly exitCode?: number;
|
||||
},
|
||||
) {
|
||||
super(
|
||||
reason,
|
||||
failure.reason,
|
||||
message,
|
||||
options?.cause === undefined ? undefined : { cause: options.cause },
|
||||
);
|
||||
this.processNotStarted = options?.processNotStarted ?? false;
|
||||
this.verifyDiagnostic = failure.verifyDiagnostic;
|
||||
this.exitCode = options?.exitCode ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +93,7 @@ const createSystemHost = (
|
||||
const output = execFileOutputFailure(cause);
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new NativeDmgCommandFailure(
|
||||
"cancelled",
|
||||
{ reason: "cancelled" },
|
||||
"DMG operation cancelled",
|
||||
output?.stdout ?? "",
|
||||
{ cause },
|
||||
@@ -99,7 +108,7 @@ const createSystemHost = (
|
||||
cause,
|
||||
};
|
||||
throw new NativeDmgCommandFailure(
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
classifyCommandFailure(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`,
|
||||
output?.stdout ?? "",
|
||||
{ cause, processNotStarted: processNotStarted(cause) },
|
||||
@@ -348,8 +357,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async #attach(signal?: AbortSignal): Promise<void> {
|
||||
await runChecked(this.host, ["verify", this.path], signal);
|
||||
this.#provenance.push(command(["verify", this.path], ["read"]));
|
||||
await this.#verify(signal);
|
||||
const baseline = await this.#readInfo();
|
||||
this.#baselineDevices = new Set(
|
||||
baseline.images.flatMap((image) =>
|
||||
@@ -431,6 +439,40 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
async #verify(signal?: AbortSignal): Promise<void> {
|
||||
const arguments_ = ["verify", this.path];
|
||||
const deadline = performance.now() + HDIUTIL_COMMAND_TIMEOUT_MS;
|
||||
for (let attempt = 0; ; attempt += 1) {
|
||||
if (signal?.aborted === true)
|
||||
throw new NativeDmgCommandFailure(
|
||||
{ reason: "cancelled" },
|
||||
"DMG operation cancelled",
|
||||
"",
|
||||
{ cause: signal.reason },
|
||||
);
|
||||
try {
|
||||
await runChecked(this.host, arguments_, signal, {
|
||||
timeoutMs: Math.max(1, Math.ceil(deadline - performance.now())),
|
||||
});
|
||||
this.#provenance.push(command(arguments_, ["read"]));
|
||||
return;
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof NativeDmgCommandFailure)) throw cause;
|
||||
this.#provenance.push(command(arguments_, ["read"], cause.exitCode));
|
||||
const delayMs = VERIFY_SETTLE_DELAYS_MS[attempt];
|
||||
// Retry only the producer's explicit transient diagnostic, before any mount.
|
||||
if (
|
||||
cause.verifyDiagnostic !== "Resource temporarily unavailable" ||
|
||||
delayMs === undefined ||
|
||||
deadline - performance.now() <= delayMs
|
||||
)
|
||||
throw cause;
|
||||
await (this.host.delay ?? delay)(delayMs);
|
||||
if (performance.now() >= deadline) throw cause;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #readInfo(): Promise<NativeDmgInfo> {
|
||||
const info = await runChecked(this.host, ["info", "-plist"], undefined, {
|
||||
timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS,
|
||||
@@ -501,14 +543,14 @@ const runChecked = async (
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new NativeDmgCommandFailure(
|
||||
"cancelled",
|
||||
{ reason: "cancelled" },
|
||||
"DMG operation cancelled",
|
||||
execFileOutputFailure(cause)?.stdout ?? "",
|
||||
{ cause },
|
||||
);
|
||||
const output = execFileOutputFailure(cause);
|
||||
throw new NativeDmgCommandFailure(
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
classifyCommandFailure(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(
|
||||
cause,
|
||||
arguments_,
|
||||
@@ -527,17 +569,17 @@ const runChecked = async (
|
||||
stdout: result.stdout,
|
||||
...(result.stderr === undefined ? {} : { stderr: result.stderr }),
|
||||
};
|
||||
const reason = commandFailureReason(failure, arguments_[0]);
|
||||
const classification = classifyCommandFailure(failure, arguments_[0]);
|
||||
const details = describeCommandFailure(failure, arguments_);
|
||||
const unknownVerifyFailure =
|
||||
arguments_[0] === "verify" && reason === "unavailable";
|
||||
arguments_[0] === "verify" && classification.reason === "unavailable";
|
||||
throw new NativeDmgCommandFailure(
|
||||
reason,
|
||||
classification,
|
||||
unknownVerifyFailure
|
||||
? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}`
|
||||
: `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`,
|
||||
result.stdout,
|
||||
{ cause: result.cause ?? failure },
|
||||
{ cause: result.cause ?? failure, exitCode: result.exitCode },
|
||||
);
|
||||
}
|
||||
return { stdout: result.stdout, exitCode: 0 };
|
||||
@@ -587,20 +629,36 @@ const processOutput = (cause: unknown, field: "stdout" | "stderr"): string => {
|
||||
return typeof value === "string" ? value : "";
|
||||
};
|
||||
|
||||
const commandFailureReason = (
|
||||
const classifyCommandFailure = (
|
||||
cause: unknown,
|
||||
operation: string | undefined,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
if (typeof cause !== "object" || cause === null) return "unavailable";
|
||||
): {
|
||||
readonly reason: ArtifactReaderFailure["reason"];
|
||||
readonly verifyDiagnostic?: string;
|
||||
} => {
|
||||
if (typeof cause !== "object" || cause === null)
|
||||
return { reason: "unavailable" };
|
||||
const code = Reflect.get(cause, "code");
|
||||
const exitCode = Reflect.get(cause, "exitCode");
|
||||
if (typeof code === "number" || typeof exitCode === "number")
|
||||
return operation === "verify" ? verifyFailureReason(cause) : "unavailable";
|
||||
if (typeof code === "number" || typeof exitCode === "number") {
|
||||
if (operation !== "verify") return { reason: "unavailable" };
|
||||
const diagnostic = verifyFailureDiagnostic(
|
||||
processOutput(cause, "stdout"),
|
||||
processOutput(cause, "stderr"),
|
||||
);
|
||||
return {
|
||||
reason: verifyFailureReason(diagnostic),
|
||||
...(diagnostic === undefined ? {} : { verifyDiagnostic: diagnostic }),
|
||||
};
|
||||
}
|
||||
if (code === "ENOENT") {
|
||||
const syscall = Reflect.get(cause, "syscall");
|
||||
return typeof syscall === "string" && syscall.startsWith("spawn")
|
||||
? "unavailable"
|
||||
: "io";
|
||||
return {
|
||||
reason:
|
||||
typeof syscall === "string" && syscall.startsWith("spawn")
|
||||
? "unavailable"
|
||||
: "io",
|
||||
};
|
||||
}
|
||||
if (
|
||||
code === "EACCES" ||
|
||||
@@ -613,17 +671,13 @@ const commandFailureReason = (
|
||||
code === "EMFILE" ||
|
||||
code === "ENFILE"
|
||||
)
|
||||
return "io";
|
||||
return "unavailable";
|
||||
return { reason: "io" };
|
||||
return { reason: "unavailable" };
|
||||
};
|
||||
|
||||
const verifyFailureReason = (
|
||||
cause: unknown,
|
||||
diagnostic: string | undefined,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
const diagnostic = verifyFailureDiagnostic(
|
||||
processOutput(cause, "stdout"),
|
||||
processOutput(cause, "stderr"),
|
||||
);
|
||||
switch (diagnostic) {
|
||||
// hdiutil follows AppleLanguages, so en-GB and en-AU spell it "recognised".
|
||||
case "image not recognized":
|
||||
@@ -656,11 +710,12 @@ const verifyFailureDiagnostic = (
|
||||
const command = (
|
||||
arguments_: readonly string[],
|
||||
effects: ArtifactCommand["effects"],
|
||||
exitCode: number | null = 0,
|
||||
): ArtifactCommand => ({
|
||||
tool: "/usr/bin/hdiutil",
|
||||
arguments: [...arguments_],
|
||||
tool_version: null,
|
||||
executable_sha256: null,
|
||||
exit_code: 0,
|
||||
exit_code: exitCode,
|
||||
effects,
|
||||
});
|
||||
|
||||
@@ -280,9 +280,11 @@ export class SafeOutputTree {
|
||||
}
|
||||
|
||||
/** Sync the owned output tree and prevent further writes through this instance. */
|
||||
async commit(): Promise<void> {
|
||||
async commit(signal?: AbortSignal): Promise<void> {
|
||||
this.#assertWritable();
|
||||
abortIfNeeded(signal);
|
||||
await this.#assertOwnedDirectories();
|
||||
abortIfNeeded(signal);
|
||||
// Windows has no directory fsync; file contents are already synced in write().
|
||||
if (this.platform === "win32") {
|
||||
this.#published = true;
|
||||
@@ -315,6 +317,7 @@ export class SafeOutputTree {
|
||||
);
|
||||
await output.handle.sync();
|
||||
await parent.handle.sync();
|
||||
abortIfNeeded(signal);
|
||||
this.#published = true;
|
||||
} catch (cause: unknown) {
|
||||
sync = { kind: "failed", cause };
|
||||
@@ -336,23 +339,26 @@ export class SafeOutputTree {
|
||||
closeFailure,
|
||||
this.#outputRoot,
|
||||
);
|
||||
if (sync.kind === "failed")
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
),
|
||||
cleanup,
|
||||
);
|
||||
if (sync.kind === "failed") {
|
||||
const primary = isCancellationFailure(sync.cause)
|
||||
? sync.cause
|
||||
: new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
);
|
||||
throw ArtifactReaderFailure.withCleanup(primary, cleanup);
|
||||
}
|
||||
throw ArtifactReaderFailure.withCleanup(closeFailure, cleanup);
|
||||
}
|
||||
if (sync.kind === "failed")
|
||||
if (sync.kind === "failed") {
|
||||
if (isCancellationFailure(sync.cause)) throw sync.cause;
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
@@ -579,6 +585,11 @@ const normalizeDestinationPath = (
|
||||
"path",
|
||||
`Windows destination cannot materialize artifact path as a regular file: ${path}; ':' denotes alternate data stream syntax.`,
|
||||
);
|
||||
if (platform === "win32" && /[\u0001-\u001f]/u.test(path))
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Windows destination cannot materialize artifact path: ${JSON.stringify(path)}; Windows names cannot contain U+0001-U+001F.`,
|
||||
);
|
||||
return path;
|
||||
};
|
||||
|
||||
@@ -590,6 +601,11 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
);
|
||||
};
|
||||
|
||||
const isCancellationFailure = (
|
||||
cause: unknown,
|
||||
): cause is ArtifactReaderFailure =>
|
||||
cause instanceof ArtifactReaderFailure && cause.reason === "cancelled";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
|
||||
|
||||
|
||||
@@ -255,10 +255,29 @@ const decodeZipEntryText = (
|
||||
encoding: string,
|
||||
type: "filename" | "comment",
|
||||
): string | undefined => {
|
||||
if (type !== "filename" || encoding !== "utf-8") return undefined;
|
||||
return decodeStrictZipUtf8(bytes, "ZIP filename is not valid UTF-8");
|
||||
if (type !== "filename") return undefined;
|
||||
if (encoding === "utf-8")
|
||||
return decodeStrictZipUtf8(bytes, "ZIP filename is not valid UTF-8");
|
||||
return encoding === "cp437" ? decodeCp437(bytes) : undefined;
|
||||
};
|
||||
|
||||
/** CP437 characters for bytes 0x80-0xFF. */
|
||||
const CP437_HIGH_HALF =
|
||||
"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00A0";
|
||||
|
||||
/**
|
||||
* Decode a legacy ZIP name with the Unicode CP437 mapping, which Python's
|
||||
* zipfile also uses: bytes below 0x80 are ASCII. zip.js shows 0x01-0x1F and
|
||||
* 0x7F as IBM PC display glyphs, which turns the macOS folder icon file
|
||||
* `Icon\r` into `Icon♪`.
|
||||
*/
|
||||
const decodeCp437 = (bytes: Uint8Array): string =>
|
||||
Array.from(bytes, (byte) =>
|
||||
byte < 0x80
|
||||
? String.fromCharCode(byte)
|
||||
: CP437_HIGH_HALF.charAt(byte - 0x80),
|
||||
).join("");
|
||||
|
||||
const zipEntryPath = (entry: Entry): string => {
|
||||
const field = entry.extraFieldUnicodePath;
|
||||
if (field?.valid !== true) return entry.filename;
|
||||
|
||||
@@ -134,7 +134,14 @@ export const decodeNibArchive = (
|
||||
const value = values.get(index);
|
||||
if (value === undefined) continue;
|
||||
const key = keys[value.key_index];
|
||||
if (key !== undefined) fields[key] = value.value;
|
||||
if (key !== undefined)
|
||||
// Archive keys are data, including the legacy __proto__ setter name.
|
||||
Object.defineProperty(fields, key, {
|
||||
value: value.value,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
}
|
||||
return [{ id, class_name: className, values: fields }];
|
||||
});
|
||||
@@ -519,7 +526,8 @@ const decodeUtf8 = (
|
||||
label: string,
|
||||
): string => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
// These are length-prefixed names, not standalone text documents.
|
||||
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
bytes.subarray(start, end),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
@@ -248,7 +249,7 @@ const materializeSelection = async ({
|
||||
compareUnicodeCodePoints(left.relative_path, right.relative_path),
|
||||
);
|
||||
completed = createExtractionResult(input, inventory, selected, extracted);
|
||||
await output.commit();
|
||||
await output.commit(signal);
|
||||
return completed;
|
||||
} catch (cause: unknown) {
|
||||
const cleanupFailures = await releaseExtractionOwners(
|
||||
@@ -400,13 +401,6 @@ interface ExtractionInventory {
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
}
|
||||
|
||||
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
|
||||
|
||||
const isZipFormat = (
|
||||
format: BinaryTarget["format"],
|
||||
): format is (typeof ZIP_FORMATS)[number] =>
|
||||
(ZIP_FORMATS as readonly string[]).includes(format);
|
||||
|
||||
/**
|
||||
* Refuse a format without an extraction reader before inventory work starts.
|
||||
* The target kind, not the host, is unsupported by extraction. The error keeps
|
||||
@@ -422,7 +416,7 @@ const requireExtractableFormat = async (
|
||||
!directory &&
|
||||
format !== "asar" &&
|
||||
!isMachOFormat(format) &&
|
||||
!isZipFormat(format)
|
||||
!isZipPackageFormat(format)
|
||||
)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
"extract_artifact",
|
||||
@@ -443,7 +437,7 @@ const createReader = async (
|
||||
if (await requireExtractableFormat(path, input))
|
||||
return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
|
||||
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
|
||||
return new MachOSliceArtifactReader(path, input.environment);
|
||||
};
|
||||
|
||||
|
||||
@@ -38,6 +38,13 @@ const afterValidation = async <T>(
|
||||
}
|
||||
};
|
||||
|
||||
const assertReadActive = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted)
|
||||
throw new ArtifactReaderFailure("cancelled", "Artifact read cancelled", {
|
||||
cause: signal.reason,
|
||||
});
|
||||
};
|
||||
|
||||
/** Read one bounded regular file and reject replacement or in-place changes. */
|
||||
export const readStableArtifact = async (
|
||||
path: string,
|
||||
@@ -46,7 +53,7 @@ export const readStableArtifact = async (
|
||||
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
|
||||
resourceScope?: ArtifactResourceScope,
|
||||
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
|
||||
signal?.throwIfAborted();
|
||||
assertReadActive(signal);
|
||||
const before = await fileSystem.lstat(path);
|
||||
if (!before.isFile() || before.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -84,7 +91,7 @@ export const readStableArtifact = async (
|
||||
autoClose: false,
|
||||
highWaterMark: 65536,
|
||||
})) {
|
||||
signal?.throwIfAborted();
|
||||
assertReadActive(signal);
|
||||
const value: unknown = chunk;
|
||||
if (!Buffer.isBuffer(value))
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -120,6 +127,7 @@ export const readStableArtifact = async (
|
||||
"integrity",
|
||||
`Artifact changed during read: ${path}`,
|
||||
);
|
||||
assertReadActive(signal);
|
||||
const bytes = Buffer.concat(chunks, count);
|
||||
return { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
} catch (cause: unknown) {
|
||||
|
||||
@@ -91,7 +91,7 @@ export const browserScenarioCaptureData = (input: {
|
||||
network_content: input.scenario.capture.network,
|
||||
event_families: [...new Set(input.scenario.capture.events)].sort(),
|
||||
},
|
||||
duration_ms: Date.now() - input.startedAt,
|
||||
duration_ms: Math.max(0, Math.round(performance.now() - input.startedAt)),
|
||||
steps: [...input.steps],
|
||||
events,
|
||||
limitations: [
|
||||
|
||||
@@ -303,6 +303,7 @@ describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
});
|
||||
expect(result.value.limitations).toContain(session.eventGaps[0]);
|
||||
});
|
||||
|
||||
it("returns an initial state and every step beyond the former action ceiling", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider(() =>
|
||||
@@ -376,6 +377,35 @@ describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider timing", () => {
|
||||
it("keeps capture elapsed values valid across a backward wall-clock jump", async () => {
|
||||
let wallClock = 10_000;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => wallClock);
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => {
|
||||
wallClock = 1;
|
||||
};
|
||||
const provider = new PlaywrightBrowserScenarioProvider(() =>
|
||||
Promise.resolve(session),
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await provider.captureScenario(scenario());
|
||||
if (!result.ok) throw result.error;
|
||||
expect(wallClock).toBe(1);
|
||||
expect(Number.isInteger(result.value.duration_ms)).toBe(true);
|
||||
expect(result.value.duration_ms).toBeGreaterThanOrEqual(0);
|
||||
expect(
|
||||
result.value.steps.every(
|
||||
({ elapsed_ms }) => Number.isInteger(elapsed_ms) && elapsed_ms >= 0,
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider comparison coverage", () => {
|
||||
it("keeps quiet captures with different event families from comparing unchanged", async () => {
|
||||
const capture = async (events: readonly BrowserScenarioEventFamily[]) => {
|
||||
|
||||
@@ -172,7 +172,7 @@ const executeStep = async (input: {
|
||||
),
|
||||
});
|
||||
|
||||
const actionStartedAt = Date.now();
|
||||
const actionStartedAt = performance.now();
|
||||
session.setStep(stepIndex);
|
||||
const requestCancelled = (): boolean => signal?.aborted === true;
|
||||
let outcome: BrowserScenarioStepOutcome = {
|
||||
@@ -200,7 +200,7 @@ const executeStep = async (input: {
|
||||
stepId: action.step_id,
|
||||
action: action.action,
|
||||
...outcome,
|
||||
elapsedMs: Date.now() - actionStartedAt,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),
|
||||
beforeUrl,
|
||||
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
||||
eventStart,
|
||||
@@ -233,7 +233,7 @@ const runScenario = async (
|
||||
): Promise<BrowserScenarioCapture> => {
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
const startedAt = Date.now();
|
||||
const startedAt = performance.now();
|
||||
const session = await openSession(scenario, {
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
retainCleanup,
|
||||
@@ -250,7 +250,7 @@ const runScenario = async (
|
||||
await initialStep({
|
||||
session,
|
||||
scenario,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
|
||||
signal: options.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,7 +72,7 @@ export const runElectronActions = async (
|
||||
): Promise<ElectronActions> => {
|
||||
const actions: ElectronActions = [];
|
||||
for (const action of input.actions) {
|
||||
const actionStartedAt = Date.now();
|
||||
const actionStartedAt = performance.now();
|
||||
const windowIndex = actionWindowIndex(action);
|
||||
let selectedWindow: Page | undefined;
|
||||
try {
|
||||
@@ -107,7 +107,10 @@ export const runElectronActions = async (
|
||||
target:
|
||||
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
|
||||
status: "completed",
|
||||
elapsed_ms: Date.now() - actionStartedAt,
|
||||
elapsed_ms: Math.max(
|
||||
0,
|
||||
Math.round(performance.now() - actionStartedAt),
|
||||
),
|
||||
error: null,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
@@ -118,7 +121,10 @@ export const runElectronActions = async (
|
||||
target:
|
||||
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
|
||||
status: options.signal?.aborted ? "cancelled" : "failed",
|
||||
elapsed_ms: Date.now() - actionStartedAt,
|
||||
elapsed_ms: Math.max(
|
||||
0,
|
||||
Math.round(performance.now() - actionStartedAt),
|
||||
),
|
||||
error: safeActionErrorMessage(cause),
|
||||
});
|
||||
break;
|
||||
@@ -366,7 +372,7 @@ export const runWithExecutionLimits = async <Value>(
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new BrowserObservationError(OPERATION, "timeout")),
|
||||
Math.max(1, deadline - Date.now()),
|
||||
Math.max(1, deadline - performance.now()),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -86,7 +86,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
await prepareProcessOwnershipInspection(options.signal);
|
||||
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
const startupDeadline = performance.now() + STARTUP_TIMEOUT_MS;
|
||||
paths = {
|
||||
executable: input.executable_path,
|
||||
application: input.application_path,
|
||||
@@ -101,7 +101,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
cwd: paths.root,
|
||||
env: safeElectronEnvironment(this.environment, runId),
|
||||
args: ["-r", hookPath, paths.application, ...input.args],
|
||||
timeout: Math.max(1, startupDeadline - Date.now()),
|
||||
timeout: Math.max(1, startupDeadline - performance.now()),
|
||||
});
|
||||
const leaderPid = application.process().pid;
|
||||
if (
|
||||
@@ -128,7 +128,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
const state = await runWithExecutionLimits(
|
||||
readApplicationState(application),
|
||||
undefined,
|
||||
options.signal?.aborted ? Date.now() + 5_000 : undefined,
|
||||
options.signal?.aborted ? performance.now() + 5_000 : undefined,
|
||||
);
|
||||
capture = projectElectronActiveCapture(paths, actions, state);
|
||||
outcome = options.signal?.aborted
|
||||
@@ -187,7 +187,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
await runWithExecutionLimits(
|
||||
application.close(),
|
||||
undefined,
|
||||
Date.now() + 5_000,
|
||||
performance.now() + 5_000,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
closeError = cause;
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
@@ -31,4 +34,20 @@ describe("withPlaywrightExecutionBoundary", () => {
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
|
||||
it("keeps its timeout stable across a wall-clock jump", async () => {
|
||||
vi.spyOn(Date, "now")
|
||||
.mockReturnValueOnce(1_000)
|
||||
.mockReturnValue(10_000_000);
|
||||
|
||||
await expect(
|
||||
withPlaywrightExecutionBoundary(
|
||||
() =>
|
||||
new Promise<string>((resolve) =>
|
||||
setTimeout(() => resolve("done"), 5),
|
||||
),
|
||||
1_000,
|
||||
),
|
||||
).resolves.toBe("done");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,10 +19,10 @@ export const withPlaywrightExecutionBoundary = <Value>(
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const deadline =
|
||||
timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
|
||||
timeoutMs === undefined ? undefined : performance.now() + timeoutMs;
|
||||
const scheduleTimeout = (): void => {
|
||||
if (deadline === undefined) return;
|
||||
const remaining = deadline - Date.now();
|
||||
const remaining = deadline - performance.now();
|
||||
if (remaining <= 0) {
|
||||
fail(new AnalysisTimeoutError(OPERATION, timeoutMs ?? 0));
|
||||
return;
|
||||
|
||||
@@ -133,7 +133,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
|
||||
if (secrets === undefined)
|
||||
throw new BrowserObservationError(OPERATION, "secret_unavailable");
|
||||
const startedAt = Date.now();
|
||||
const startedAt = performance.now();
|
||||
const opening = openPlaywrightScenarioBrowser(scenario, environment, {
|
||||
signal: options.signal,
|
||||
...(options.retainCleanup === undefined
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as t from "@babel/types";
|
||||
import {
|
||||
decodeValidatedSourceMapLeaves,
|
||||
isBeforeSourceMapLeafStop,
|
||||
resolveSourceMapSource,
|
||||
} from "../javascript/sourceMaps/DecodedSourceMap.js";
|
||||
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
@@ -21,6 +20,7 @@ import { webSourceMapsSchema } from "../domain/webBundleAnalysis.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
import { sourceMapJsonText } from "../domain/sourceMapEnvelope.js";
|
||||
import { resolveJavaScriptSourceMapUrl } from "../domain/javascript/javascriptSourceMapPaths.js";
|
||||
import { jsonParts } from "../domain/jsonSerialization.js";
|
||||
import {
|
||||
inspectSourceMapValue,
|
||||
@@ -86,7 +86,7 @@ export const fetchWebSourceMaps = async (
|
||||
signal?.addEventListener("abort", abortFromCaller, { once: true });
|
||||
const operationSignal = operationController.signal;
|
||||
const deadlineAt =
|
||||
Date.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
|
||||
performance.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
|
||||
const budget = {
|
||||
retainedBytes: 0,
|
||||
deadlineAt,
|
||||
@@ -110,7 +110,7 @@ export const fetchWebSourceMaps = async (
|
||||
}
|
||||
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
|
||||
budget.decodedRecords.expandedBytes += reservation;
|
||||
if (operationSignal.aborted || Date.now() >= deadlineAt) {
|
||||
if (operationSignal.aborted || performance.now() >= deadlineAt) {
|
||||
items.push(
|
||||
emptySourceMapItem(
|
||||
request,
|
||||
@@ -789,7 +789,7 @@ const checkOperation = (
|
||||
): void => {
|
||||
if (callerSignal?.aborted === true) throw callerSignal.reason;
|
||||
if (operationSignal?.aborted === true) throw operationSignal.reason;
|
||||
if (Date.now() >= deadlineAt) throw new SourceMapDeadlineError();
|
||||
if (performance.now() >= deadlineAt) throw new SourceMapDeadlineError();
|
||||
};
|
||||
|
||||
const approvedUrl = (
|
||||
@@ -867,7 +867,11 @@ const preflightResolvedSourceBytes = (
|
||||
const sourceKey = source;
|
||||
let resolved = sourcesForRoot.get(sourceKey);
|
||||
if (resolved === undefined)
|
||||
resolved = resolveSourceMapSource(source, map.sourceRoot, mapUrl);
|
||||
resolved = resolveJavaScriptSourceMapUrl(
|
||||
source,
|
||||
map.sourceRoot,
|
||||
mapUrl,
|
||||
);
|
||||
const bytes = Buffer.byteLength(resolved, "utf8");
|
||||
if (bytes > SOURCE_MAP_RESPONSE_BYTES - resolvedBytes)
|
||||
throw resolvedSourceLimitFailure();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { normalizeArtifactPath } from "../../artifacts/ArtifactPaths.js";
|
||||
import type { WebScriptArtifactPort } from "../../application/WebScriptArtifactPort.js";
|
||||
@@ -19,10 +20,36 @@ import {
|
||||
|
||||
/** Read one digest-verified captured source under the manifest's current location. */
|
||||
export class LocalWebScriptArtifacts implements WebScriptArtifactPort {
|
||||
constructor(readonly operation: WebArtifactReadContext["operation"]) {}
|
||||
constructor(
|
||||
readonly operation: WebArtifactReadContext["operation"],
|
||||
readonly resources = new ArtifactResourceScope(),
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.resources.close();
|
||||
}
|
||||
|
||||
/** Read the selected source; relocated exports retain their reported original root. */
|
||||
async load(input: SelectedWebScriptInput, options?: ExecutionOptions) {
|
||||
try {
|
||||
return await this.resources.run(() => this.#load(input, options));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
webArtifactReadError(
|
||||
cause,
|
||||
{
|
||||
operation: this.operation,
|
||||
field: ["manifest_path"],
|
||||
targetPath: input.manifest_path,
|
||||
callerSelected: true,
|
||||
},
|
||||
options?.signal,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #load(input: SelectedWebScriptInput, options?: ExecutionOptions) {
|
||||
let field: readonly (string | number)[] = ["manifest_path"];
|
||||
let targetPath = input.manifest_path;
|
||||
let callerSelected = true;
|
||||
@@ -31,6 +58,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort {
|
||||
input.manifest_path,
|
||||
32 * 1024 * 1024,
|
||||
options?.signal,
|
||||
this.resources,
|
||||
);
|
||||
const manifest = webScriptExportManifestSchema.parse(manifestBytes.value);
|
||||
field = ["script_index"];
|
||||
@@ -65,6 +93,8 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort {
|
||||
sourcePath,
|
||||
16 * 1024 * 1024,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.resources,
|
||||
);
|
||||
await assertContained(root, sourcePath);
|
||||
if (
|
||||
|
||||
@@ -113,7 +113,7 @@ export const publishWebScripts = async (
|
||||
options.signal,
|
||||
);
|
||||
options.signal?.throwIfAborted();
|
||||
await tree.commit();
|
||||
await tree.commit(options.signal);
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
@@ -9,6 +10,8 @@ import {
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js";
|
||||
import { safeParseJson } from "../../domain/safeJson.js";
|
||||
|
||||
/** The selected artifact and input field owning a reader failure. */
|
||||
@@ -42,8 +45,15 @@ export const readWebArtifactJson = async (
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
signal?: AbortSignal,
|
||||
resourceScope?: ArtifactResourceScope,
|
||||
) => {
|
||||
const data = await readStableArtifact(path, maximumBytes, signal);
|
||||
const data = await readStableArtifact(
|
||||
path,
|
||||
maximumBytes,
|
||||
signal,
|
||||
undefined,
|
||||
resourceScope,
|
||||
);
|
||||
const value = safeParseJson(decodeWebArtifact(data.bytes));
|
||||
if (!value.ok) throw new WebArtifactFormatFailure(value.error);
|
||||
return { ...data, value: value.value };
|
||||
@@ -55,8 +65,30 @@ export const webArtifactReadError = (
|
||||
context: WebArtifactReadContext,
|
||||
signal?: AbortSignal,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) {
|
||||
const primary =
|
||||
signal?.aborted === true
|
||||
? new AnalysisCancelledError(context.operation, { cause })
|
||||
: new ArtifactOperationError(
|
||||
context.operation,
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
{ cause },
|
||||
);
|
||||
return analysisErrorWithCleanupFailure(
|
||||
primary,
|
||||
new ProviderCleanupError(
|
||||
"captured-web-artifacts",
|
||||
cause.cleanup.resources,
|
||||
{ reason: cause.cleanup.reason },
|
||||
{ cause, operation: context.operation },
|
||||
),
|
||||
context.operation,
|
||||
);
|
||||
}
|
||||
if (signal?.aborted === true)
|
||||
return new AnalysisCancelledError(context.operation);
|
||||
return new AnalysisCancelledError(context.operation, { cause });
|
||||
const selection = context.callerSelected
|
||||
? selectedFileError(cause, context)
|
||||
: undefined;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { WebSourceLocationArtifactPort } from "../../application/WebSourceLocationPorts.js";
|
||||
import type { WebScriptArtifactPort } from "../../application/WebScriptArtifactPort.js";
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import {
|
||||
WEB_SOURCE_MAP_LIMITS,
|
||||
@@ -12,14 +13,64 @@ import { decodeWebArtifact, webArtifactReadError } from "./WebArtifactReads.js";
|
||||
|
||||
/** Read one verified capture source and the caller-selected map, without fetching. */
|
||||
export class LocalWebSourceLocationArtifacts implements WebSourceLocationArtifactPort {
|
||||
readonly scripts: WebScriptArtifactPort;
|
||||
readonly #resources: ArtifactResourceScope;
|
||||
|
||||
constructor(
|
||||
readonly scripts: WebScriptArtifactPort = new LocalWebScriptArtifacts(
|
||||
"trace_web_source_location",
|
||||
),
|
||||
) {}
|
||||
scripts?: WebScriptArtifactPort,
|
||||
resources = scripts instanceof LocalWebScriptArtifacts
|
||||
? scripts.resources
|
||||
: new ArtifactResourceScope(),
|
||||
) {
|
||||
this.#resources = resources;
|
||||
this.scripts =
|
||||
scripts ??
|
||||
new LocalWebScriptArtifacts("trace_web_source_location", resources);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closeScript =
|
||||
this.scripts instanceof LocalWebScriptArtifacts &&
|
||||
this.scripts.resources === this.#resources
|
||||
? undefined
|
||||
: this.scripts.close?.bind(this.scripts);
|
||||
const results = await Promise.allSettled([
|
||||
Promise.resolve().then(() => this.#resources.close()),
|
||||
...(closeScript === undefined
|
||||
? []
|
||||
: [Promise.resolve().then(closeScript)]),
|
||||
]);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
if (failures.length > 0)
|
||||
throw new AggregateError(
|
||||
failures,
|
||||
"Web source-location artifact cleanup failed",
|
||||
);
|
||||
}
|
||||
|
||||
/** Preserve actual map identity separately from the selected deployment URL. */
|
||||
async load(input: WebSourceLocationInput, options?: ExecutionOptions) {
|
||||
try {
|
||||
return await this.#resources.run(() => this.#load(input, options));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
webArtifactReadError(
|
||||
cause,
|
||||
{
|
||||
operation: "trace_web_source_location",
|
||||
field: ["source_map", "path"],
|
||||
targetPath: input.source_map.path,
|
||||
callerSelected: true,
|
||||
},
|
||||
options?.signal,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #load(input: WebSourceLocationInput, options?: ExecutionOptions) {
|
||||
const loaded = await this.scripts.load(input, options);
|
||||
if (!loaded.ok) return loaded;
|
||||
try {
|
||||
@@ -27,6 +78,8 @@ export class LocalWebSourceLocationArtifacts implements WebSourceLocationArtifac
|
||||
input.source_map.path,
|
||||
WEB_SOURCE_MAP_LIMITS.mapBytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
return ok({
|
||||
...loaded.value,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
|
||||
import { inspectWebNetworkCaptureInputSchema } from "../../domain/webNetworkCapture.js";
|
||||
import { historicalCaptureFailure } from "./CaptureFailures.js";
|
||||
import { HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "./CaptureRelease.js";
|
||||
import { NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "./CaptureRelease.js";
|
||||
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
|
||||
@@ -118,7 +118,7 @@ it.each([
|
||||
},
|
||||
});
|
||||
// The enforced limit is reported only where Bun runs on Windows.
|
||||
if (HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null)
|
||||
if (NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null)
|
||||
expect(JSON.stringify(projected)).not.toContain(
|
||||
"process_memory_limit_bytes",
|
||||
);
|
||||
@@ -126,12 +126,12 @@ it.each([
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
reported_limits: {
|
||||
process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
process_memory_limit_bytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
},
|
||||
},
|
||||
remediation: {
|
||||
action: expect.stringContaining(
|
||||
`${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes`,
|
||||
`${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes`,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -18,9 +18,9 @@ import {
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
import {
|
||||
HAR_CAPTURE_HEAP_ENFORCED,
|
||||
HAR_CAPTURE_HEAP_LIMITS,
|
||||
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
NODE_CAPTURE_HEAP_ENFORCED,
|
||||
NODE_CAPTURE_HEAP_LIMITS,
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
} from "./CaptureRelease.js";
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
@@ -78,7 +78,7 @@ export const historicalCaptureFailure = (
|
||||
);
|
||||
if (
|
||||
phase === "decoder" &&
|
||||
input.format === "har" &&
|
||||
input.format !== "mitmproxy" &&
|
||||
cause.reason === "process" &&
|
||||
(cause.snapshot?.signal === "SIGABRT" ||
|
||||
(cause.snapshot?.signal === null && cause.snapshot.exitCode === 134)) &&
|
||||
@@ -86,7 +86,7 @@ export const historicalCaptureFailure = (
|
||||
)
|
||||
return captureMemoryFailure(
|
||||
input,
|
||||
"The HAR decoder exhausted its fixed V8 heap",
|
||||
`The ${input.format} decoder exhausted its fixed V8 heap`,
|
||||
cause,
|
||||
);
|
||||
}
|
||||
@@ -195,15 +195,17 @@ export const captureMemoryFailure = (
|
||||
format: input.format,
|
||||
maximum_input_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
maximum_reply_bytes: WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
|
||||
...(input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED
|
||||
...(input.format !== "mitmproxy" && NODE_CAPTURE_HEAP_ENFORCED
|
||||
? {
|
||||
old_generation_heap_mib: HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB,
|
||||
semi_space_heap_mib: HAR_CAPTURE_HEAP_LIMITS.semiSpaceMiB,
|
||||
old_generation_heap_mib: NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB,
|
||||
semi_space_heap_mib: NODE_CAPTURE_HEAP_LIMITS.semiSpaceMiB,
|
||||
}
|
||||
: {}),
|
||||
...(input.format === "har" &&
|
||||
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null
|
||||
? { process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }
|
||||
...(input.format !== "mitmproxy" &&
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null
|
||||
? {
|
||||
process_memory_limit_bytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
}
|
||||
: {}),
|
||||
...(cause instanceof OwnedCommandFailure
|
||||
? {
|
||||
@@ -214,7 +216,7 @@ export const captureMemoryFailure = (
|
||||
},
|
||||
{
|
||||
cause,
|
||||
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED ? ` REA's HAR old-generation heap is fixed at ${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}${input.format === "har" && HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null ? ` REA's HAR decoder process commit limit is fixed at ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes.` : ""}`,
|
||||
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format !== "mitmproxy" && NODE_CAPTURE_HEAP_ENFORCED ? ` REA's Node capture old-generation heap is fixed at ${NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}${input.format !== "mitmproxy" && NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null ? ` REA's Node capture decoder process commit limit is fixed at ${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes.` : ""}`,
|
||||
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
|
||||
? {
|
||||
capturedOutput: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Expected malformed, unsupported or oversized producer data at a historical decoder boundary. */
|
||||
export class CaptureFormatError extends Error {
|
||||
constructor(
|
||||
readonly reason: "format" | "unsupported" | "input-limit",
|
||||
readonly reason: "format" | "unsupported" | "input-limit" | "limit",
|
||||
message: string,
|
||||
readonly pointer = "",
|
||||
) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { visit } from "jsonc-parser";
|
||||
import { LosslessNumber } from "lossless-json";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import { TextDecoder } from "node:util";
|
||||
|
||||
type Frame =
|
||||
| {
|
||||
@@ -13,7 +14,10 @@ type Frame =
|
||||
| { kind: "array"; pointer: string; items: unknown[] };
|
||||
|
||||
/** Materialize upstream JSON events without duplicate folding, prototype setters or numeric rounding. */
|
||||
export const parseHarJson = (text: string): unknown => {
|
||||
export const parseCaptureJson = (
|
||||
text: string,
|
||||
format: "HAR" | "qlog",
|
||||
): unknown => {
|
||||
const frames: Frame[] = [];
|
||||
let result: unknown;
|
||||
const valuePointer = (): string => {
|
||||
@@ -29,7 +33,7 @@ export const parseHarJson = (text: string): unknown => {
|
||||
if (frames.length > WEB_NETWORK_CAPTURE_LIMITS.depth)
|
||||
throw new CaptureFormatError(
|
||||
"input-limit",
|
||||
"HAR exceeds the 64-level complete-evidence nesting budget.",
|
||||
`${format} exceeds the 64-level complete-evidence nesting budget.`,
|
||||
valuePointer(),
|
||||
);
|
||||
};
|
||||
@@ -69,7 +73,7 @@ export const parseHarJson = (text: string): unknown => {
|
||||
if (frame.members.has(key))
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR JSON contains duplicate object members.",
|
||||
`${format} JSON contains duplicate object members.`,
|
||||
);
|
||||
frame.pendingKey = key;
|
||||
},
|
||||
@@ -103,7 +107,7 @@ export const parseHarJson = (text: string): unknown => {
|
||||
throw new TypeError("JSON visitor emitted an unsupported literal.");
|
||||
},
|
||||
onError: () => {
|
||||
throw new CaptureFormatError("format", "HAR is malformed JSON.");
|
||||
throw new CaptureFormatError("format", `${format} is malformed JSON.`);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -114,3 +118,18 @@ export const parseHarJson = (text: string): unknown => {
|
||||
);
|
||||
return result;
|
||||
};
|
||||
|
||||
/** UTF-8 JSON decoding skips one permitted BOM and rejects malformed bytes. */
|
||||
export const decodeCaptureText = (
|
||||
bytes: Uint8Array,
|
||||
format: "HAR" | "qlog",
|
||||
): string => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
`${format} is not valid UTF-8 JSON.`,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -8,19 +8,19 @@ export const HAR_CAPTURE_PROVIDER_IDENTITY = {
|
||||
version: "har-schema@2.0.0;jsonc-parser@3.3.1;lossless-json@4.3.1",
|
||||
} as const;
|
||||
|
||||
/** Fixed V8 heap settings used by the owned HAR decoder process. */
|
||||
export const HAR_CAPTURE_HEAP_LIMITS = {
|
||||
/** Fixed V8 heap settings used by the owned Node capture decoder process. */
|
||||
export const NODE_CAPTURE_HEAP_LIMITS = {
|
||||
oldGenerationMiB: 192,
|
||||
semiSpaceMiB: 8,
|
||||
} as const;
|
||||
|
||||
/** The HAR decoder runs on this executable; Bun accepts but ignores V8 heap flags. */
|
||||
export const HAR_CAPTURE_HEAP_ENFORCED =
|
||||
/** The Node capture decoder runs on this executable; Bun accepts but ignores V8 heap flags. */
|
||||
export const NODE_CAPTURE_HEAP_ENFORCED =
|
||||
javaScriptRuntime(process.versions).id === "node";
|
||||
|
||||
/** Windows Job Object commit limit replacing the ignored heap flags under Bun; otherwise null. */
|
||||
export const HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES =
|
||||
javaScriptWorkerMemoryLimitBytes(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB);
|
||||
export const NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES =
|
||||
javaScriptWorkerMemoryLimitBytes(NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB);
|
||||
|
||||
/** Native executable profile verified with unchanged mitmproxy raw-state decoding. */
|
||||
export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
|
||||
@@ -28,3 +28,18 @@ export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
|
||||
name: "REA offline native mitmproxy adapter",
|
||||
version: "12.2.3",
|
||||
} as const;
|
||||
|
||||
/** Native SAZ member decoding with the existing ZIP and XML package profiles. */
|
||||
export const SAZ_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "fiddler-saz",
|
||||
name: "REA Fiddler SAZ capture adapter",
|
||||
version: "1;zip.js@2.15.0;xmldom@0.9.12",
|
||||
} as const;
|
||||
|
||||
/** Fixed offline interpretation profile, not an authenticated producer claim. */
|
||||
export const QLOG_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "aioquic-qlog-json",
|
||||
name: "REA aioquic qlog capture adapter",
|
||||
version:
|
||||
"aioquic-profile@1.5.0;qlog@0.3;jsonc-parser@3.3.1;lossless-json@4.3.1",
|
||||
} as const;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { historicalHar } from "../../../tests/fixtures/historicalHar.js";
|
||||
import { decodeHarCapture, decodeHarText } from "./HarCapture.js";
|
||||
import { decodeCaptureText } from "./CaptureJson.js";
|
||||
import { decodeHarCapture } from "./HarCapture.js";
|
||||
|
||||
it.each([
|
||||
{ values: [] },
|
||||
@@ -161,6 +162,19 @@ it("rejects identical duplicate core fields before schema validation", () => {
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
});
|
||||
|
||||
it("names the violated HAR schema constraint without restating capture values", () => {
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: { creator: { name: "x", version: "1" }, entries: [] },
|
||||
}),
|
||||
[],
|
||||
),
|
||||
).toThrow(
|
||||
"HAR schema validation failed: required (must have required property 'version').",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves prototype-named producer members through the capture boundary", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
@@ -563,18 +577,21 @@ it("ignores one leading byte-order mark, as HAR 1.2 requires of readers", () =>
|
||||
const text = JSON.stringify(historicalHar());
|
||||
const body = Buffer.from(text, "utf8");
|
||||
const marked = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]);
|
||||
expect(decodeHarText(marked)).toBe(text);
|
||||
expect(decodeHarCapture(decodeHarText(marked), [])).toEqual(
|
||||
decodeHarCapture(decodeHarText(body), []),
|
||||
expect(decodeCaptureText(marked, "HAR")).toBe(text);
|
||||
expect(decodeHarCapture(decodeCaptureText(marked, "HAR"), [])).toEqual(
|
||||
decodeHarCapture(decodeCaptureText(body, "HAR"), []),
|
||||
);
|
||||
// A second mark is content, not an encoding signature.
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
decodeHarText(Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), marked])),
|
||||
decodeCaptureText(
|
||||
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), marked]),
|
||||
"HAR",
|
||||
),
|
||||
[],
|
||||
),
|
||||
).toThrow("HAR is malformed JSON.");
|
||||
expect(() => decodeHarText(Buffer.from([0x7b, 0xff, 0x7d]))).toThrow(
|
||||
"HAR is not valid UTF-8 JSON.",
|
||||
);
|
||||
expect(() =>
|
||||
decodeCaptureText(Buffer.from([0x7b, 0xff, 0x7d]), "HAR"),
|
||||
).toThrow("HAR is not valid UTF-8 JSON.");
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { isSafeNumber, LosslessNumber } from "lossless-json";
|
||||
import { parseHarJson } from "./HarJson.js";
|
||||
import { parseCaptureJson } from "./CaptureJson.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
@@ -26,25 +25,12 @@ type Projection = Pick<
|
||||
"reported" | "numeric_literals" | "binary_fields" | "redactions"
|
||||
>;
|
||||
|
||||
/**
|
||||
* Decode retained HAR bytes as UTF-8. HAR 1.2 lets writers emit a byte-order
|
||||
* mark and requires readers to ignore it, so one leading BOM is skipped.
|
||||
*/
|
||||
export const decodeHarText = (bytes: Uint8Array): string => {
|
||||
try {
|
||||
// ignoreBOM: false (the default) is what skips the mark; true keeps it.
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
|
||||
}
|
||||
};
|
||||
|
||||
/** Decode a retained HAR with exact numeric lexemes and unchanged upstream schema validation. */
|
||||
export const decodeHarCapture = (
|
||||
text: string,
|
||||
sensitiveValues: readonly string[],
|
||||
): DecodedCapture => {
|
||||
const raw = parseHarJson(text);
|
||||
const raw = parseCaptureJson(text, "HAR");
|
||||
const validation = projectHar(raw, [], false);
|
||||
createHarValidator()(validation.reported);
|
||||
if (
|
||||
@@ -158,7 +144,8 @@ const projectHar = (
|
||||
(literal) =>
|
||||
item.includes(literal) ||
|
||||
contentBase64.includes(literal) ||
|
||||
sha256.includes(literal),
|
||||
sha256.includes(literal) ||
|
||||
String(bytes.length).includes(literal),
|
||||
);
|
||||
binary_fields.push(
|
||||
hidden
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import {
|
||||
HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
HAR_CAPTURE_HEAP_LIMITS,
|
||||
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
} from "./CaptureRelease.js";
|
||||
|
||||
/** HAR's parser/schema packages run in one bounded Node heap, without network or target execution. */
|
||||
export class HarCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly format = "har";
|
||||
readonly identity = HAR_CAPTURE_PROVIDER_IDENTITY;
|
||||
async command(requestPath: string): Promise<{
|
||||
command: string;
|
||||
arguments: readonly string[];
|
||||
memoryLimitBytes?: number;
|
||||
}> {
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
`--max-old-space-size=${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB}`,
|
||||
`--max-semi-space-size=${HAR_CAPTURE_HEAP_LIMITS.semiSpaceMiB}`,
|
||||
"--v8-pool-size=1",
|
||||
"--single-threaded",
|
||||
fileURLToPath(new URL("./HarCaptureProcess.js", import.meta.url)),
|
||||
requestPath,
|
||||
],
|
||||
...(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
|
||||
? {}
|
||||
: { memoryLimitBytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,13 @@ export const createHarValidator = (): ((value: unknown) => void) => {
|
||||
allowMitmproxyAbsentPostData(value);
|
||||
if (!validate(value)) {
|
||||
const error = validate.errors?.[0];
|
||||
// AJV messages name the violated constraint, such as the missing
|
||||
// property, without restating any captured value.
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
`HAR schema validation failed: ${error?.keyword ?? "unknown constraint"}.`,
|
||||
error === undefined
|
||||
? "HAR schema validation failed: unknown constraint."
|
||||
: `HAR schema validation failed: ${error.keyword} (${error.message ?? "no detail"}).`,
|
||||
error?.instancePath ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
captureMemoryFailure,
|
||||
} from "./CaptureFailures.js";
|
||||
import {
|
||||
HAR_CAPTURE_HEAP_ENFORCED,
|
||||
HAR_CAPTURE_HEAP_LIMITS,
|
||||
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
NODE_CAPTURE_HEAP_ENFORCED,
|
||||
NODE_CAPTURE_HEAP_LIMITS,
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
} from "./CaptureRelease.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
@@ -17,6 +17,7 @@ import { z } from "zod";
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
@@ -60,18 +62,52 @@ const replySchema = z.discriminatedUnion("ok", [
|
||||
|
||||
/** One owned snapshot/process/root lifecycle for replaceable historical format decoders. */
|
||||
export class HistoricalCaptureDecoder {
|
||||
readonly #resources: ArtifactResourceScope;
|
||||
|
||||
constructor(
|
||||
readonly adapters: readonly HistoricalCaptureFormatAdapter[],
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>,
|
||||
readonly createRuntime: () => Promise<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
> = () => PrivateRuntimeRoot.create({ prefix: "rea-web-capture-" }),
|
||||
) {}
|
||||
resources = new ArtifactResourceScope(),
|
||||
) {
|
||||
this.#resources = resources;
|
||||
}
|
||||
|
||||
/** Retry retained readers and private roots at service shutdown. */
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
|
||||
/** Snapshot the selected artifact, decode it offline, and release private credentials and processes. */
|
||||
async inspect(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>> {
|
||||
try {
|
||||
return await this.#resources.run(() =>
|
||||
this.inspectAdmitted(input, options),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const error = historicalCaptureFailure(
|
||||
input,
|
||||
cause,
|
||||
"capture-read",
|
||||
options,
|
||||
);
|
||||
return err(
|
||||
redactExplicitFailure(
|
||||
this.withReaderCleanup(error, cause),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async inspectAdmitted(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>> {
|
||||
let runtime: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
let result: Result<WebNetworkCapture, AnalysisError>;
|
||||
@@ -90,6 +126,8 @@ export class HistoricalCaptureDecoder {
|
||||
input.capture_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
phase = "decoder";
|
||||
runtime = await this.createRuntime();
|
||||
@@ -139,9 +177,16 @@ export class HistoricalCaptureDecoder {
|
||||
replyPath,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
reply = replySchema.parse(JSON.parse(replyFile.bytes.toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.cleanup !== undefined
|
||||
)
|
||||
throw cause;
|
||||
if (options?.signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION);
|
||||
throw new AnalysisOutputError(
|
||||
@@ -198,34 +243,53 @@ export class HistoricalCaptureDecoder {
|
||||
OPERATION,
|
||||
"Capture decoder changed the selected upstream profile identity.",
|
||||
);
|
||||
result = ok({
|
||||
...reply.value,
|
||||
const common = {
|
||||
artifact: {
|
||||
path: input.capture_path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
},
|
||||
format: input.format,
|
||||
runtime_attribution: "unknown",
|
||||
|
||||
runtime_attribution: "unknown" as const,
|
||||
limitations: [
|
||||
...(adapter.limitations ?? []),
|
||||
"This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.",
|
||||
"Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.",
|
||||
"Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.",
|
||||
`A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. ${harMemoryLimitation()}; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.`,
|
||||
`A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. ${nodeMemoryLimitation()}; mitmproxy decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.`,
|
||||
],
|
||||
});
|
||||
};
|
||||
if (input.format === "qlog") {
|
||||
if (!("qlog" in reply.value))
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture decoder omitted qlog transport facts.",
|
||||
);
|
||||
result = ok({ ...reply.value, ...common, format: "qlog" });
|
||||
} else {
|
||||
if ("qlog" in reply.value)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture decoder supplied inapplicable qlog transport facts.",
|
||||
);
|
||||
result = ok({ ...reply.value, ...common, format: input.format });
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
const error = historicalCaptureFailure(input, cause, phase, options);
|
||||
result = err(
|
||||
redactExplicitFailure(
|
||||
historicalCaptureFailure(input, cause, phase, options),
|
||||
this.withReaderCleanup(error, cause),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (runtime !== undefined) {
|
||||
try {
|
||||
await runtime.close();
|
||||
} catch (cause: unknown) {
|
||||
const cleanup = await this.#resources.release({
|
||||
kind: "private-runtime-root",
|
||||
resource: runtime.path,
|
||||
root: runtime,
|
||||
});
|
||||
if (cleanup.kind === "failed") {
|
||||
return err(
|
||||
redactExplicitFailure(
|
||||
new ProviderCleanupError(
|
||||
@@ -236,9 +300,12 @@ export class HistoricalCaptureDecoder {
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
reason:
|
||||
cleanup.cause instanceof Error
|
||||
? cleanup.cause.message
|
||||
: String(cleanup.cause),
|
||||
},
|
||||
{ operation: OPERATION },
|
||||
{ operation: OPERATION, cause: cleanup.cause },
|
||||
),
|
||||
input.sensitive_values,
|
||||
),
|
||||
@@ -249,15 +316,43 @@ export class HistoricalCaptureDecoder {
|
||||
? err(new AnalysisCancelledError(OPERATION))
|
||||
: result;
|
||||
}
|
||||
|
||||
private withReaderCleanup(
|
||||
primary: AnalysisError,
|
||||
cause: unknown,
|
||||
): AnalysisError {
|
||||
if (
|
||||
!(cause instanceof ArtifactReaderFailure) ||
|
||||
cause.cleanup === undefined
|
||||
)
|
||||
return primary;
|
||||
if (cause.reason === "unavailable")
|
||||
return new ProviderCleanupError(
|
||||
"web-network-capture",
|
||||
cause.cleanup.resources,
|
||||
{ reason: cause.cleanup.reason },
|
||||
{ operation: OPERATION, cause },
|
||||
);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
"web-network-capture",
|
||||
cause.cleanup.resources,
|
||||
{
|
||||
reason: cause.cleanup.reason,
|
||||
previous_error: projectAnalysisError(primary),
|
||||
},
|
||||
{ operation: OPERATION, cause },
|
||||
);
|
||||
return analysisErrorWithCleanupFailure(primary, cleanup, OPERATION);
|
||||
}
|
||||
}
|
||||
|
||||
/** The HAR decoder runs on this executable; only Node.js enforces its V8 heap flags. */
|
||||
const harMemoryLimitation = (): string => {
|
||||
if (HAR_CAPTURE_HEAP_ENFORCED)
|
||||
return `HAR uses a ${String(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
|
||||
return HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
|
||||
? "HAR runs on Bun, which does not enforce REA's V8 heap flags"
|
||||
: `HAR runs on Bun, which does not enforce REA's V8 heap flags, under a ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)}-byte Windows Job Object commit limit`;
|
||||
/** The Node capture decoder runs on this executable; only Node.js enforces its V8 heap flags. */
|
||||
const nodeMemoryLimitation = (): string => {
|
||||
if (NODE_CAPTURE_HEAP_ENFORCED)
|
||||
return `HAR/SAZ/qlog use a ${String(NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
|
||||
return NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
|
||||
? "HAR/SAZ/qlog run on Bun, which does not enforce REA's V8 heap flags"
|
||||
: `HAR/SAZ/qlog run on Bun, which does not enforce REA's V8 heap flags, under a ${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)}-byte Windows Job Object commit limit`;
|
||||
};
|
||||
|
||||
const replyFailureReason = (cause: unknown): string => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { InspectWebNetworkCaptureInput } from "../../domain/webNetworkCaptu
|
||||
/** Format-specific process profile keeps mature upstream code behind a replaceable adapter seam. */
|
||||
export interface HistoricalCaptureFormatAdapter {
|
||||
readonly format: InspectWebNetworkCaptureInput["format"];
|
||||
readonly limitations?: readonly string[];
|
||||
readonly identity: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import { NodeCaptureAdapter } from "./NodeCaptureAdapter.js";
|
||||
|
||||
vi.mock("./CaptureRelease.js", async (original) => ({
|
||||
...(await original<typeof import("./CaptureRelease.js")>()),
|
||||
NODE_CAPTURE_HEAP_ENFORCED: false,
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES: null,
|
||||
}));
|
||||
|
||||
it.each(["saz", "qlog"] as const)(
|
||||
"refuses a %s worker when the runtime has no enforceable memory bound",
|
||||
async (format) => {
|
||||
await expect(
|
||||
new NodeCaptureAdapter(format).command("/owned/request.json"),
|
||||
).rejects.toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,61 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import {
|
||||
NODE_CAPTURE_HEAP_ENFORCED,
|
||||
HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
SAZ_CAPTURE_PROVIDER_IDENTITY,
|
||||
QLOG_CAPTURE_PROVIDER_IDENTITY,
|
||||
NODE_CAPTURE_HEAP_LIMITS,
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
|
||||
} from "./CaptureRelease.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
|
||||
/** Package-backed capture decoders share one bounded offline Node process profile. */
|
||||
export class NodeCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly identity;
|
||||
readonly limitations;
|
||||
constructor(readonly format: "har" | "saz" | "qlog") {
|
||||
this.identity =
|
||||
format === "har"
|
||||
? HAR_CAPTURE_PROVIDER_IDENTITY
|
||||
: format === "saz"
|
||||
? SAZ_CAPTURE_PROVIDER_IDENTITY
|
||||
: QLOG_CAPTURE_PROVIDER_IDENTITY;
|
||||
this.limitations =
|
||||
format === "saz"
|
||||
? [
|
||||
"SAZ ordinals follow first session-member occurrence in ZIP directory order, not chronology or numeric session ID.",
|
||||
"HTTP fields use byte-preserving Latin-1 text; start-line separators and header delimiters are not projected. Bodies retain stored bytes without transfer/content decoding. Absent members are null, distinct from empty bodies.",
|
||||
"XML preserves node order and attribute/text values, not its original byte serialization. WebSocket and gRPC members retain opaque message-file bytes, not decoded protocol events.",
|
||||
"Non-session archive members are inventoried but their content is not decoded.",
|
||||
]
|
||||
: [];
|
||||
}
|
||||
async command(requestPath: string) {
|
||||
if (
|
||||
this.format !== "har" &&
|
||||
!NODE_CAPTURE_HEAP_ENFORCED &&
|
||||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
this.identity.id,
|
||||
"inspect_web_network_capture",
|
||||
`${this.format} decoding requires an enforced decoder memory limit. Run REA with Node.js on this host.`,
|
||||
);
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
`--max-old-space-size=${NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB}`,
|
||||
`--max-semi-space-size=${NODE_CAPTURE_HEAP_LIMITS.semiSpaceMiB}`,
|
||||
"--v8-pool-size=1",
|
||||
"--single-threaded",
|
||||
fileURLToPath(new URL("./NodeCaptureProcess.js", import.meta.url)),
|
||||
requestPath,
|
||||
this.format,
|
||||
],
|
||||
...(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
|
||||
? {}
|
||||
: { memoryLimitBytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }),
|
||||
};
|
||||
}
|
||||
}
|
||||
+26
-14
@@ -3,7 +3,6 @@ import { z } from "zod";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import { decodeHarCapture, decodeHarText } from "./HarCapture.js";
|
||||
|
||||
const requestSchema = z.strictObject({
|
||||
snapshot_path: z.string(),
|
||||
@@ -11,24 +10,37 @@ const requestSchema = z.strictObject({
|
||||
sensitive_values: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
/** Decode untrusted HAR in an owned, bounded heap rather than the long-lived MCP process. */
|
||||
/** Parse untrusted captures in an owned heap and return one complete bounded reply. */
|
||||
const main = async (): Promise<void> => {
|
||||
const format = z.enum(["har", "saz", "qlog"]).parse(process.argv[3]);
|
||||
const request = requestSchema.parse(
|
||||
JSON.parse(await readFile(process.argv[2] ?? "", "utf8")),
|
||||
);
|
||||
let reply: unknown;
|
||||
try {
|
||||
const snapshot = await readStableArtifact(
|
||||
request.snapshot_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
reply = {
|
||||
ok: true,
|
||||
value: decodeHarCapture(
|
||||
decodeHarText(snapshot.bytes),
|
||||
let value;
|
||||
if (format !== "saz") {
|
||||
const { decodeCaptureText } = await import("./CaptureJson.js");
|
||||
const decoder =
|
||||
format === "har"
|
||||
? (await import("./HarCapture.js")).decodeHarCapture
|
||||
: (await import("./QlogCapture.js")).decodeQlogCapture;
|
||||
const snapshot = await readStableArtifact(
|
||||
request.snapshot_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
value = decoder(
|
||||
decodeCaptureText(snapshot.bytes, format === "har" ? "HAR" : "qlog"),
|
||||
request.sensitive_values,
|
||||
),
|
||||
};
|
||||
);
|
||||
} else {
|
||||
const { decodeSazCapture } = await import("./SazCapture.js");
|
||||
value = await decodeSazCapture(
|
||||
request.snapshot_path,
|
||||
request.sensitive_values,
|
||||
);
|
||||
}
|
||||
reply = { ok: true, value };
|
||||
} catch (cause: unknown) {
|
||||
reply =
|
||||
cause instanceof CaptureFormatError
|
||||
@@ -41,7 +53,7 @@ const main = async (): Promise<void> => {
|
||||
: {
|
||||
ok: false,
|
||||
reason: "decoder",
|
||||
message: `HAR decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
|
||||
message: `Capture decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
|
||||
pointer: "",
|
||||
};
|
||||
}
|
||||
@@ -50,7 +62,7 @@ const main = async (): Promise<void> => {
|
||||
text = JSON.stringify({
|
||||
ok: false,
|
||||
reason: "limit",
|
||||
message: "HAR reply exceeds the complete-evidence output budget.",
|
||||
message: "Capture reply exceeds the complete-evidence output budget.",
|
||||
pointer: "",
|
||||
});
|
||||
await writeFile(request.reply_path, text, { flag: "wx", mode: 0o600 });
|
||||
@@ -0,0 +1,259 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { decodeQlogCapture } from "./QlogCapture.js";
|
||||
import { decodeCaptureText } from "./CaptureJson.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
|
||||
// Synthetic format inputs exercise distinct parser semantics, not producer provenance.
|
||||
const event = (frames: unknown[], name = "transport:packet_sent") => ({
|
||||
name,
|
||||
time: 1791819895000.25,
|
||||
data: { header: { packet_type: "1RTT", packet_number: 5 }, frames },
|
||||
});
|
||||
const frame = (offset: number, length: number, fin = false) => ({
|
||||
frame_type: "stream",
|
||||
stream_id: 0,
|
||||
offset,
|
||||
length,
|
||||
fin,
|
||||
});
|
||||
const capture = (events: unknown[], extra: Record<string, unknown> = {}) =>
|
||||
JSON.stringify({
|
||||
qlog_format: "JSON",
|
||||
qlog_version: "0.3",
|
||||
...extra,
|
||||
traces: [
|
||||
{
|
||||
common_fields: { ODCID: "same" },
|
||||
vantage_point: { name: "aioquic", type: "server" },
|
||||
events,
|
||||
},
|
||||
],
|
||||
});
|
||||
const facts = (text: string, sensitive: string[] = []) => {
|
||||
const decoded = decodeQlogCapture(text, sensitive);
|
||||
if (!("qlog" in decoded)) throw new Error("qlog facet required");
|
||||
return { decoded, traces: decoded.qlog.traces };
|
||||
};
|
||||
|
||||
it("derives interval unions per trace/direction while retaining event source order and extensions", () => {
|
||||
const original = JSON.parse(
|
||||
capture([
|
||||
event([frame(10, 10)]),
|
||||
event([frame(0, 15), frame(30, 5, true)]),
|
||||
event([frame(0, 4)], "transport:packet_received"),
|
||||
{
|
||||
name: "recovery:packet_lost",
|
||||
time: 1,
|
||||
data: { packet_number: 5, type: "1RTT" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
original.traces.push({
|
||||
...original.traces[0],
|
||||
events: [event([frame(0, 3)])],
|
||||
});
|
||||
Object.defineProperty(original, "__proto__", {
|
||||
enumerable: true,
|
||||
value: { ordinary: true },
|
||||
});
|
||||
original.extra = "https://example.test/path?token=ordinary";
|
||||
const { decoded, traces } = facts(JSON.stringify(original));
|
||||
expect(traces[0]?.streams[0]).toMatchObject({
|
||||
stream_id: "0",
|
||||
direction: "sent",
|
||||
unique_bytes: "25",
|
||||
frame_length_sum: "30",
|
||||
repeated_bytes: "5",
|
||||
covered_ranges: [
|
||||
{ start: "0", end: "20" },
|
||||
{ start: "30", end: "35" },
|
||||
],
|
||||
reported_final_sizes: ["35"],
|
||||
});
|
||||
expect(traces[0]?.streams[1]).toMatchObject({
|
||||
direction: "received",
|
||||
unique_bytes: "4",
|
||||
});
|
||||
expect(traces[1]?.streams[0]).toMatchObject({ unique_bytes: "3" });
|
||||
expect(traces[0]?.loss_declarations[0]).toMatchObject({
|
||||
confidence: "observed",
|
||||
packet_number: { state: "reported", value: "5" },
|
||||
packet_number_space: "application",
|
||||
});
|
||||
expect(decoded.records.at(-1)?.location).toEqual({
|
||||
kind: "json-pointer",
|
||||
pointer: "/traces/1/events/0",
|
||||
});
|
||||
expect(decoded.container.reported).toMatchObject({
|
||||
extra: original.extra,
|
||||
["__proto__"]: { ordinary: true },
|
||||
});
|
||||
expect(Reflect.get(Object.prototype, "ordinary")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps exact 62-bit integers and numeric lexemes without allocating exponent expansion", () => {
|
||||
const text = capture([event([frame(0, 0, true)])])
|
||||
.replace('"stream_id":0', '"stream_id":4611686018427387903')
|
||||
.replace('"offset":0', '"offset":9007199254740993')
|
||||
.replace('"length":0', '"length":1e3');
|
||||
const { decoded, traces } = facts(text);
|
||||
expect(traces[0]?.streams[0]).toMatchObject({
|
||||
stream_id: "4611686018427387903",
|
||||
unique_bytes: "1000",
|
||||
reported_final_sizes: ["9007199254741993"],
|
||||
});
|
||||
expect(decoded.records[0]?.numeric_literals).toContainEqual({
|
||||
pointer: "/data/frames/0/length",
|
||||
producer_type: "json-number",
|
||||
literal: "1e3",
|
||||
});
|
||||
expect(decoded.records[0]?.reported).toMatchObject({
|
||||
data: { frames: [{ stream_id: null, offset: null, length: 1000 }] },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps incomplete fields unknown and FIN without bytes as metadata", () => {
|
||||
const { traces } = facts(
|
||||
capture([
|
||||
event([{ frame_type: "stream", stream_id: 0, length: 5 }]),
|
||||
event([frame(10, 0, true)]),
|
||||
{ name: "recovery:packet_lost", time: 1, data: {} },
|
||||
{
|
||||
name: "extension:custom",
|
||||
time: 0,
|
||||
data: { body: "ordinary evidence" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(traces[0]?.incomplete_fact_records).toEqual([0]);
|
||||
expect(traces[0]?.streams[0]).toMatchObject({
|
||||
unique_bytes: "0",
|
||||
covered_ranges: [],
|
||||
reported_final_sizes: ["10"],
|
||||
});
|
||||
expect(traces[0]?.loss_declarations[0]?.packet_number.state).toBe("unknown");
|
||||
});
|
||||
|
||||
it("excludes structural auth material and explicit normalized values without guessing extension secrecy", () => {
|
||||
const text = capture([
|
||||
{
|
||||
name: "http:frame_parsed",
|
||||
time: 1,
|
||||
data: {
|
||||
frame: {
|
||||
frame_type: "headers",
|
||||
headers: [
|
||||
{ name: "authorization", value: "Bearer credential" },
|
||||
{ name: ":path", value: "/?token=ordinary" },
|
||||
{ name: "location", value: "https://user:pass@example.test/a" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "transport:parameters_set",
|
||||
time: 2,
|
||||
data: { stateless_reset_token: "reset-credential" },
|
||||
},
|
||||
event([
|
||||
{ frame_type: "new_connection_id", reset_token: "reset-frame" },
|
||||
{ frame_type: "new_token", token: "new-token" },
|
||||
frame(0, 100),
|
||||
]),
|
||||
{
|
||||
name: "extension:custom",
|
||||
time: 3,
|
||||
data: {
|
||||
secret: "caller-selected ordinary value",
|
||||
reset_token: "extension ordinary",
|
||||
},
|
||||
},
|
||||
]).replace('"length":100', '"length":1e2');
|
||||
const { decoded, traces } = facts(text, ["100"]);
|
||||
const serialized = JSON.stringify(decoded);
|
||||
for (const hidden of [
|
||||
"Bearer credential",
|
||||
"reset-credential",
|
||||
"reset-frame",
|
||||
"new-token",
|
||||
"100",
|
||||
"user:pass",
|
||||
])
|
||||
expect(serialized).not.toContain(hidden);
|
||||
expect(serialized).toContain("token=ordinary");
|
||||
expect(serialized).toContain("caller-selected ordinary value");
|
||||
expect(traces[0]?.streams).toEqual([]);
|
||||
expect(traces[0]?.incomplete_fact_records).toContain(2);
|
||||
});
|
||||
|
||||
it("hides marked ancestor keys and safe derived sums while still validating hidden subtrees", () => {
|
||||
const text = capture([event([frame(0, 3), frame(3, 4)])]);
|
||||
expect(facts(text, ["7"]).traces[0]?.streams).toEqual([]);
|
||||
const { decoded, traces } = facts(text, ["events"]);
|
||||
expect(decoded.records[0]?.reported).toBe(null);
|
||||
expect(decoded.records[0]?.location.kind).toBe("unknown");
|
||||
expect(traces[0]?.location.kind).toBe("unknown");
|
||||
expect(traces[0]?.streams).toEqual([]);
|
||||
expect(() =>
|
||||
facts(text.replace('"length":3', '"length":-3'), ["events"]),
|
||||
).toThrow(CaptureFormatError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"-1",
|
||||
"0.5",
|
||||
"4611686018427387904",
|
||||
"1e1000000",
|
||||
"1e-1000000",
|
||||
'"3"',
|
||||
"true",
|
||||
])("rejects malformed or out-of-range STREAM integer %s", (literal) => {
|
||||
expect(() =>
|
||||
facts(
|
||||
capture([event([frame(0, 3)])]).replace(
|
||||
'"length":3',
|
||||
`"length":${literal}`,
|
||||
),
|
||||
),
|
||||
).toThrow(CaptureFormatError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'{"qlog_format":"JSON","qlog_format":"JSON","qlog_version":"0.3","traces":[]}',
|
||||
capture([]).slice(0, -1),
|
||||
capture([]) + " {}",
|
||||
capture([{ name: "invalid", time: "1", data: {} }]),
|
||||
capture([[1, "transport", "packet_sent", {}]]),
|
||||
capture([event([{ ...frame(0, 1), fin: "true" }])]),
|
||||
capture([event([{ ...frame(0, 1), offset: 4611686018427388000 }])]),
|
||||
])(
|
||||
"rejects malformed JSON/profile events with no partial success: %s",
|
||||
(text) => {
|
||||
expect(() => facts(text)).toThrow(CaptureFormatError);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects other qlog containers/versions and excessive nesting, accepts empty profiles and UTF-8 BOM", () => {
|
||||
for (const extra of [{ qlog_format: "JSON-SEQ" }, { qlog_version: "0.4" }])
|
||||
expect(() => facts(capture([], extra))).toThrow("Only the aioquic");
|
||||
expect(() =>
|
||||
facts(
|
||||
capture([], {
|
||||
extension: JSON.parse("[".repeat(65) + "0" + "]".repeat(65)),
|
||||
}),
|
||||
),
|
||||
).toThrow("nesting budget");
|
||||
expect(
|
||||
facts('{"qlog_format":"JSON","qlog_version":"0.3","traces":[]}').traces,
|
||||
).toEqual([]);
|
||||
const raw = Buffer.from(capture([]));
|
||||
expect(
|
||||
facts(
|
||||
decodeCaptureText(
|
||||
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), raw]),
|
||||
"qlog",
|
||||
),
|
||||
).decoded.total_records,
|
||||
).toBe(0);
|
||||
expect(() => decodeCaptureText(Buffer.from([0xff]), "qlog")).toThrow("UTF-8");
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user