chore: reconcile iNES inventory with current main
This commit is contained in:
@@ -508,6 +508,44 @@ it("reads a bounded logcat dump with the caller count and buffer", async () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports UTF-8 byte counts in total_bytes for non-ASCII logcat output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
logcat:
|
||||
"08-10 13:00:00.000 I/Tag( 1): 中文\n08-10 13:00:00.000 I/Tag( 1): 😀\n",
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "read_adb_logcat",
|
||||
input: { serial: "emulator-5554", count: 500, buffer: "main" },
|
||||
});
|
||||
expect(result.lines).toEqual([
|
||||
"08-10 13:00:00.000 I/Tag( 1): 中文",
|
||||
"08-10 13:00:00.000 I/Tag( 1): 😀",
|
||||
]);
|
||||
// 30-byte prefix + 6-byte CJK + LF = 37; 30-byte prefix + 4-byte emoji + LF = 35.
|
||||
expect(result.total_bytes).toBe(72);
|
||||
});
|
||||
|
||||
it("counts raw captured bytes in total_bytes for malformed UTF-8 logcat output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "shell" ]; then
|
||||
printf '%b' '08-10 13:00:00.000 I/Tag( 1): A\\377B\\n'
|
||||
exit 0
|
||||
fi
|
||||
printf 'unexpected arguments: %s\\n' "$@"
|
||||
exit 1`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "read_adb_logcat",
|
||||
input: { serial: "emulator-5554", count: 500, buffer: "main" },
|
||||
});
|
||||
// 30-byte prefix + "A" + one raw 0xff byte + "B" + LF = 34 captured bytes.
|
||||
// Re-encoding the decoded U+FFFD replacement would report 36.
|
||||
expect(result.total_bytes).toBe(34);
|
||||
});
|
||||
|
||||
it("projects package details from dumpsys package output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
@@ -1086,10 +1124,10 @@ it("rejects mistyped intent extras before touching the device", async () => {
|
||||
|
||||
it("collects a device bugreport archive with its digest", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "bugreport" ]; then
|
||||
printf 'bugreport-bytes' > "${join(root, "bugreport test.zip")}"
|
||||
printf 'Bug report copied to ${join(root, "bugreport test.zip")}\\n'
|
||||
printf 'bugreport-bytes' > "$4/bugreport test.zip"
|
||||
printf 'Bug report copied to %s/bugreport test.zip\\n' "$4"
|
||||
exit 0
|
||||
fi
|
||||
exit 1`,
|
||||
@@ -1103,7 +1141,7 @@ exit 1`,
|
||||
local_path: join(root, "bugreport test.zip"),
|
||||
bytes: 15,
|
||||
sha256: digest,
|
||||
adb_reported_path: join(root, "bugreport test.zip"),
|
||||
adb_reported_path: expect.stringContaining(".rea-bugreport-"),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+271
-101
@@ -2,14 +2,16 @@ import { createHash } from "node:crypto";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
copyFile,
|
||||
lstat,
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
rmdir,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { basename, dirname, extname, join, resolve } from "node:path";
|
||||
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
@@ -20,7 +22,12 @@ import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisExecution,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { AdbRequest } from "../domain/adb/adbDeviceAnalysis.js";
|
||||
import type {
|
||||
AdbActivityStartPartialObservation,
|
||||
AdbAcquiredFilePartialObservation,
|
||||
AdbRequest,
|
||||
} from "../domain/adb/adbDeviceAnalysis.js";
|
||||
import { adbResultSchemas } from "../domain/adb/adbDeviceAnalysis.js";
|
||||
import {
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
@@ -227,12 +234,17 @@ const runAdbCapture = async (
|
||||
/** Decode textual adb protocols after the shared byte capture and error boundary. */
|
||||
const runAdb = async (
|
||||
...arguments_: Parameters<typeof runAdbCapture>
|
||||
): Promise<Result<{ stdout: string; stderr: string }, AnalysisError>> => {
|
||||
): Promise<
|
||||
Result<{ stdout: string; stderr: string; stdoutBytes: number }, AnalysisError>
|
||||
> => {
|
||||
const captured = await runAdbCapture(...arguments_);
|
||||
if (!captured.ok) return captured;
|
||||
return ok({
|
||||
stdout: captured.value.stdout.toString("utf8"),
|
||||
stderr: captured.value.stderr.toString("utf8"),
|
||||
// Byte count of the captured output before UTF-8 decoding, so malformed
|
||||
// sequences replaced by U+FFFD still report their true captured size.
|
||||
stdoutBytes: captured.value.stdout.byteLength,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -305,30 +317,56 @@ const refuseExistingTarget = async (
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Publish an ADB-produced archive without replacing an existing caller file. */
|
||||
const publishBugreport = async (
|
||||
source: string,
|
||||
directory: string,
|
||||
): Promise<string> => {
|
||||
const fileName = basename(source);
|
||||
const extension = extname(fileName);
|
||||
const stem =
|
||||
extension === "" ? fileName : fileName.slice(0, -extension.length);
|
||||
for (let suffix = 0; ; suffix += 1) {
|
||||
const destination = join(
|
||||
directory,
|
||||
suffix === 0 ? fileName : `${stem} (${String(suffix)})${extension}`,
|
||||
);
|
||||
try {
|
||||
await copyFile(source, destination, fsConstants.COPYFILE_EXCL);
|
||||
return destination;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
|
||||
continue;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export interface AdbProviderOptions {
|
||||
readonly environment?: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
interface PendingPackageDirectoryCleanup {
|
||||
interface PendingOutputDirectoryCleanup {
|
||||
readonly operation: "pull_adb_package" | "collect_adb_bugreport";
|
||||
readonly path: string;
|
||||
readonly identity: PackageDirectoryIdentity | undefined;
|
||||
readonly identity: OutputDirectoryIdentity | undefined;
|
||||
readonly primary: AnalysisError;
|
||||
readonly remove: () => Promise<void>;
|
||||
}
|
||||
|
||||
interface PackageDirectoryIdentity {
|
||||
interface OutputDirectoryIdentity {
|
||||
readonly dev: number;
|
||||
readonly ino: number;
|
||||
readonly mode: number;
|
||||
}
|
||||
|
||||
const removeOwnedPackageDirectory = async (
|
||||
const removeOwnedOutputDirectory = async (
|
||||
path: string,
|
||||
identity: PackageDirectoryIdentity | undefined,
|
||||
identity: OutputDirectoryIdentity | undefined,
|
||||
): Promise<void> => {
|
||||
if (identity === undefined)
|
||||
throw new Error(
|
||||
`Cannot verify the created package directory identity; refusing to remove ${path}`,
|
||||
`Cannot verify the created output directory identity; refusing to remove ${path}`,
|
||||
);
|
||||
let current: Awaited<ReturnType<typeof lstat>>;
|
||||
try {
|
||||
@@ -346,7 +384,7 @@ const removeOwnedPackageDirectory = async (
|
||||
current.mode !== identity.mode
|
||||
)
|
||||
throw new Error(
|
||||
`The created package directory was replaced or changed; refusing to remove ${path}`,
|
||||
`The created output directory was replaced or changed; refusing to remove ${path}`,
|
||||
);
|
||||
await rm(path, { recursive: true, force: true });
|
||||
};
|
||||
@@ -363,7 +401,7 @@ const reservePackageDestinations = async (
|
||||
): Promise<AnalysisOutputError | undefined> => {
|
||||
const reservations: {
|
||||
readonly path: string;
|
||||
readonly identity: PackageDirectoryIdentity;
|
||||
readonly identity: OutputDirectoryIdentity;
|
||||
}[] = [];
|
||||
for (const entry of entries) {
|
||||
const path = join(packageDirectory, entry.file_name);
|
||||
@@ -424,12 +462,12 @@ const reservePackageDestinations = async (
|
||||
*/
|
||||
export class AdbProvider {
|
||||
private readonly environment: Readonly<Record<string, string | undefined>>;
|
||||
readonly #pendingPackageDirectoryCleanup =
|
||||
new Set<PendingPackageDirectoryCleanup>();
|
||||
readonly #pendingOutputDirectoryCleanup =
|
||||
new Set<PendingOutputDirectoryCleanup>();
|
||||
readonly #activeOperations = new Set<Promise<void>>();
|
||||
#closing = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#packageCleanupPromise: Promise<void> | undefined;
|
||||
#outputCleanupPromise: Promise<void> | undefined;
|
||||
|
||||
constructor(options: AdbProviderOptions = {}) {
|
||||
this.environment = options.environment ?? process.env;
|
||||
@@ -462,13 +500,13 @@ export class AdbProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry removal of package directories retained after failed rollback. */
|
||||
/** Retry removal of owned output directories retained after failed cleanup. */
|
||||
close(): Promise<void> {
|
||||
this.#closing = true;
|
||||
if (this.#closePromise !== undefined) return this.#closePromise;
|
||||
const closing = (async () => {
|
||||
await Promise.all(this.#activeOperations);
|
||||
await this.#retryPackageDirectoryCleanup();
|
||||
await this.#retryOutputDirectoryCleanup();
|
||||
})().finally(() => {
|
||||
if (this.#closePromise === closing) this.#closePromise = undefined;
|
||||
});
|
||||
@@ -476,23 +514,23 @@ export class AdbProvider {
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
#retryPackageDirectoryCleanup(): Promise<void> {
|
||||
if (this.#packageCleanupPromise !== undefined)
|
||||
return this.#packageCleanupPromise;
|
||||
const cleanup = this.#performPackageDirectoryCleanup().finally(() => {
|
||||
if (this.#packageCleanupPromise === cleanup)
|
||||
this.#packageCleanupPromise = undefined;
|
||||
#retryOutputDirectoryCleanup(): Promise<void> {
|
||||
if (this.#outputCleanupPromise !== undefined)
|
||||
return this.#outputCleanupPromise;
|
||||
const cleanup = this.#performOutputDirectoryCleanup().finally(() => {
|
||||
if (this.#outputCleanupPromise === cleanup)
|
||||
this.#outputCleanupPromise = undefined;
|
||||
});
|
||||
this.#packageCleanupPromise = cleanup;
|
||||
this.#outputCleanupPromise = cleanup;
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
async #performPackageDirectoryCleanup(): Promise<void> {
|
||||
async #performOutputDirectoryCleanup(): Promise<void> {
|
||||
const failures: AnalysisError[] = [];
|
||||
for (const owner of this.#pendingPackageDirectoryCleanup) {
|
||||
for (const owner of this.#pendingOutputDirectoryCleanup) {
|
||||
try {
|
||||
await owner.remove();
|
||||
this.#pendingPackageDirectoryCleanup.delete(owner);
|
||||
this.#pendingOutputDirectoryCleanup.delete(owner);
|
||||
} catch (cause: unknown) {
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
@@ -500,13 +538,13 @@ export class AdbProvider {
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: "pull_adb_package", cause },
|
||||
{ operation: owner.operation, cause },
|
||||
);
|
||||
failures.push(
|
||||
analysisErrorWithCleanupFailure(
|
||||
owner.primary,
|
||||
cleanup,
|
||||
"pull_adb_package",
|
||||
owner.operation,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -515,20 +553,22 @@ export class AdbProvider {
|
||||
if (failures.length > 1)
|
||||
throw new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[...this.#pendingPackageDirectoryCleanup].map(({ path }) => path),
|
||||
[...this.#pendingOutputDirectoryCleanup].map(({ path }) => path),
|
||||
{
|
||||
reason:
|
||||
"Failed package output directories remain after cleanup retry",
|
||||
reason: "Failed ADB output directories remain after cleanup retry",
|
||||
operations: [...this.#pendingOutputDirectoryCleanup].map(
|
||||
({ operation }) => operation,
|
||||
),
|
||||
failures: failures.map(({ message, cleanupResources }) => ({
|
||||
message,
|
||||
resources: [...cleanupResources],
|
||||
})),
|
||||
},
|
||||
{
|
||||
operation: "pull_adb_package",
|
||||
operation: "close_binary",
|
||||
cause: new AggregateError(
|
||||
failures,
|
||||
"Multiple ADB package rollback cleanups failed",
|
||||
"Multiple ADB output directory cleanups failed",
|
||||
),
|
||||
},
|
||||
);
|
||||
@@ -546,16 +586,16 @@ export class AdbProvider {
|
||||
});
|
||||
this.#activeOperations.add(active);
|
||||
try {
|
||||
if (this.#pendingPackageDirectoryCleanup.size > 0) {
|
||||
if (this.#pendingOutputDirectoryCleanup.size > 0) {
|
||||
try {
|
||||
await this.#retryPackageDirectoryCleanup();
|
||||
await this.#retryOutputDirectoryCleanup();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[...this.#pendingPackageDirectoryCleanup].map(
|
||||
[...this.#pendingOutputDirectoryCleanup].map(
|
||||
({ path }) => path,
|
||||
),
|
||||
{
|
||||
@@ -782,7 +822,7 @@ export class AdbProvider {
|
||||
buffer: request.input.buffer,
|
||||
pid: request.input.pid ?? null,
|
||||
lines: bounded,
|
||||
total_bytes: ran.value.stdout.length,
|
||||
total_bytes: ran.value.stdoutBytes,
|
||||
coverage:
|
||||
bounded.length !== lines.length ||
|
||||
bounded.length === request.input.count
|
||||
@@ -1245,7 +1285,7 @@ export class AdbProvider {
|
||||
if (!directory.ok) return directory;
|
||||
const packageDirectory = join(directory.value, packageName);
|
||||
let packageDirectoryCreated = false;
|
||||
let packageDirectoryIdentity: PackageDirectoryIdentity | undefined;
|
||||
let packageDirectoryIdentity: OutputDirectoryIdentity | undefined;
|
||||
try {
|
||||
if (
|
||||
await lstat(packageDirectory).then(
|
||||
@@ -1275,17 +1315,18 @@ export class AdbProvider {
|
||||
{ cause },
|
||||
);
|
||||
if (!packageDirectoryCreated) return err(primary);
|
||||
const owner: PendingPackageDirectoryCleanup = {
|
||||
const owner: PendingOutputDirectoryCleanup = {
|
||||
operation,
|
||||
path: packageDirectory,
|
||||
identity: packageDirectoryIdentity,
|
||||
primary,
|
||||
remove: () =>
|
||||
removeOwnedPackageDirectory(
|
||||
removeOwnedOutputDirectory(
|
||||
packageDirectory,
|
||||
packageDirectoryIdentity,
|
||||
),
|
||||
};
|
||||
this.#pendingPackageDirectoryCleanup.add(owner);
|
||||
this.#pendingOutputDirectoryCleanup.add(owner);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[packageDirectory],
|
||||
@@ -1299,12 +1340,13 @@ export class AdbProvider {
|
||||
const failOwnedPackage = async (
|
||||
primary: AnalysisError,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> => {
|
||||
const owner: PendingPackageDirectoryCleanup = {
|
||||
const owner: PendingOutputDirectoryCleanup = {
|
||||
operation,
|
||||
path: packageDirectory,
|
||||
identity: packageDirectoryIdentity,
|
||||
primary,
|
||||
remove: () =>
|
||||
removeOwnedPackageDirectory(
|
||||
removeOwnedOutputDirectory(
|
||||
packageDirectory,
|
||||
packageDirectoryIdentity,
|
||||
),
|
||||
@@ -1312,7 +1354,7 @@ export class AdbProvider {
|
||||
try {
|
||||
await owner.remove();
|
||||
} catch (cause: unknown) {
|
||||
this.#pendingPackageDirectoryCleanup.add(owner);
|
||||
this.#pendingOutputDirectoryCleanup.add(owner);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[packageDirectory],
|
||||
@@ -1945,28 +1987,55 @@ export class AdbProvider {
|
||||
signal,
|
||||
);
|
||||
if (!started.ok) return started;
|
||||
const verdict = parseAmStartOutput(started.value.stdout);
|
||||
if (verdict.status === "refused")
|
||||
const verdict = parseAmStartOutput(
|
||||
started.value.stdout,
|
||||
started.value.stderr,
|
||||
);
|
||||
const result = {
|
||||
...resultFields,
|
||||
started_activity: verdict.startedActivity,
|
||||
reported_activity: verdict.activity,
|
||||
reported_status: verdict.reportedStatus,
|
||||
};
|
||||
if (verdict.status === "refused") {
|
||||
const partialObservation: AdbActivityStartPartialObservation =
|
||||
operation === "start_adb_app"
|
||||
? {
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: adbResultSchemas.start_adb_app.parse(result),
|
||||
}
|
||||
: {
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: adbResultSchemas.start_adb_activity.parse(result),
|
||||
};
|
||||
return err(
|
||||
new AnalysisUnsupportedTargetError(
|
||||
operation,
|
||||
serial,
|
||||
verdict.reason ?? "am start refused the intent",
|
||||
{
|
||||
capturedOutput: {
|
||||
stdout: started.value.stdout,
|
||||
stderr: started.value.stderr,
|
||||
truncated: false,
|
||||
},
|
||||
partialObservation,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
...resultFields,
|
||||
started_activity: verdict.startedActivity,
|
||||
createAnalysisExecution(result, provider, {
|
||||
rawResult: {
|
||||
stdout: started.value.stdout,
|
||||
stderr: started.value.stderr,
|
||||
},
|
||||
provider,
|
||||
{
|
||||
limitations: [
|
||||
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
|
||||
],
|
||||
},
|
||||
) as AnalysisExecution,
|
||||
limitations: [
|
||||
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
|
||||
],
|
||||
}) as AnalysisExecution,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2084,48 +2153,71 @@ export class AdbProvider {
|
||||
input.output_directory,
|
||||
);
|
||||
if (!directory.ok) return directory;
|
||||
const collected = await runAdb(
|
||||
operation,
|
||||
input.serial,
|
||||
selection.binary,
|
||||
adbArguments(input.serial, ["bugreport", directory.value]),
|
||||
{
|
||||
timeoutMs: BUGREPORT_TIMEOUT_MS,
|
||||
maxOutputBytes: BUGREPORT_MAX_OUTPUT_BYTES,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!collected.ok) return collected;
|
||||
const reportedPath = parseBugreportCopiedPath(collected.value.stdout);
|
||||
if (reportedPath === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"adb bugreport did not report an archive path; the build may use an unsupported format",
|
||||
),
|
||||
);
|
||||
let stagingDirectory: string;
|
||||
let stagingIdentity: OutputDirectoryIdentity | undefined;
|
||||
let retainedObservation: AdbAcquiredFilePartialObservation | undefined;
|
||||
let publishedPath: string | undefined;
|
||||
try {
|
||||
const digest = await hashAdbFile(reportedPath, operation, signal);
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
client,
|
||||
serial: input.serial,
|
||||
local_path: reportedPath,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
adb_reported_path: reportedPath,
|
||||
},
|
||||
provider,
|
||||
{
|
||||
limitations: [
|
||||
"The archive is device-generated: dumpstate, dumpsys, and logcat content is the device's own report",
|
||||
],
|
||||
},
|
||||
),
|
||||
stagingDirectory = await mkdtemp(
|
||||
join(directory.value, ".rea-bugreport-"),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisCancelledError) {
|
||||
cause.retainPartialObservation({
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"The bugreport staging directory could not be created",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
const collectedResult = await (async (): Promise<
|
||||
Result<AnalysisExecution, AnalysisError>
|
||||
> => {
|
||||
let reportedPath: string | null = null;
|
||||
try {
|
||||
const created = await lstat(stagingDirectory);
|
||||
if (!created.isDirectory() || created.isSymbolicLink())
|
||||
throw new Error(
|
||||
`The created bugreport staging output is not a regular directory: ${stagingDirectory}`,
|
||||
);
|
||||
stagingIdentity = {
|
||||
dev: created.dev,
|
||||
ino: created.ino,
|
||||
mode: created.mode,
|
||||
};
|
||||
const collected = await runAdb(
|
||||
operation,
|
||||
input.serial,
|
||||
selection.binary,
|
||||
adbArguments(input.serial, ["bugreport", stagingDirectory]),
|
||||
{
|
||||
timeoutMs: BUGREPORT_TIMEOUT_MS,
|
||||
maxOutputBytes: BUGREPORT_MAX_OUTPUT_BYTES,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!collected.ok) return collected;
|
||||
reportedPath = parseBugreportCopiedPath(collected.value.stdout);
|
||||
if (reportedPath === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"adb bugreport did not report an archive path; the build may use an unsupported format",
|
||||
),
|
||||
);
|
||||
if (dirname(resolve(reportedPath)) !== stagingDirectory)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
`adb bugreport reported an archive outside its staging directory: ${reportedPath}`,
|
||||
),
|
||||
);
|
||||
const archive = await lstat(reportedPath);
|
||||
if (!archive.isFile() || archive.isSymbolicLink())
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
`adb bugreport did not report a regular archive file: ${reportedPath}`,
|
||||
),
|
||||
);
|
||||
retainedObservation = {
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: {
|
||||
@@ -2135,16 +2227,94 @@ export class AdbProvider {
|
||||
adb_reported_path: reportedPath,
|
||||
digest_status: "unknown",
|
||||
},
|
||||
});
|
||||
return err(cause);
|
||||
};
|
||||
try {
|
||||
publishedPath = await publishBugreport(reportedPath, directory.value);
|
||||
} catch (cause) {
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
`The reported bugreport archive could not be published: ${reportedPath}`,
|
||||
{ cause, partialObservation: retainedObservation },
|
||||
),
|
||||
);
|
||||
}
|
||||
retainedObservation = {
|
||||
...retainedObservation,
|
||||
result: { ...retainedObservation.result, local_path: publishedPath },
|
||||
};
|
||||
const digest = await hashAdbFile(publishedPath, operation, signal);
|
||||
const report = {
|
||||
client,
|
||||
serial: input.serial,
|
||||
local_path: publishedPath,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
adb_reported_path: reportedPath,
|
||||
};
|
||||
retainedObservation = {
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: report,
|
||||
};
|
||||
return ok(
|
||||
createAnalysisExecution(report, provider, {
|
||||
limitations: [
|
||||
"The archive is device-generated: dumpstate, dumpsys, and logcat content is the device's own report",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisCancelledError) {
|
||||
if (retainedObservation !== undefined)
|
||||
cause.retainPartialObservation(retainedObservation);
|
||||
return err(cause);
|
||||
}
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
`The reported bugreport archive could not be read back: ${reportedPath ?? stagingDirectory}`,
|
||||
{ cause, partialObservation: retainedObservation },
|
||||
),
|
||||
);
|
||||
}
|
||||
})();
|
||||
// A completed acquisition becomes caller evidence even if publication fails.
|
||||
// Its staging directory must not enter automatic cleanup or cleanup retries.
|
||||
if (retainedObservation !== undefined && publishedPath === undefined)
|
||||
return collectedResult;
|
||||
try {
|
||||
await removeOwnedOutputDirectory(stagingDirectory, stagingIdentity);
|
||||
} catch (cause) {
|
||||
const primary = collectedResult.ok
|
||||
? new AnalysisOutputError(
|
||||
operation,
|
||||
"The archive was published, but its staging directory could not be removed",
|
||||
)
|
||||
: collectedResult.error;
|
||||
if (retainedObservation !== undefined)
|
||||
primary.retainPartialObservation(retainedObservation);
|
||||
this.#pendingOutputDirectoryCleanup.add({
|
||||
operation,
|
||||
path: stagingDirectory,
|
||||
identity: stagingIdentity,
|
||||
primary,
|
||||
remove: () =>
|
||||
removeOwnedOutputDirectory(stagingDirectory, stagingIdentity),
|
||||
});
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
analysisErrorWithCleanupFailure(
|
||||
primary,
|
||||
new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[stagingDirectory],
|
||||
{ reason: cause instanceof Error ? cause.message : String(cause) },
|
||||
{ operation, cause },
|
||||
),
|
||||
operation,
|
||||
`The reported bugreport archive could not be read back: ${reportedPath}`,
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
return collectedResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseAmStartOutput } from "./AdbShellOutput.js";
|
||||
|
||||
const starting =
|
||||
"Starting: Intent { act=android.intent.action.MAIN cmp=com.example/.Main }";
|
||||
|
||||
describe("parseAmStartOutput", () => {
|
||||
it("recognizes a CRLF wait-timeout report", () => {
|
||||
expect(
|
||||
parseAmStartOutput(
|
||||
`${starting}\r\nStatus: timeout\r\nActivity: com.example/.Main\r\nComplete\r\n`,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "refused",
|
||||
activity: "com.example/.Main",
|
||||
reportedStatus: "timeout",
|
||||
reason: "am start reported status: timeout",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats every non-ok status as refusal, including a later status after ok", () => {
|
||||
expect(
|
||||
parseAmStartOutput(`${starting}\nStatus: ok\nStatus: timeout\n`),
|
||||
).toMatchObject({
|
||||
status: "refused",
|
||||
reportedStatus: "timeout",
|
||||
reason: "am start reported status: timeout",
|
||||
});
|
||||
expect(
|
||||
parseAmStartOutput(`${starting}\nStatus: future-value\n`),
|
||||
).toMatchObject({
|
||||
status: "refused",
|
||||
reportedStatus: "future-value",
|
||||
});
|
||||
});
|
||||
|
||||
it("gives hard errors in either stream priority over status and attempt", () => {
|
||||
expect(
|
||||
parseAmStartOutput(
|
||||
`${starting}\nStatus: timeout\nActivity: com.example/.Main\n`,
|
||||
"Exception: Activity class does not exist\n",
|
||||
),
|
||||
).toEqual({
|
||||
status: "refused",
|
||||
startedActivity: "act=android.intent.action.MAIN cmp=com.example/.Main",
|
||||
activity: "com.example/.Main",
|
||||
reportedStatus: "timeout",
|
||||
reason: "Activity class does not exist",
|
||||
});
|
||||
expect(
|
||||
parseAmStartOutput(
|
||||
`${starting}\nStatus: ok\nError: Activity class does not exist\n`,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "refused",
|
||||
reason: "Activity class does not exist",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps Starting-only output compatible and refuses no-attempt output", () => {
|
||||
expect(parseAmStartOutput(starting)).toMatchObject({
|
||||
status: "started",
|
||||
reportedStatus: null,
|
||||
activity: null,
|
||||
});
|
||||
expect(
|
||||
parseAmStartOutput("Status: ok\nWarning: Activity not started\n"),
|
||||
).toMatchObject({
|
||||
status: "refused",
|
||||
startedActivity: null,
|
||||
reportedStatus: "ok",
|
||||
});
|
||||
});
|
||||
});
|
||||
+63
-15
@@ -320,32 +320,80 @@ export const parseResolveActivityOutput = (stdout: string): string | null => {
|
||||
return lines.length === 0 ? null : lines[lines.length - 1]!;
|
||||
};
|
||||
|
||||
/** Parsed facts and verdict from the full `am start -W` report. */
|
||||
export interface AmStartOutput {
|
||||
readonly status: "started" | "refused";
|
||||
readonly startedActivity: string | null;
|
||||
readonly activity: string | null;
|
||||
readonly reportedStatus: string | null;
|
||||
readonly reason: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `am start` output. Success prints `Starting: Intent { ... }`;
|
||||
* refusals print lines starting with `Error:` or `Warning:` and activity
|
||||
* classes that do not exist name the component.
|
||||
* Parse the complete `am start -W` report. `Starting:` records an attempt;
|
||||
* hard errors and any non-ok Activity Manager status determine the verdict.
|
||||
*/
|
||||
export const parseAmStartOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
readonly status: "started" | "refused";
|
||||
readonly startedActivity: string | null;
|
||||
readonly reason: string | null;
|
||||
} => {
|
||||
const text = stdout.trim();
|
||||
const starting = /^Starting:\s+Intent\s*\{(.*)\}\s*$/mu.exec(text);
|
||||
if (starting !== null)
|
||||
stderr = "",
|
||||
): AmStartOutput => {
|
||||
const normalizedStdout = stdout.replaceAll("\r\n", "\n");
|
||||
const starting = /^Starting:[ \t]+Intent[ \t]*\{(.*)\}[ \t]*$/mu.exec(
|
||||
normalizedStdout,
|
||||
);
|
||||
const startedActivity = starting?.[1]?.trim() ?? null;
|
||||
const activityMatch = /^Activity:[ \t]*(.*)$/mu.exec(normalizedStdout);
|
||||
const activity = activityMatch?.[1]?.trim() || null;
|
||||
const statuses = [...normalizedStdout.matchAll(/^Status:[ \t]*(.*)$/gmu)].map(
|
||||
(match) => match[1]!.trim(),
|
||||
);
|
||||
const nonOkStatus = statuses.find((status) => status.toLowerCase() !== "ok");
|
||||
const reportedStatus = nonOkStatus ?? statuses[0] ?? null;
|
||||
const error = [normalizedStdout, stderr.replaceAll("\r\n", "\n")]
|
||||
.flatMap((stream) => stream.split("\n"))
|
||||
.map((line) => line.trim())
|
||||
.map((line) => ({
|
||||
line,
|
||||
match: /^(?:Error|Exception)(?::|\b)(.*)$/iu.exec(line),
|
||||
}))
|
||||
.find(({ match }) => match !== null);
|
||||
const errorReason = error?.match?.[1]?.trim() || error?.line || null;
|
||||
const statusReason =
|
||||
nonOkStatus === ""
|
||||
? "am start reported an empty status"
|
||||
: nonOkStatus === undefined
|
||||
? null
|
||||
: `am start reported status: ${nonOkStatus}`;
|
||||
const reason =
|
||||
errorReason ??
|
||||
statusReason ??
|
||||
(/^Warning:/mu.test(normalizedStdout.trim())
|
||||
? normalizedStdout.trim().slice(0, 512)
|
||||
: null);
|
||||
if (errorReason !== null || nonOkStatus !== undefined)
|
||||
return {
|
||||
status: "refused",
|
||||
startedActivity,
|
||||
activity,
|
||||
reportedStatus,
|
||||
reason: reason ?? "am start did not report a successful launch",
|
||||
};
|
||||
if (startedActivity !== null)
|
||||
return {
|
||||
status: "started",
|
||||
startedActivity: starting[1]!.trim(),
|
||||
startedActivity,
|
||||
activity,
|
||||
reportedStatus,
|
||||
reason: null,
|
||||
};
|
||||
const error = /^(?:Error|Warning|Exception)(?::|\b)(.*)$/mu.exec(text);
|
||||
const text = `${normalizedStdout}\n${stderr.replaceAll("\r\n", "\n")}`.trim();
|
||||
return {
|
||||
status: "refused",
|
||||
startedActivity: null,
|
||||
startedActivity,
|
||||
activity,
|
||||
reportedStatus,
|
||||
reason:
|
||||
error?.[1]?.trim() ??
|
||||
reason ??
|
||||
(text === "" ? "am start returned no activity" : text.slice(0, 512)),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
parseXmlPropertyList,
|
||||
} from "../domain/propertyListKeys.js";
|
||||
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
|
||||
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Decoded representation bound for one binary Info.plist. */
|
||||
@@ -195,11 +196,10 @@ const resolveLayoutExecutable = async (
|
||||
|
||||
let name: string;
|
||||
try {
|
||||
name =
|
||||
plist.subarray(0, 6).toString("ascii") === "bplist"
|
||||
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
|
||||
parseBinaryPlistExecutable(plist))
|
||||
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
|
||||
name = hasBinaryPlistSignature(plist)
|
||||
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
|
||||
parseBinaryPlistExecutable(plist))
|
||||
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
|
||||
@@ -30,7 +30,8 @@ import {
|
||||
rawBinarySelectionError,
|
||||
} from "../domain/rawBinary.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
|
||||
import { observeMzWindowsHeader } from "../domain/dosMz.js";
|
||||
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
isZipPackageFormat,
|
||||
@@ -330,8 +331,7 @@ const detectArtifactFormat = async (
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
// Binary plists, including keyed archives, often use other extensions.
|
||||
if (magic.length >= 8 && magic.subarray(0, 8).equals(Buffer.from("bplist00")))
|
||||
return "plist";
|
||||
if (hasBinaryPlistSignature(magic)) return "plist";
|
||||
const named = namedArtifactFormat(lower);
|
||||
if (named !== undefined) return named;
|
||||
if (
|
||||
@@ -443,11 +443,31 @@ const readExecutableMetadata = async (
|
||||
const fileSize = (await handle.stat()).size;
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
|
||||
const offset = mzWindowsHeaderOffset(bytes);
|
||||
if (offset !== null) {
|
||||
if (offset < 64)
|
||||
let windowsHeader = observeMzWindowsHeader(bytes, fileSize);
|
||||
let signatureBytes: Buffer | undefined;
|
||||
if (windowsHeader.state === "signature-needed") {
|
||||
const { offset } = windowsHeader;
|
||||
const signature = Buffer.alloc(Math.min(4, fileSize - offset));
|
||||
const observedSignature = await handle.read(
|
||||
signature,
|
||||
0,
|
||||
signature.length,
|
||||
offset,
|
||||
);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
signatureBytes = signature.subarray(0, observedSignature.bytesRead);
|
||||
windowsHeader = observeMzWindowsHeader(bytes, fileSize, signatureBytes);
|
||||
}
|
||||
if (windowsHeader.state === "declared") {
|
||||
if (windowsHeader.offset < 64)
|
||||
return err("invalid Windows new-header offset in MZ image");
|
||||
return readPeMetadata(handle, offset, signal);
|
||||
return readPeMetadata(
|
||||
handle,
|
||||
windowsHeader.offset,
|
||||
bytes,
|
||||
fileSize,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
// MZ relocation records may extend past the initial probe; their format
|
||||
// bounds are at most 65535 records inside a 65535-paragraph header.
|
||||
@@ -470,7 +490,12 @@ const readExecutableMetadata = async (
|
||||
fileSize,
|
||||
);
|
||||
}
|
||||
return parseExecutableHeader(bytes, hostArchitecture, fileSize);
|
||||
return parseExecutableHeader(
|
||||
bytes,
|
||||
hostArchitecture,
|
||||
fileSize,
|
||||
signatureBytes,
|
||||
);
|
||||
}
|
||||
if (bytes.length >= 8) {
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
@@ -521,6 +546,8 @@ const readExecutableMetadata = async (
|
||||
const readPeMetadata = async (
|
||||
handle: FileHandle,
|
||||
offset: number,
|
||||
mzPrefix: Buffer,
|
||||
fileSize: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
@@ -534,9 +561,15 @@ const readPeMetadata = async (
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (fileHeaderRead.bytesRead !== fileHeader.length)
|
||||
return err("invalid or truncated PE header");
|
||||
const signature = fileHeader.toString("ascii", 0, 2);
|
||||
if (["NE", "LE", "LX"].includes(signature))
|
||||
return err(`unsupported ${signature} executable in MZ image`);
|
||||
const windowsHeader = observeMzWindowsHeader(
|
||||
mzPrefix,
|
||||
fileSize,
|
||||
fileHeader.subarray(0, 4),
|
||||
);
|
||||
if (windowsHeader.state !== "declared")
|
||||
return err("invalid Windows new-header signature in MZ image");
|
||||
if (["NE", "LE", "LX"].includes(windowsHeader.signature))
|
||||
return err(`unsupported ${windowsHeader.signature} executable in MZ image`);
|
||||
const optionalHeaderSize = fileHeader.readUInt16LE(20);
|
||||
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
|
||||
const record = Buffer.alloc(24 + optionalHeaderSize);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
|
||||
import type {
|
||||
OptionalProviderLoadFailures,
|
||||
OptionalProviderLoadFailure,
|
||||
@@ -42,6 +43,8 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly packetCaptureEnabled?: boolean;
|
||||
readonly signalRecordingEnabled?: boolean;
|
||||
readonly wasmArtifactEnabled?: boolean;
|
||||
readonly evmInterfaceEnabled?: boolean;
|
||||
readonly processCaptureEnabled: boolean;
|
||||
@@ -341,6 +344,15 @@ const workflowAvailabilityFor = ({
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
if (name === "inspect_go_binary")
|
||||
return { reason: "available", remediation: null };
|
||||
if (name === "inspect_sqlite_database") {
|
||||
const capability = sqliteDatabaseCapability(process.versions.node);
|
||||
return capability.available
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_unavailable",
|
||||
remediation: capability.reason,
|
||||
};
|
||||
}
|
||||
if (name === "trace_web_module_imports")
|
||||
return {
|
||||
reason: "available",
|
||||
@@ -385,6 +397,22 @@ const workflowAvailabilityFor = ({
|
||||
remediation:
|
||||
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
|
||||
};
|
||||
if (name === "inspect_packet_capture")
|
||||
return policy.packetCaptureEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
|
||||
};
|
||||
if (name === "decode_signal_recording")
|
||||
return policy.signalRecordingEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"On Linux, supply sigrok-cli 0.7.2 via absolute REA_SIGROK_COMMAND and util-linux prlimit (REA_SIGROK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
|
||||
};
|
||||
if (name === "inspect_wasm_artifact")
|
||||
return policy.wasmArtifactEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
@@ -453,6 +481,8 @@ 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")
|
||||
return { reason: "available", remediation: null };
|
||||
const electron = electronProviderAvailability(name, kind, policy);
|
||||
if (electron !== null) return electron;
|
||||
if (kind === "runtime-provider")
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseClientConfiguration } from "./ClientConfigurationDocument.js";
|
||||
|
||||
describe("parseClientConfiguration shape diagnostics", () => {
|
||||
it.each([
|
||||
["null", "null"],
|
||||
["array", "[]"],
|
||||
["string", '"x"'],
|
||||
] as const)("names a non-object JSON root (%s)", (_label, text) => {
|
||||
expect(() => parseClientConfiguration(text, "json")).toThrow(
|
||||
new TypeError("The configuration root must be an object"),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["null", "null"],
|
||||
["array", "[]"],
|
||||
["string", '"x"'],
|
||||
] as const)(
|
||||
'names a non-object "mcpServers" value (%s)',
|
||||
(_label, servers) => {
|
||||
expect(() =>
|
||||
parseClientConfiguration(`{"mcpServers":${servers},"keep":1}`, "json"),
|
||||
).toThrow(new TypeError('"mcpServers" must be an object'));
|
||||
},
|
||||
);
|
||||
|
||||
it("still rejects unparsable JSON with SyntaxError", () => {
|
||||
expect(() => parseClientConfiguration("not-json", "json")).toThrow(
|
||||
SyntaxError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,7 @@ export const clientConfigurationServersKey = (
|
||||
case "hermes":
|
||||
return "mcp_servers";
|
||||
case "opencode":
|
||||
case "zcode":
|
||||
return "mcp";
|
||||
case "vscode":
|
||||
return "servers";
|
||||
@@ -106,16 +107,21 @@ const parseDocument = (
|
||||
format: ClientConfigurationFormat,
|
||||
): Record<string, unknown> => {
|
||||
if (format === "toml" || format === "grok")
|
||||
return objectSchema.parse(parseToml(text));
|
||||
return requireObject(parseToml(text), "The configuration root");
|
||||
// Pi loads `mcp.json` with a strict `JSON.parse` and no BOM tolerance, so
|
||||
// comments, trailing commas, a BOM, or an empty existing file must be
|
||||
// rejected instead of registering into a document Pi cannot load.
|
||||
if (format === "pi") return objectSchema.parse(JSON.parse(text));
|
||||
if (format === "pi")
|
||||
return requireObject(JSON.parse(text), "The configuration root");
|
||||
// An empty file, which some clients create before any server is added,
|
||||
// holds no settings to preserve.
|
||||
if (isEmptyClientConfigurationText(text)) return {};
|
||||
// Hermes stores MCP servers in `mcp_servers` inside a YAML document.
|
||||
if (format === "hermes") return objectSchema.parse(parseYaml(text));
|
||||
if (format === "hermes")
|
||||
return requireObject(parseYaml(text), "The configuration root");
|
||||
// ZCode loads nonempty native files with strict JSON.parse.
|
||||
if (format === "zcode")
|
||||
return requireObject(JSON.parse(text), "The configuration root");
|
||||
const errors: ParseError[] = [];
|
||||
// Accept a UTF-8 BOM without shifting diagnostics or editing the original text.
|
||||
const jsonText = text.startsWith("\uFEFF") ? ` ${text.slice(1)}` : text;
|
||||
@@ -125,12 +131,13 @@ const parseDocument = (
|
||||
throw new SyntaxError(
|
||||
`Invalid JSON/JSONC at offset ${firstError.offset}: ${printParseErrorCode(firstError.error)}`,
|
||||
);
|
||||
return objectSchema.parse(document);
|
||||
return requireObject(document, "The configuration root");
|
||||
};
|
||||
|
||||
/** A parsed configuration whose structure, not its syntax, cannot hold MCP servers. */
|
||||
export class ClientConfigurationShapeError extends TypeError {}
|
||||
|
||||
/** Validate and copy own properties, excluding non-record YAML values and parser-injected prototypes. */
|
||||
const requireObject = (
|
||||
value: unknown,
|
||||
description: string,
|
||||
@@ -142,6 +149,23 @@ const requireObject = (
|
||||
});
|
||||
};
|
||||
|
||||
/** ZCode reads the same-scope fallback as strict JSON with a mcpServers table. */
|
||||
export const parseZcodeFallbackConfiguration = (
|
||||
text: string,
|
||||
): ClientConfigurationDocument => {
|
||||
const document = requireObject(JSON.parse(text), "ZCode fallback root");
|
||||
return {
|
||||
document,
|
||||
servers:
|
||||
document.mcpServers === undefined
|
||||
? {}
|
||||
: requireObject(document.mcpServers, "ZCode fallback mcpServers"),
|
||||
serversPath: ["mcpServers"],
|
||||
dialect: "json",
|
||||
legacyServers: {},
|
||||
};
|
||||
};
|
||||
|
||||
/** Members of OpenCode V2's `mcp` object that are not server names. */
|
||||
const OPENCODE_V2_MCP_SETTINGS = new Set(["servers", "timeout"]);
|
||||
|
||||
@@ -154,21 +178,26 @@ export const parseClientConfiguration = (
|
||||
throw new TypeError("client does not have a supported MCP config format");
|
||||
// DeepSeek Harness stores a Cordis patch list, not a server table.
|
||||
if (format === "dsh") return parseDshCordisDocument(text);
|
||||
let document: Record<string, unknown>;
|
||||
try {
|
||||
document = parseDocument(text, format);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof z.ZodError)
|
||||
throw new ClientConfigurationShapeError(
|
||||
"The configuration root must be an object",
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
const document = parseDocument(text, format);
|
||||
const serversKey = clientConfigurationServersKey(format);
|
||||
const value = document[serversKey];
|
||||
const servers =
|
||||
value === undefined ? {} : requireObject(value, `"${serversKey}"`);
|
||||
// ZCode reads stdio servers from the nested `mcp.servers` table of
|
||||
// `~/.zcode/cli/config.json`; entries carry `command`, `args`, and `env`.
|
||||
if (format === "zcode") {
|
||||
const nested = servers.servers;
|
||||
return {
|
||||
document,
|
||||
servers:
|
||||
nested === undefined
|
||||
? {}
|
||||
: requireObject(nested, `"${serversKey}.servers"`),
|
||||
serversPath: [serversKey, "servers"],
|
||||
dialect: format,
|
||||
legacyServers: {},
|
||||
};
|
||||
}
|
||||
const native = servers.servers;
|
||||
// A V1 server named `servers` has a string `type` discriminator; the V2
|
||||
// table may instead hold a server object named `type`.
|
||||
@@ -228,8 +257,16 @@ export const withClientServers = (
|
||||
: editDshDocument(parsed);
|
||||
const [key = "", nested] = parsed.serversPath;
|
||||
if (nested === undefined) return { ...parsed.document, [key]: servers };
|
||||
const outer = { ...objectSchema.parse(parsed.document[key]) };
|
||||
if (removeLegacy !== undefined && !OPENCODE_V2_MCP_SETTINGS.has(removeLegacy))
|
||||
// A fresh document may not hold the outer table yet (for example a new
|
||||
// ZCode `config.json` without an `mcp` object), so treat absence as empty.
|
||||
const outerValue = parsed.document[key];
|
||||
const outer =
|
||||
outerValue === undefined ? {} : { ...objectSchema.parse(outerValue) };
|
||||
if (
|
||||
parsed.dialect === "opencode_v2" &&
|
||||
removeLegacy !== undefined &&
|
||||
!OPENCODE_V2_MCP_SETTINGS.has(removeLegacy)
|
||||
)
|
||||
delete outer[removeLegacy];
|
||||
return { ...parsed.document, [key]: { ...outer, [nested]: servers } };
|
||||
};
|
||||
|
||||
@@ -226,7 +226,9 @@ const registrationAligned = (
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false && !forcedEnabled)
|
||||
(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))
|
||||
|
||||
@@ -4,6 +4,9 @@ import { createServerIdentity } from "../serverIdentity.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
|
||||
import { providerCapabilitySet } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { providerCapabilitySets } from "./binary/BinarySessionStatus.js";
|
||||
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
|
||||
|
||||
/** Read target-free provider status and operation availability. */
|
||||
export const runSessionStatus = async (
|
||||
@@ -17,8 +20,15 @@ export const runSessionStatus = async (
|
||||
if (!config.ok) return { error: projectAnalysisError(config.error) };
|
||||
const session = await dependencies.createBinarySession(config.value, logger);
|
||||
try {
|
||||
const status = jsonObjectSchema.parse(session.status());
|
||||
return {
|
||||
...jsonObjectSchema.parse(session.status()),
|
||||
...status,
|
||||
capabilities: [
|
||||
...providerCapabilitySet.array().parse(status.capabilities),
|
||||
...providerCapabilitySets([
|
||||
sqliteDatabaseCapability(process.versions.node),
|
||||
]),
|
||||
],
|
||||
server_identity: createServerIdentity({
|
||||
startedAt: new Date().toISOString(),
|
||||
}),
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
parseFunctionDossier,
|
||||
parseListCount,
|
||||
parseRelatedAddresses,
|
||||
parseSegmentImageBase,
|
||||
parseSegments,
|
||||
} from "../domain/hopperValues.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -527,6 +528,7 @@ export class EnhancedTools {
|
||||
|
||||
const segments = parseSegments(segmentsResult.value);
|
||||
if (!segments.ok) return segments;
|
||||
const imageBase = parseSegmentImageBase(segmentsResult.value);
|
||||
const procedureCount = parseListCount(proceduresResult.value, "procedures");
|
||||
if (!procedureCount.ok) return procedureCount;
|
||||
const stringCount = parseListCount(stringsResult.value, "strings");
|
||||
@@ -543,6 +545,7 @@ export class EnhancedTools {
|
||||
segment_count: segments.value.length,
|
||||
procedure_count: procedureCount.value,
|
||||
string_count: stringCount.value,
|
||||
...(imageBase === undefined ? {} : { image_base: imageBase }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import {
|
||||
createImmutableEvidenceBundle,
|
||||
describeEvidenceBundleFailure,
|
||||
describeValidationFailure,
|
||||
parseImmutableEvidenceBundle,
|
||||
parseEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
@@ -49,15 +49,7 @@ export const readImmutableEvidenceBundle = (
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
|
||||
readBundle(
|
||||
path,
|
||||
(input) => {
|
||||
const bundle = parseEvidenceBundle(input);
|
||||
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
|
||||
},
|
||||
signal,
|
||||
resources,
|
||||
);
|
||||
readBundle(path, parseImmutableEvidenceBundle, signal, resources);
|
||||
|
||||
const readBundle = async (
|
||||
path: string,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
MipsAbiFlags,
|
||||
MipsElfMetadata,
|
||||
} from "../domain/binaryTargetTypes.js";
|
||||
import { readElfFixedHeader } from "../domain/elfFixedHeader.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readMipsElfSharedLoad,
|
||||
@@ -64,21 +65,22 @@ export const readMipsElfMetadata = async (
|
||||
const header = await read(0, 52, "ELF32 header");
|
||||
if (!header.ok) return header;
|
||||
const bytes = header.value;
|
||||
const fixedHeader = readElfFixedHeader(bytes, fileSize);
|
||||
if (!fixedHeader.ok) return fixedHeader;
|
||||
const little = metadata.byteOrder === "little";
|
||||
const u16 = (data: Buffer, offset: number): number =>
|
||||
little ? data.readUInt16LE(offset) : data.readUInt16BE(offset);
|
||||
const u32 = (data: Buffer, offset: number): number =>
|
||||
little ? data.readUInt32LE(offset) : data.readUInt32BE(offset);
|
||||
if (
|
||||
bytes.toString("hex", 0, 4) !== "7f454c46" ||
|
||||
bytes[4] !== 1 ||
|
||||
bytes[5] !== (little ? 1 : 2) ||
|
||||
fixedHeader.value.elfClass !== 32 ||
|
||||
fixedHeader.value.byteOrder !== metadata.byteOrder ||
|
||||
u16(bytes, 18) !== 8 ||
|
||||
u16(bytes, 16) !== metadata.type ||
|
||||
u32(bytes, 36) !== metadata.flags
|
||||
)
|
||||
return err("MIPS ELF header no longer matches the resolved identity");
|
||||
if (bytes[6] !== 1 || u32(bytes, 20) !== 1 || u16(bytes, 40) !== 52)
|
||||
if (fixedHeader.value.headerSize !== 52)
|
||||
return err("invalid MIPS ELF32 version or header size");
|
||||
|
||||
const tables = [
|
||||
|
||||
@@ -109,12 +109,18 @@ const resolveInternalSpecifier = (
|
||||
: { to: match, resolution: "internal" };
|
||||
};
|
||||
|
||||
type ReadFile = Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>;
|
||||
|
||||
const appendFile = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>,
|
||||
entry: ReadFile,
|
||||
lookupPath: ReferenceSourcePathLookup,
|
||||
output: ParsedReferenceSourceEntries,
|
||||
): void => {
|
||||
const language = detectReferenceSourceLanguage(entry.path);
|
||||
const parsed =
|
||||
language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language)
|
||||
? undefined
|
||||
: parseReferenceSourceImports(entry.path, entry.bytes, language);
|
||||
output.entries.push({
|
||||
path: entry.path,
|
||||
kind: "file",
|
||||
@@ -123,11 +129,9 @@ const appendFile = (
|
||||
language,
|
||||
classifications: classifyReferenceSourcePath(entry.path),
|
||||
content_state: "hashed",
|
||||
limitations: [],
|
||||
limitations: [...(parsed?.limitations ?? [])],
|
||||
});
|
||||
if (language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
|
||||
return;
|
||||
const parsed = parseReferenceSourceImports(entry.path, entry.bytes, language);
|
||||
if (parsed === undefined) return;
|
||||
for (const relationship of parsed.relationships) {
|
||||
if (relationship.resolution !== "internal") {
|
||||
output.relationships.push(relationship);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
@@ -32,18 +32,24 @@ export const readReferenceSourceVcs = async (
|
||||
): Promise<Result<ReferenceSourceVcsInfo, ReferenceSourceReaderError>> => {
|
||||
try {
|
||||
return await resources.run(async () => {
|
||||
if (isAborted(signal)) return ok(unknownVcs());
|
||||
try {
|
||||
await lstat(join(root, ".git"));
|
||||
} catch (cause: unknown) {
|
||||
return ok(
|
||||
errorCode(cause) === "ENOENT"
|
||||
? { kind: "none", head: null, dirty: null }
|
||||
: unknownVcs(),
|
||||
);
|
||||
// Like Git, a subdirectory belongs to its nearest enclosing repository;
|
||||
// only a missing `.git` at every ancestor means no version control.
|
||||
let repository = resolve(root);
|
||||
for (;;) {
|
||||
if (isAborted(signal)) return ok(unknownVcs());
|
||||
try {
|
||||
await lstat(join(repository, ".git"));
|
||||
break;
|
||||
} catch (cause: unknown) {
|
||||
if (errorCode(cause) !== "ENOENT") return ok(unknownVcs());
|
||||
}
|
||||
const parent = dirname(repository);
|
||||
if (parent === repository)
|
||||
return ok({ kind: "none", head: null, dirty: null });
|
||||
repository = parent;
|
||||
}
|
||||
try {
|
||||
const head = await resolveSourceHead(root, resources, signal);
|
||||
const head = await resolveSourceHead(repository, resources, signal);
|
||||
if (isAborted(signal)) return ok(unknownVcs());
|
||||
return ok({ kind: "git", head, dirty: null });
|
||||
} catch (cause: unknown) {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
|
||||
import { readClientConfigurationFiles } from "./ClientConfigurationFiles.js";
|
||||
import {
|
||||
readClientConfigurationFiles,
|
||||
readConfigurationText,
|
||||
} from "./ClientConfigurationFiles.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
clientRegistrationEntry,
|
||||
clientConfigurationValuesEqual,
|
||||
@@ -8,6 +12,7 @@ import {
|
||||
legacyClientServerPath,
|
||||
OMP_DISABLED_SERVERS_KEY,
|
||||
parseClientConfiguration,
|
||||
parseZcodeFallbackConfiguration,
|
||||
serializeClientConfiguration,
|
||||
withClientServers,
|
||||
type ClientConfigurationDocument,
|
||||
@@ -120,12 +125,15 @@ const configureClientDocument = async (
|
||||
void cause;
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = clientConfigurationDesired(
|
||||
client,
|
||||
environment,
|
||||
command,
|
||||
parsed,
|
||||
);
|
||||
const fallback = await readZcodeFallbackServers(client, parsed);
|
||||
if (!fallback.ok) {
|
||||
throwCleanupFailure(fallback.error);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = clientConfigurationDesired(client, environment, command, {
|
||||
...parsed,
|
||||
servers: { ...fallback.value, ...parsed.servers },
|
||||
});
|
||||
if (registrationCurrent(parsed, desired)) return { status: "unchanged" };
|
||||
return persistClientConfiguration({
|
||||
client,
|
||||
@@ -134,6 +142,7 @@ const configureClientDocument = async (
|
||||
original,
|
||||
parsed,
|
||||
desired,
|
||||
fallbackServers: fallback.value,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -144,6 +153,7 @@ interface ClientConfigurationUpdate {
|
||||
readonly original: string | undefined;
|
||||
readonly parsed: ClientConfigurationDocument;
|
||||
readonly desired: unknown;
|
||||
readonly fallbackServers: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const persistClientConfiguration = async ({
|
||||
@@ -153,6 +163,7 @@ const persistClientConfiguration = async ({
|
||||
original,
|
||||
parsed,
|
||||
desired,
|
||||
fallbackServers,
|
||||
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
@@ -169,7 +180,11 @@ const persistClientConfiguration = async ({
|
||||
);
|
||||
const registered = withClientServers(
|
||||
parsed,
|
||||
{ ...parsed.servers, [PRODUCT_IDENTITY.mcpServerKey]: desired },
|
||||
{
|
||||
...fallbackServers,
|
||||
...parsed.servers,
|
||||
[PRODUCT_IDENTITY.mcpServerKey]: desired,
|
||||
},
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
);
|
||||
// OMP's denylist would hide the registration; keep every other listed name.
|
||||
@@ -194,6 +209,9 @@ const persistClientConfiguration = async ({
|
||||
await writeFileAtomic(
|
||||
transactionPath,
|
||||
serializeClientConfiguration(document, format, original, [
|
||||
...Object.keys(fallbackServers)
|
||||
.filter((name) => name !== PRODUCT_IDENTITY.mcpServerKey)
|
||||
.map((name) => clientServerPath(parsed, name)),
|
||||
clientServerPath(parsed, PRODUCT_IDENTITY.mcpServerKey),
|
||||
...(legacyPath === undefined ? [] : [legacyPath]),
|
||||
...(enableOmp ? [[OMP_DISABLED_SERVERS_KEY]] : []),
|
||||
@@ -213,7 +231,14 @@ const persistClientConfiguration = async ({
|
||||
await readRegularFileText(transactionPath),
|
||||
format,
|
||||
);
|
||||
if (!registrationCurrent(readback, desired)) {
|
||||
if (
|
||||
!registrationCurrent(readback, desired) ||
|
||||
Object.entries(fallbackServers).some(
|
||||
([name, entry]) =>
|
||||
name !== PRODUCT_IDENTITY.mcpServerKey &&
|
||||
!clientConfigurationValuesEqual(readback.servers[name], entry),
|
||||
)
|
||||
) {
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
@@ -329,7 +354,14 @@ export const inspectClientConfiguration = async (
|
||||
original = await readRegularFileText(transactionPath);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (isMissing(cause)) return { status: "create" };
|
||||
if (isMissing(cause)) {
|
||||
const fallback = await readZcodeFallbackServers(client);
|
||||
if (!fallback.ok) {
|
||||
throwCleanupFailure(fallback.error);
|
||||
return { status: "invalid", remediation: fallback.error.detail };
|
||||
}
|
||||
return { status: "create" };
|
||||
}
|
||||
return {
|
||||
status: "invalid",
|
||||
remediation: `The configuration file could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
@@ -359,6 +391,11 @@ export const inspectClientConfiguration = async (
|
||||
);
|
||||
if (registrationCurrent(parsed, desired))
|
||||
return { status: "already_current" };
|
||||
const fallback = await readZcodeFallbackServers(client, parsed);
|
||||
if (!fallback.ok) {
|
||||
throwCleanupFailure(fallback.error);
|
||||
return { status: "invalid", remediation: fallback.error.detail };
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
// Malformed configuration is reported with the invalid remediation.
|
||||
@@ -382,6 +419,48 @@ const throwCleanupFailure = (error: ClientConfigurationFileError): void => {
|
||||
if (error.cleanupFailure !== undefined) throw error.cleanupFailure;
|
||||
};
|
||||
|
||||
/** Admit the fallback only when the first native ZCode server would suppress it. */
|
||||
const readZcodeFallbackServers = async (
|
||||
client: SetupClient,
|
||||
parsed?: ClientConfigurationDocument,
|
||||
): Promise<
|
||||
Result<Readonly<Record<string, unknown>>, ClientConfigurationFileError>
|
||||
> => {
|
||||
if (
|
||||
client.format !== "zcode" ||
|
||||
(parsed !== undefined && Object.keys(parsed.servers).length > 0)
|
||||
)
|
||||
return ok({});
|
||||
const path = client.zcodeFallbackPath;
|
||||
const detail = `The ZCode fallback configuration ${path ?? "path"} is unresolved, malformed or unreadable. Repair it before rerunning setup: the first native server would suppress that fallback.`;
|
||||
if (path === undefined)
|
||||
return err({ kind: "unreadable", path: client.configPath, detail });
|
||||
const transactionPath = await resolveClientConfigTransactionPath(path);
|
||||
if (transactionPath === undefined)
|
||||
return err({ kind: "unreadable", path, detail });
|
||||
const source = await readConfigurationText(transactionPath);
|
||||
if (!source.ok)
|
||||
return err({ ...source.error, detail: `${detail} ${source.error.detail}` });
|
||||
if (source.value === undefined) return ok({});
|
||||
try {
|
||||
const parsed = parseZcodeFallbackConfiguration(source.value);
|
||||
const environment = clientRegistrationEnvironment(parsed);
|
||||
if (!environment.ok)
|
||||
return err({
|
||||
kind: "malformed",
|
||||
path,
|
||||
detail: `${detail} ${environment.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`,
|
||||
});
|
||||
return ok(parsed.servers);
|
||||
} catch (cause: unknown) {
|
||||
return err({
|
||||
kind: "malformed",
|
||||
path,
|
||||
detail: `${detail} ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const preserveConfigBackup = async (
|
||||
source: string,
|
||||
destination: string,
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface SetupClient {
|
||||
};
|
||||
/** Unresolved path evidence only; consumers must not perform I/O on it. */
|
||||
readonly configPathError?: string;
|
||||
/** Same-scope fallback ZCode stops loading after its first native server. */
|
||||
readonly zcodeFallbackPath?: string;
|
||||
readonly markerPath?: string;
|
||||
readonly format?:
|
||||
| "json"
|
||||
@@ -38,6 +40,7 @@ export interface SetupClient {
|
||||
| "omp"
|
||||
| "pi"
|
||||
| "hermes"
|
||||
| "zcode"
|
||||
| "dsh"
|
||||
| "unsupported";
|
||||
}
|
||||
@@ -64,6 +67,7 @@ interface ClientDefinition {
|
||||
readonly configPath: ClientPath;
|
||||
readonly markerPath: ClientPath;
|
||||
readonly format: NonNullable<SetupClient["format"]>;
|
||||
readonly zcodeFallbackPath?: (context: ClientPathContext) => string;
|
||||
readonly skillPath?: ClientPath;
|
||||
readonly configPaths?: (context: ClientPathContext) => readonly string[];
|
||||
readonly geminiSettings?: (
|
||||
@@ -71,6 +75,10 @@ interface ClientDefinition {
|
||||
) => NonNullable<SetupClient["geminiSettings"]>;
|
||||
}
|
||||
|
||||
/** XDG treats an empty config-home value as unset. */
|
||||
const xdgConfigHome = ({ home, env }: ClientPathContext): string =>
|
||||
env.XDG_CONFIG_HOME || join(home, ".config");
|
||||
|
||||
const vscodeUserDirectory = ({
|
||||
home,
|
||||
platform,
|
||||
@@ -84,7 +92,23 @@ const vscodeUserDirectory = ({
|
||||
);
|
||||
if (platform === "darwin")
|
||||
return join(home, "Library", "Application Support", "Code", "User");
|
||||
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Code", "User");
|
||||
return join(xdgConfigHome({ home, platform, env }), "Code", "User");
|
||||
};
|
||||
|
||||
const traeUserDirectory = ({
|
||||
home,
|
||||
platform,
|
||||
env,
|
||||
}: ClientPathContext): string => {
|
||||
if (platform === "win32")
|
||||
return join(
|
||||
env.APPDATA ?? join(home, "AppData", "Roaming"),
|
||||
"Trae",
|
||||
"User",
|
||||
);
|
||||
if (platform === "darwin")
|
||||
return join(home, "Library", "Application Support", "Trae", "User");
|
||||
return join(xdgConfigHome({ home, platform, env }), "Trae", "User");
|
||||
};
|
||||
|
||||
const claudeDesktopDirectory = ({
|
||||
@@ -95,7 +119,7 @@ const claudeDesktopDirectory = ({
|
||||
if (platform === "win32")
|
||||
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
|
||||
if (platform === "linux")
|
||||
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Claude");
|
||||
return join(xdgConfigHome({ home, platform, env }), "Claude");
|
||||
return join(home, "Library", "Application Support", "Claude");
|
||||
};
|
||||
|
||||
@@ -108,6 +132,9 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
const codexDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CODEX_HOME || join(home, ".codex");
|
||||
|
||||
const qoderDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.QODER_CONFIG_DIR || join(home, ".qoder");
|
||||
|
||||
/** Match Qwen Code's home override, including tilde and cwd-relative paths. */
|
||||
const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
|
||||
const override = env.QWEN_HOME;
|
||||
@@ -245,19 +272,13 @@ const openCodeOverrideDirectory = (
|
||||
|
||||
const opencodeDirectory = (context: ClientPathContext): string =>
|
||||
openCodeOverrideDirectory(context.env) ??
|
||||
join(
|
||||
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
|
||||
"opencode",
|
||||
);
|
||||
join(xdgConfigHome(context), "opencode");
|
||||
|
||||
/** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */
|
||||
const openCodeConfigurationPaths = (
|
||||
context: ClientPathContext,
|
||||
): readonly string[] => {
|
||||
const directory = join(
|
||||
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
|
||||
"opencode",
|
||||
);
|
||||
const directory = join(xdgConfigHome(context), "opencode");
|
||||
const overrideDirectory = openCodeOverrideDirectory(context.env);
|
||||
const paths = [
|
||||
join(directory, "config.json"),
|
||||
@@ -460,6 +481,15 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
markerPath: vscodeUserDirectory,
|
||||
format: "vscode",
|
||||
},
|
||||
{
|
||||
name: "trae",
|
||||
displayName: "Trae",
|
||||
skillPath: [".trae", "skills"],
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(traeUserDirectory(context), "mcp.json"),
|
||||
markerPath: traeUserDirectory,
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "grok_build",
|
||||
displayName: "Grok Build",
|
||||
@@ -499,6 +529,26 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
markerPath: hermesDirectory,
|
||||
format: "hermes",
|
||||
},
|
||||
{
|
||||
name: "qoder",
|
||||
displayName: "Qoder",
|
||||
skillPath: (context: ClientPathContext) =>
|
||||
join(qoderDirectory(context), "skills"),
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(qoderDirectory(context), "settings.json"),
|
||||
markerPath: qoderDirectory,
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "zcode",
|
||||
zcodeFallbackPath: ({ home }: ClientPathContext) =>
|
||||
join(home, ".agents", "mcp.json"),
|
||||
displayName: "ZCode",
|
||||
configPath: [".zcode", "cli", "config.json"],
|
||||
markerPath: [".zcode", "cli"],
|
||||
skillPath: [".zcode", "skills"],
|
||||
format: "zcode",
|
||||
},
|
||||
{
|
||||
name: "dsh",
|
||||
displayName: "DeepSeek Harness",
|
||||
@@ -590,6 +640,9 @@ export const supportedClients = (
|
||||
...new Set([...definition.configPaths(context), configPath]),
|
||||
],
|
||||
}),
|
||||
...(definition.zcodeFallbackPath === undefined
|
||||
? {}
|
||||
: { zcodeFallbackPath: definition.zcodeFallbackPath(context) }),
|
||||
markerPath: marker.value,
|
||||
format: definition.format,
|
||||
};
|
||||
|
||||
@@ -289,7 +289,7 @@ const readClientConfiguration = async (
|
||||
"failed",
|
||||
cause instanceof ClientConfigurationShapeError
|
||||
? `Configuration was not changed: ${cause.message}. Repair it, then rerun uninstall.`
|
||||
: `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
: `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : client.format === "hermes" || client.format === "dsh" ? "YAML" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,6 +102,38 @@ export interface AnalysisViewRetention {
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
/** Fail before analysis when selected delivery cannot keep its complete source. */
|
||||
export const requireAnalysisViewRetention = (
|
||||
operation: string,
|
||||
retention: AnalysisViewRetention,
|
||||
): Result<
|
||||
{
|
||||
readonly evidenceById: EvidenceLookup;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"];
|
||||
},
|
||||
AnalysisError
|
||||
> => {
|
||||
if (
|
||||
retention.recordEvidence === undefined ||
|
||||
retention.evidenceById === undefined
|
||||
)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
ANALYSIS_VIEW_PROVIDER.id,
|
||||
operation,
|
||||
"summary detail requires a server session that retains Evidence for later views",
|
||||
{
|
||||
userMessage:
|
||||
"This server does not retain Evidence. Select detail complete to receive the complete analysis inline.",
|
||||
},
|
||||
),
|
||||
);
|
||||
return ok({
|
||||
evidenceById: retention.evidenceById,
|
||||
recordEvidence: retention.recordEvidence,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retain complete analysis Evidence in the session, then project its summary
|
||||
* view from the retained record. Callers page or select the rest through
|
||||
@@ -111,29 +143,16 @@ export const summarizeRetainedAnalysis = (
|
||||
evidence: Evidence,
|
||||
retention: AnalysisViewRetention,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
if (
|
||||
retention.recordEvidence === undefined ||
|
||||
retention.evidenceById === undefined
|
||||
)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
ANALYSIS_VIEW_PROVIDER.id,
|
||||
evidence.operation,
|
||||
"summary detail requires a server session that retains Evidence for later views",
|
||||
{
|
||||
userMessage:
|
||||
"This server does not retain Evidence. Select detail complete to receive the complete analysis inline.",
|
||||
},
|
||||
),
|
||||
);
|
||||
const recorded = retention.recordEvidence(evidence);
|
||||
const ready = requireAnalysisViewRetention(evidence.operation, retention);
|
||||
if (!ready.ok) return ready;
|
||||
const recorded = ready.value.recordEvidence(evidence);
|
||||
if (!recorded.ok) return recorded;
|
||||
return inspectAnalysisViewValidated(
|
||||
{
|
||||
source: { kind: "retained-evidence", evidence_id: evidence.evidence_id },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
retention.evidenceById,
|
||||
ready.value.evidenceById,
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ import type {
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import type {
|
||||
UnknownPage,
|
||||
UnknownQuery,
|
||||
} from "../investigation/InvestigationRecordPort.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -350,6 +354,10 @@ export abstract class BinarySessionRecords {
|
||||
return this.#records.listUnknowns(filters);
|
||||
}
|
||||
|
||||
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
|
||||
return this.#records.listUnknownsPage(query);
|
||||
}
|
||||
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
|
||||
@@ -198,15 +198,19 @@ type CapabilityAvailabilityCode = Exclude<
|
||||
CapabilityDescriptor["availabilityCode"],
|
||||
undefined
|
||||
>;
|
||||
type CapabilityProjection = Omit<CapabilityDescriptor, "available" | "reason"> &
|
||||
(
|
||||
// Wire capability projection also covers target-free operations outside binary routing.
|
||||
type CapabilityProjection = Omit<
|
||||
CapabilityDescriptor,
|
||||
"operation" | "available" | "reason"
|
||||
> & { readonly operation: string } & (
|
||||
| { readonly available: true; readonly reason: null }
|
||||
| { readonly available: false; readonly reason: string }
|
||||
);
|
||||
type ProviderCapabilityGroup = ProviderCapabilitySet["groups"][number];
|
||||
|
||||
/** Group inline capability facts without merging distinct providers or states. */
|
||||
const providerCapabilitySets = (
|
||||
/** Project provider descriptors once for binary and target-free status consumers. */
|
||||
export const providerCapabilitySets = (
|
||||
descriptors: readonly CapabilityProjection[],
|
||||
): ProviderCapabilitySet[] => {
|
||||
const providers = new Map<
|
||||
|
||||
@@ -10,6 +10,11 @@ import type { ProviderIdentity } from "../AnalysisProvider.js";
|
||||
/** Replaceable offline binary-layout provider; owns its parser and process protocol. */
|
||||
export interface BinaryLayoutPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
inspectAndClose(
|
||||
input: InspectBinaryLayoutInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<BinaryLayout, AnalysisError>>;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectBinaryLayoutInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -17,6 +17,9 @@ it.each([
|
||||
"rejects malformed selection before starting the provider: %j",
|
||||
async (input) => {
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -32,6 +35,9 @@ it.each([
|
||||
it("records the decoded layout once in its Evidence", async () => {
|
||||
const layout = binaryLayoutFixture();
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(layout)),
|
||||
});
|
||||
@@ -49,6 +55,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
"ELF core belongs to recorded-crash analysis.",
|
||||
);
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(err(failure)),
|
||||
});
|
||||
@@ -58,6 +67,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
it("cancels before invocation and after an acquired observation", async () => {
|
||||
const controller = new AbortController();
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
controller.abort();
|
||||
@@ -77,6 +89,9 @@ it("cancels before invocation and after an acquired observation", async () => {
|
||||
},
|
||||
});
|
||||
const untouched = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -112,6 +127,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
|
||||
permissions: { read: true, write: false, execute: true },
|
||||
});
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
|
||||
@@ -21,10 +21,36 @@ const OPERATION = "inspect_binary_layout";
|
||||
export class BinaryLayoutService {
|
||||
constructor(readonly provider: BinaryLayoutPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspect(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
|
||||
inspectAndClose(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspectAndClose(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions | undefined,
|
||||
inspect: (
|
||||
input: Parameters<BinaryLayoutPort["inspect"]>[0],
|
||||
) => ReturnType<BinaryLayoutPort["inspect"]>,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
@@ -45,7 +71,7 @@ export class BinaryLayoutService {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
const inspected = await inspect(input.data);
|
||||
if (!inspected.ok) return inspected;
|
||||
const diagnostics = binaryLayoutSchema.shape.diagnostics.safeParse(
|
||||
inspected.value.diagnostics,
|
||||
|
||||
@@ -12,6 +12,11 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Replaceable decoder of supplied recordings; historical PID is never live authority. */
|
||||
export interface RecordedCrashPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
inspectAndClose(
|
||||
input: InspectRecordedCrashInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<RecordedCrash, AnalysisError>>;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectRecordedCrashInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -13,6 +13,9 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
|
||||
const fixture = recordedCrashFixture();
|
||||
fixture.debugger = recordedCrashDebuggerFixture();
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
@@ -36,6 +39,9 @@ it.each([
|
||||
"rejects malformed selection before starting the provider: %j",
|
||||
async (input) => {
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -55,6 +61,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
"ELF core belongs to recorded-crash analysis.",
|
||||
);
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(err(failure)),
|
||||
});
|
||||
@@ -64,6 +73,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
it("cancels before invocation and after an acquired observation", async () => {
|
||||
const controller = new AbortController();
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
controller.abort();
|
||||
@@ -83,6 +95,9 @@ it("cancels before invocation and after an acquired observation", async () => {
|
||||
},
|
||||
});
|
||||
const untouched = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -117,6 +132,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
|
||||
flags: "0x5",
|
||||
});
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
|
||||
@@ -21,10 +21,36 @@ const OPERATION = "inspect_recorded_crash";
|
||||
export class RecordedCrashService {
|
||||
constructor(readonly provider: RecordedCrashPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspect(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
|
||||
inspectAndClose(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspectAndClose(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions | undefined,
|
||||
inspect: (
|
||||
input: Parameters<RecordedCrashPort["inspect"]>[0],
|
||||
) => ReturnType<RecordedCrashPort["inspect"]>,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
@@ -45,7 +71,7 @@ export class RecordedCrashService {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
const inspected = await inspect(input.data);
|
||||
if (!inspected.ok) return inspected;
|
||||
const diagnostics = recordedCrashSchema.shape.diagnostics.safeParse(
|
||||
inspected.value.diagnostics,
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import {
|
||||
inspectPacketCaptureInputSchema,
|
||||
packetCaptureSchema,
|
||||
type InspectPacketCaptureInput,
|
||||
} from "../../domain/captures/packetCapture.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
export interface PacketCapturePort {
|
||||
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
|
||||
inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** One shared validation and Evidence owner for CLI and MCP. */
|
||||
export class PacketCaptureService {
|
||||
constructor(readonly provider: PacketCapturePort) {}
|
||||
close(): Promise<void> {
|
||||
return this.provider.close();
|
||||
}
|
||||
async inspect(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_packet_capture";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectPacketCaptureInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
if (!isAbsolute(input.data.path))
|
||||
return err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute local path.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const decoded = await this.provider.inspect(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = packetCaptureSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256 ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Capture analyzer returned malformed data or changed the selected artifact identity/options.",
|
||||
),
|
||||
);
|
||||
const evidence = createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: input.data,
|
||||
result: report.data,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
});
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
partialObservation: evidence,
|
||||
}),
|
||||
)
|
||||
: ok(evidence);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { FlutterRequest } from "../../domain/flutter/flutterBuildAnalysis.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/**
|
||||
* Flutter build-identification boundary by pure APK parsing.
|
||||
* Implementation details belong to the provider adapter.
|
||||
*/
|
||||
export interface FlutterBuildAnalysisPort {
|
||||
/** Pure parsing; always available. */
|
||||
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
|
||||
/** The provider holds no long-lived resources; safe to call always. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
request: FlutterRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { FlutterBuildAnalysisService } from "./FlutterBuildAnalysisService.js";
|
||||
import type { FlutterBuildAnalysisPort } from "./FlutterBuildAnalysisPort.js";
|
||||
import { createAnalysisExecution } from "../AnalysisProvider.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import { parseEvidence } from "../../domain/evidence.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
|
||||
const identity = {
|
||||
id: "flutter",
|
||||
name: "Flutter build identification",
|
||||
version: null,
|
||||
};
|
||||
|
||||
const execution = createAnalysisExecution(
|
||||
{
|
||||
target: { path: "/targets/app.apk", bytes: 10, sha256: "a".repeat(64) },
|
||||
flutter_detected: true,
|
||||
abis: [],
|
||||
coverage: "complete",
|
||||
},
|
||||
identity,
|
||||
);
|
||||
|
||||
const refusing: FlutterBuildAnalysisPort = {
|
||||
async inspectAvailability() {
|
||||
throw new Error("must not probe");
|
||||
},
|
||||
async close() {},
|
||||
async execute() {
|
||||
throw new Error("must not execute");
|
||||
},
|
||||
};
|
||||
|
||||
const malformedSelections: readonly unknown[] = [
|
||||
{ path: "/targets/app.apk", extra: true },
|
||||
{ path: 7 },
|
||||
{},
|
||||
{ path: "/targets/app.apk", abi: "not a locale" },
|
||||
];
|
||||
it.each(malformedSelections)("refuses %j at admission", async (input) => {
|
||||
const settled = await new FlutterBuildAnalysisService(refusing).execute(
|
||||
"identify_flutter_build",
|
||||
input,
|
||||
);
|
||||
expect(settled.ok).toBe(false);
|
||||
if (settled.ok) return;
|
||||
expect(settled.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
|
||||
it("passes the validated request to the provider and seals Evidence", async () => {
|
||||
const seen: unknown[] = [];
|
||||
const recording: FlutterBuildAnalysisPort = {
|
||||
async inspectAvailability() {
|
||||
return { status: "available", code: null, reason: null, diagnostics: {} };
|
||||
},
|
||||
async close() {},
|
||||
async execute(request) {
|
||||
seen.push(request);
|
||||
return ok(execution);
|
||||
},
|
||||
};
|
||||
const result = await new FlutterBuildAnalysisService(recording).execute(
|
||||
"identify_flutter_build",
|
||||
{ path: "/targets/app.apk" },
|
||||
);
|
||||
expect(seen).toEqual([
|
||||
{
|
||||
operation: "identify_flutter_build",
|
||||
input: { path: "/targets/app.apk" },
|
||||
},
|
||||
]);
|
||||
if (!result.ok) throw new Error(result.error.message);
|
||||
const evidence = parseEvidence(result.value);
|
||||
expect(evidence.provider).toEqual(identity);
|
||||
expect(evidence.confidence).toBe("observed");
|
||||
});
|
||||
|
||||
it("settles an already-aborted call as cancellation before execution", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const settled = await new FlutterBuildAnalysisService(refusing).execute(
|
||||
"identify_flutter_build",
|
||||
{ path: "/targets/app.apk" },
|
||||
{
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
expect(settled.ok).toBe(false);
|
||||
if (settled.ok) return;
|
||||
expect(settled.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { FlutterBuildAnalysisPort } from "./FlutterBuildAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import {
|
||||
flutterRequestSchema,
|
||||
type FlutterOperation,
|
||||
} from "../../domain/flutter/flutterBuildAnalysis.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { executeProviderOperation } from "../ProviderOperationExecution.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP admission, execution, and Evidence composition for Flutter. */
|
||||
export class FlutterBuildAnalysisService {
|
||||
constructor(readonly provider: FlutterBuildAnalysisPort) {}
|
||||
|
||||
/** Run one caller-selected Flutter request and retain target identity inline. */
|
||||
execute(
|
||||
operation: FlutterOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return executeProviderOperation(
|
||||
operation,
|
||||
input,
|
||||
options,
|
||||
flutterRequestSchema,
|
||||
this.provider,
|
||||
"observed",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -986,3 +986,39 @@ it("serializes script loading against concurrent close and unloads the loaded sc
|
||||
expect(bindings.device.session.scripts[0]?.isDestroyed).toBe(true);
|
||||
expect(bindings.device.session.isDetached()).toBe(true);
|
||||
});
|
||||
|
||||
it("names the unknown session or script ID it rejects", async () => {
|
||||
const { manager, started } = await startLocalAttachedSession();
|
||||
if (!started.ok) throw started.error;
|
||||
const missing = "00000000-0000-4000-8000-000000000009";
|
||||
const sessionIssue = {
|
||||
path: ["session_id"],
|
||||
reason: "invalid_value",
|
||||
message: `No open Frida session ${missing}; start one with start_frida_session.`,
|
||||
};
|
||||
for (const result of [
|
||||
await manager.closeSession(missing),
|
||||
await manager.resumeSession(missing),
|
||||
await manager.loadScript(missing, { sourceKind: "inline", source: "" }),
|
||||
await manager.unloadScript(missing, missing),
|
||||
])
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError", issues: [sessionIssue] },
|
||||
});
|
||||
expect(
|
||||
await manager.unloadScript(started.value.sessionId, missing),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
issues: [
|
||||
{
|
||||
path: ["script_id"],
|
||||
reason: "invalid_value",
|
||||
message: `No loaded Frida script ${missing} in this session.`,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await manager.closeAll();
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";
|
||||
@@ -102,6 +105,66 @@ it.each(["startSession", "instrument"] as const)(
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
[join(tmpdir(), "rea-missing-frida-script.js"), "no file exists there"],
|
||||
[tmpdir(), "it is not a regular file"],
|
||||
])(
|
||||
"rejects the unreadable script file %s before starting Frida",
|
||||
async (path, reason) => {
|
||||
let starts = 0;
|
||||
const provider = createProvider({
|
||||
async startSession() {
|
||||
starts += 1;
|
||||
return { ok: true, value: createSession() };
|
||||
},
|
||||
});
|
||||
const service = new FridaInstrumentationService(provider);
|
||||
|
||||
const result = await service.instrument({
|
||||
mode: "spawn",
|
||||
deviceId: "local",
|
||||
program: "/tmp/fixture",
|
||||
source: { sourceKind: "file", path },
|
||||
durationMs: 1,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
expect((result.error as AnalysisInputError).issues).toEqual([
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `Cannot read Frida script file ${path}: ${reason}.`,
|
||||
},
|
||||
]);
|
||||
expect(starts).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports cancellation before checking a file script source", async () => {
|
||||
const service = new FridaInstrumentationService(createProvider());
|
||||
const controller = new AbortController();
|
||||
controller.abort(new Error("cancelled before call"));
|
||||
|
||||
const result = await service.instrument(
|
||||
{
|
||||
mode: "spawn",
|
||||
deviceId: "local",
|
||||
program: "/tmp/fixture",
|
||||
source: {
|
||||
sourceKind: "file",
|
||||
path: join(tmpdir(), "rea-missing-frida-script.js"),
|
||||
},
|
||||
durationMs: 1,
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
});
|
||||
|
||||
it("does not resume a spawned target when cancellation arrives during script loading", async () => {
|
||||
const controller = new AbortController();
|
||||
let resumes = 0;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { constants } from "node:fs";
|
||||
import { access, stat } from "node:fs/promises";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import type {
|
||||
@@ -19,6 +23,64 @@ import type {
|
||||
StartFridaSessionInput,
|
||||
} from "./FridaInstrumentationPort.js";
|
||||
|
||||
const unreadableScriptFile = async (
|
||||
source: FridaScriptSource,
|
||||
): Promise<AnalysisError | undefined> => {
|
||||
if (source.sourceKind !== "file") return undefined;
|
||||
let reason: string;
|
||||
let cause: unknown;
|
||||
try {
|
||||
if (!(await stat(source.path)).isFile())
|
||||
reason = "it is not a regular file";
|
||||
else {
|
||||
await access(source.path, constants.R_OK);
|
||||
return undefined;
|
||||
}
|
||||
} catch (failure: unknown) {
|
||||
cause = failure;
|
||||
const code =
|
||||
failure instanceof Error && "code" in failure ? failure.code : undefined;
|
||||
if (code === "EACCES" || code === "EPERM")
|
||||
return new AnalysisAccessDeniedError(
|
||||
"instrument_with_frida",
|
||||
source.path,
|
||||
code,
|
||||
{ cause },
|
||||
);
|
||||
reason =
|
||||
code === "ENOENT" ? "no file exists there" : String(code ?? failure);
|
||||
}
|
||||
return new AnalysisInputError(
|
||||
"instrument_with_frida",
|
||||
cause === undefined ? undefined : { cause },
|
||||
[
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `Cannot read Frida script file ${source.path}: ${reason}.`,
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reject an unreadable script file before any attach or spawn effect;
|
||||
* cancellation before or during the check still wins.
|
||||
*/
|
||||
const rejectBeforeStart = async (
|
||||
source: FridaScriptSource,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<AnalysisError | undefined> => {
|
||||
const cancelled = () =>
|
||||
new AnalysisCancelledError(
|
||||
"instrument_with_frida",
|
||||
signal?.reason === undefined ? {} : { cause: signal.reason },
|
||||
);
|
||||
if (signal?.aborted) return cancelled();
|
||||
const unreadable = await unreadableScriptFile(source);
|
||||
return signal?.aborted ? cancelled() : unreadable;
|
||||
};
|
||||
|
||||
/** Shared CLI/MCP workflows for Frida's device and instrumentation operations. */
|
||||
export class FridaInstrumentationService {
|
||||
readonly #provider: FridaInstrumentationPort;
|
||||
@@ -163,6 +225,8 @@ export class FridaInstrumentationService {
|
||||
AnalysisError
|
||||
>
|
||||
> {
|
||||
const rejected = await rejectBeforeStart(input.source, signal);
|
||||
if (rejected !== undefined) return err(rejected);
|
||||
const started = await this.#startSession(
|
||||
input,
|
||||
signal,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
|
||||
/** A session ID that names no open Frida session owned by this process. */
|
||||
export const unknownFridaSession = (
|
||||
operation: string,
|
||||
sessionId: string,
|
||||
): AnalysisInputError =>
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["session_id"],
|
||||
reason: "invalid_value",
|
||||
message: `No open Frida session ${sessionId}; start one with start_frida_session.`,
|
||||
},
|
||||
]);
|
||||
|
||||
/** A script ID that names no loaded script in the selected session. */
|
||||
export const unknownFridaScript = (
|
||||
operation: string,
|
||||
scriptId: string,
|
||||
): AnalysisInputError =>
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["script_id"],
|
||||
reason: "invalid_value",
|
||||
message: `No loaded Frida script ${scriptId} in this session.`,
|
||||
},
|
||||
]);
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
import type { UnknownPage, UnknownQuery } from "./InvestigationRecordPort.js";
|
||||
|
||||
type EvidenceLedgerFailure = EvidenceIntegrityError;
|
||||
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
|
||||
@@ -326,18 +327,39 @@ export class EvidenceLedger {
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): ResidualUnknown[] {
|
||||
return [...this.#unknownHeads.values()]
|
||||
return this.listUnknownsPage(filters).items;
|
||||
}
|
||||
|
||||
/** Select a stable page of current heads before detaching record payloads. */
|
||||
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
|
||||
const offset = query.offset ?? 0;
|
||||
const matching = [...this.#unknownHeads.values()]
|
||||
.filter(
|
||||
(unknown) =>
|
||||
(filters.status === undefined || unknown.status === filters.status) &&
|
||||
(filters.severity === undefined ||
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
(query.status === undefined || unknown.status === query.status) &&
|
||||
(query.severity === undefined ||
|
||||
unknown.severity === query.severity) &&
|
||||
(query.domain === undefined || unknown.domain === query.domain),
|
||||
)
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
|
||||
)
|
||||
.map((unknown) => structuredClone(unknown));
|
||||
);
|
||||
const start = Math.min(offset, matching.length);
|
||||
const end =
|
||||
query.limit === undefined
|
||||
? undefined
|
||||
: start + Math.min(query.limit, matching.length - start);
|
||||
const page = matching.slice(start, end);
|
||||
const nextOffset =
|
||||
offset <= matching.length && start + page.length < matching.length
|
||||
? start + page.length
|
||||
: null;
|
||||
return {
|
||||
items: page.map((unknown) => structuredClone(unknown)),
|
||||
total: matching.length,
|
||||
offset,
|
||||
next_offset: nextOffset,
|
||||
};
|
||||
}
|
||||
|
||||
/** Return current resolution validity; imported invalid states are rejected. */
|
||||
|
||||
@@ -38,6 +38,21 @@ export interface EvidenceUnknownWriter {
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
}
|
||||
|
||||
export type UnknownPage = {
|
||||
readonly items: ResidualUnknown[];
|
||||
readonly total: number;
|
||||
readonly offset: number;
|
||||
readonly next_offset: number | null;
|
||||
};
|
||||
|
||||
export interface UnknownQuery {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
readonly offset?: number;
|
||||
readonly limit?: number;
|
||||
}
|
||||
|
||||
/** Optimistic Unknown revisions and consistency verification. */
|
||||
export interface UnknownRegistryPort {
|
||||
recordUnknown(
|
||||
@@ -51,6 +66,7 @@ export interface UnknownRegistryPort {
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
listUnknownsPage(query?: UnknownQuery): UnknownPage;
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
|
||||
@@ -19,6 +19,8 @@ import type {
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
UnknownRegistryPort,
|
||||
UnknownPage,
|
||||
UnknownQuery,
|
||||
} from "./InvestigationRecordPort.js";
|
||||
|
||||
/** One investigation's validated record owner, independent of binary execution. */
|
||||
@@ -124,6 +126,10 @@ export class InvestigationRecords
|
||||
return this.#evidence.listUnknowns(filters);
|
||||
}
|
||||
|
||||
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
|
||||
return this.#evidence.listUnknownsPage(query);
|
||||
}
|
||||
|
||||
/** Verify registry consistency without asserting the answer is true. */
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
|
||||
import type { ProviderIdentity } from "../AnalysisProvider.js";
|
||||
import type { CanonicalElectronActiveObservationInput } from "./ElectronActiveObservationPort.js";
|
||||
import type { Evidence, EvidenceObservation } from "../../domain/evidence.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import type {
|
||||
ElectronActiveObservationInput,
|
||||
ElectronActiveObservationResult,
|
||||
} from "../../domain/javascript/electronActiveObservation.js";
|
||||
import type { ElectronActiveObservationResult } from "../../domain/javascript/electronActiveObservation.js";
|
||||
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
|
||||
type CanonicalElectronActiveObservationInput =
|
||||
ElectronActiveObservationInput & {
|
||||
readonly application_root: string;
|
||||
};
|
||||
|
||||
/** Commit the selected Electron experiment and its observed result. */
|
||||
export const createElectronActiveEvidence = (
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
|
||||
@@ -9,11 +9,15 @@ import type {
|
||||
} from "../../domain/javascript/electronActiveObservation.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Caller selections resolved once before entering the runtime adapter. */
|
||||
export type CanonicalElectronActiveObservationInput =
|
||||
ElectronActiveObservationInput & { readonly application_root: string };
|
||||
|
||||
/** Provider-neutral boundary for owned Electron runtime experiments. */
|
||||
export interface ElectronActiveObservationPort {
|
||||
identity(): ProviderIdentity;
|
||||
capture(
|
||||
input: ElectronActiveObservationInput,
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<ElectronActiveObservationResult, AnalysisError>>;
|
||||
}
|
||||
|
||||
@@ -2,57 +2,80 @@ import { dirname } from "node:path";
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { ElectronActiveObservationPort } from "./ElectronActiveObservationPort.js";
|
||||
import type {
|
||||
CanonicalElectronActiveObservationInput,
|
||||
ElectronActiveObservationPort,
|
||||
} from "./ElectronActiveObservationPort.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
type AnalysisInputIssue,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import type { ElectronActiveObservationInput } from "../../domain/javascript/electronActiveObservation.js";
|
||||
import { err, type Result } from "../../domain/result.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
|
||||
|
||||
const OPERATION = "capture_electron_scenario" as const;
|
||||
const PROVIDER_ID = "rea-playwright-electron-active";
|
||||
type CanonicalElectronActiveObservationInput =
|
||||
ElectronActiveObservationInput & {
|
||||
readonly application_root: string;
|
||||
};
|
||||
|
||||
const resolveInputPath = async (
|
||||
field: "executable_path" | "application_path" | "application_root",
|
||||
selected: string,
|
||||
): Promise<
|
||||
Result<
|
||||
string,
|
||||
{ readonly issue: AnalysisInputIssue; readonly cause: unknown }
|
||||
>
|
||||
> => {
|
||||
try {
|
||||
return ok(await realpath(selected));
|
||||
} catch (cause: unknown) {
|
||||
return err({
|
||||
issue: {
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: `Cannot resolve ${field} ${selected}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
},
|
||||
cause,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const canonicalizeInput = async (
|
||||
input: ElectronActiveObservationInput,
|
||||
): Promise<Result<CanonicalElectronActiveObservationInput, AnalysisError>> => {
|
||||
try {
|
||||
const [executablePath, applicationPath] = await Promise.all([
|
||||
realpath(input.executable_path),
|
||||
realpath(input.application_path),
|
||||
]);
|
||||
const applicationRoot =
|
||||
input.application_root === undefined
|
||||
? dirname(applicationPath)
|
||||
: await realpath(input.application_root);
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
...input,
|
||||
executable_path: executablePath,
|
||||
application_path: applicationPath,
|
||||
application_root: applicationRoot,
|
||||
},
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
const [executable, application, root] = await Promise.all([
|
||||
resolveInputPath("executable_path", input.executable_path),
|
||||
resolveInputPath("application_path", input.application_path),
|
||||
input.application_root === undefined
|
||||
? Promise.resolve(ok(undefined))
|
||||
: resolveInputPath("application_root", input.application_root),
|
||||
]);
|
||||
if (!executable.ok || !application.ok || !root.ok) {
|
||||
const failures = [executable, application, root].flatMap((result) =>
|
||||
result.ok ? [] : [result.error],
|
||||
);
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, { cause }, [
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
{
|
||||
path: ["application_path"],
|
||||
reason: "invalid_format",
|
||||
message:
|
||||
"Electron executable, application, and root must resolve to existing paths",
|
||||
cause: new AggregateError(
|
||||
failures.map(({ cause }) => cause),
|
||||
"Electron paths could not be resolved",
|
||||
),
|
||||
},
|
||||
]),
|
||||
failures.map(({ issue }) => issue),
|
||||
),
|
||||
);
|
||||
}
|
||||
return ok({
|
||||
...input,
|
||||
executable_path: executable.value,
|
||||
application_path: application.value,
|
||||
application_root: root.value ?? dirname(application.value),
|
||||
});
|
||||
};
|
||||
|
||||
/** Canonicalize request paths and execute one provider-owned Electron run. */
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
@@ -380,7 +382,10 @@ function* analyzeArtifactFileSteps<
|
||||
yield;
|
||||
const semantics =
|
||||
analysis.parse_status === "complete" || analysis.parse_status === "partial"
|
||||
? yield* analyzeParsedJavaScriptSemanticsSteps(parsed)
|
||||
? yield* analyzeParsedJavaScriptSemanticsSteps(
|
||||
parsed,
|
||||
moduleKindForJavaScriptReference(file.path, "static-import"),
|
||||
)
|
||||
: null;
|
||||
const projected =
|
||||
semantics === null
|
||||
|
||||
@@ -376,10 +376,14 @@ const resolveReference = (
|
||||
): ResolvedReference | null => {
|
||||
const specifier = reference.specifier;
|
||||
if (specifier === null) return null;
|
||||
const chunk = resolveBundlerChunkReference(context, sourcePath, reference);
|
||||
const isWorker =
|
||||
reference.kind === "worker" || reference.kind === "service-worker";
|
||||
const chunk = isWorker
|
||||
? null
|
||||
: resolveBundlerChunkReference(context, sourcePath, reference);
|
||||
if (chunk !== null) return chunk;
|
||||
const module =
|
||||
reference.module_runtime === undefined
|
||||
isWorker || reference.module_runtime === undefined
|
||||
? undefined
|
||||
: context.moduleNodes.get(
|
||||
moduleLookupKey(sourcePath, reference.module_runtime, specifier),
|
||||
@@ -391,24 +395,23 @@ const resolveReference = (
|
||||
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
|
||||
}
|
||||
// Worker scripts are URLs relative to the script, not module specifiers.
|
||||
const path =
|
||||
reference.kind === "worker" || reference.kind === "service-worker"
|
||||
? resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
sourcePath,
|
||||
context: "url-reference",
|
||||
files: context.filesByPath,
|
||||
}).resolved_path
|
||||
: resolveArtifactPath(
|
||||
specifier,
|
||||
sourcePath,
|
||||
context.filesByPath,
|
||||
reference.kind === "require" ||
|
||||
reference.kind === "static-import" ||
|
||||
reference.kind === "dynamic-import"
|
||||
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
|
||||
: undefined,
|
||||
);
|
||||
const path = isWorker
|
||||
? resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
sourcePath,
|
||||
context: "url-reference",
|
||||
files: context.filesByPath,
|
||||
}).resolved_path
|
||||
: resolveArtifactPath(
|
||||
specifier,
|
||||
sourcePath,
|
||||
context.filesByPath,
|
||||
reference.kind === "require" ||
|
||||
reference.kind === "static-import" ||
|
||||
reference.kind === "dynamic-import"
|
||||
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
|
||||
: undefined,
|
||||
);
|
||||
if (path === null) return null;
|
||||
const file = context.filesByPath.get(path);
|
||||
const node = context.fileNodes.get(path);
|
||||
|
||||
@@ -509,17 +509,6 @@ describe("contextual JavaScript artifact path resolution", () => {
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "renderer/local.js",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "file:///assets/app.js#entry",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "assets/app.js",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["node:fs", "electron", "../../escape.js", "%2e%2e/escape.js"])(
|
||||
@@ -576,24 +565,52 @@ describe("contextual JavaScript artifact path resolution", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommonJS file URL resolution", () => {
|
||||
it("keeps file URL resolution specific to the import loader", () => {
|
||||
const files = fileMap([file("entry.cjs", "root"), file("dep.cjs", "root")]);
|
||||
const input = {
|
||||
declaredPath: "file:///dep.cjs",
|
||||
sourcePath: "entry.cjs",
|
||||
context: "module-specifier" as const,
|
||||
files,
|
||||
};
|
||||
describe("JavaScript file URL resolution", () => {
|
||||
it("resolves file URL paths without interpreting query bytes as path syntax", () => {
|
||||
const files = fileMap([file("assets/app.js", "root")]);
|
||||
for (const declaredPath of [
|
||||
"file:///assets/app.js#entry",
|
||||
"FILE:///assets/app.js?token=%2F#entry",
|
||||
]) {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
declared_path: declaredPath,
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "assets/app.js",
|
||||
});
|
||||
}
|
||||
|
||||
expect(resolve({ ...input, moduleKind: "require" })).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(resolve({ ...input, moduleKind: "import" })).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "dep.cjs",
|
||||
});
|
||||
for (const declaredPath of [
|
||||
"file:///assets%2Fapp.js",
|
||||
"file:///assets%2\nFapp.js",
|
||||
]) {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
|
||||
}
|
||||
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "file:/assets/app.js",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolution_status: "external", resolved_path: null });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2000,15 +2017,143 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("url-reference directory and empty-segment semantics", () => {
|
||||
it.each([
|
||||
"./worker.js/.",
|
||||
"./worker.js/child/..",
|
||||
"./worker.js/",
|
||||
"/dist/worker.js/.",
|
||||
"./worker.js/.?cache=1#entry",
|
||||
])("keeps directory-form URLs distinct from files: %s", (declaredPath) => {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.mjs",
|
||||
context: "url-reference",
|
||||
files: fileMap([file("dist/worker.js", "root")]),
|
||||
}),
|
||||
).toMatchObject({
|
||||
declared_path: declaredPath,
|
||||
resolution_status: "not-found",
|
||||
resolved_path: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["./nested//worker.js", "./nested//../worker.js"])(
|
||||
"does not collapse empty URL path segments: %s",
|
||||
(declaredPath) => {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.mjs",
|
||||
context: "url-reference",
|
||||
files: fileMap([
|
||||
file("dist/worker.js", "root"),
|
||||
file("dist/nested/worker.js", "root"),
|
||||
]),
|
||||
}),
|
||||
).toMatchObject({ resolved_path: null });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["./nested/.././worker.js?cache=1#entry", "dist/worker.js"],
|
||||
["./.worker.js", "dist/.worker.js"],
|
||||
])("resolves exact file URLs with dots: %s", (declaredPath, resolvedPath) => {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.mjs",
|
||||
context: "url-reference",
|
||||
files: fileMap([file(resolvedPath, "root")]),
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: resolvedPath,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("url-reference JavaScript artifact path resolution", () => {
|
||||
it.each([
|
||||
["C|?cache=1#entry", "dist/C|"],
|
||||
["/c:/worker.js", "c:/worker.js"],
|
||||
["/./c|/worker.js", "c|/worker.js"],
|
||||
["../c|/worker.js", "c|/worker.js"],
|
||||
["/nested/../c|/worker.js", "c|/worker.js"],
|
||||
["c|/../worker.js", "dist/worker.js"],
|
||||
])("leaves drive-letter URL paths unresolved: %s", (declaredPath, decoy) => {
|
||||
const resolution = resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.mjs",
|
||||
context: "url-reference",
|
||||
files: fileMap([file(decoy, "root")]),
|
||||
});
|
||||
expect(resolution).toMatchObject({
|
||||
declared_path: declaredPath,
|
||||
resolution_status: "unavailable",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(resolution.limitations.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["./c|/worker.js", "dist/c|/worker.js"],
|
||||
["c|name/worker.js", "dist/c|name/worker.js"],
|
||||
["/%63|/worker.js", "c|/worker.js"],
|
||||
["/c%3A/worker.js", "c:/worker.js"],
|
||||
])(
|
||||
"retains non-drive URL path identities: %s",
|
||||
(declaredPath, resolvedPath) => {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.mjs",
|
||||
context: "url-reference",
|
||||
files: fileMap([file(resolvedPath, "root")]),
|
||||
}),
|
||||
).toMatchObject({
|
||||
declared_path: declaredPath,
|
||||
resolution_status: "resolved",
|
||||
resolved_path: resolvedPath,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["?value=", "#value="])(
|
||||
"admits the pathname independently of its %s suffix",
|
||||
(suffix) => {
|
||||
for (const value of ["%2F", "%2E", "%5C", "%00", "%FF", "\\", "\0"]) {
|
||||
const declaredPath = `./worker.js${suffix}${value}`;
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath,
|
||||
sourcePath: "dist/app.js",
|
||||
context: "url-reference",
|
||||
files: fileMap([file("dist/worker.js", "root")]),
|
||||
}),
|
||||
declaredPath,
|
||||
).toMatchObject({
|
||||
declared_path: declaredPath,
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "dist/worker.js",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"app\0.js.map?valid=1",
|
||||
"nested\\worker.js#valid",
|
||||
"app%00.js.map",
|
||||
"app%FF.js.map",
|
||||
"app%C0%AF.js.map",
|
||||
"app%2ejs.map",
|
||||
"nested%2fworker.js",
|
||||
"nested%5cworker.js",
|
||||
"h\nttp://[",
|
||||
"../../outside.js.map",
|
||||
"../../outside/.",
|
||||
])("rejects an inadmissible URL path: %s", (declaredPath) => {
|
||||
const resolution = resolve({
|
||||
declaredPath,
|
||||
|
||||
@@ -68,12 +68,20 @@ export interface ResolveArtifactPathInput {
|
||||
export const moduleKindForJavaScriptReference = (
|
||||
sourcePath: string,
|
||||
referenceKind: "static-import" | "dynamic-import" | "require",
|
||||
resolutionMode?: "import" | "require",
|
||||
): "import" | "require" =>
|
||||
referenceKind === "require" ||
|
||||
resolutionMode ??
|
||||
(referenceKind === "require" ||
|
||||
(referenceKind === "static-import" &&
|
||||
posix.extname(sourcePath).toLowerCase() === ".cts")
|
||||
? "require"
|
||||
: "import";
|
||||
: "import");
|
||||
|
||||
/** Preserve an explicitly retained loader mode on graph relationships. */
|
||||
export const moduleResolutionModeProperties = (
|
||||
mode: "import" | "require" | undefined,
|
||||
): Readonly<Record<string, "import" | "require">> =>
|
||||
mode === undefined ? {} : { resolution_mode: mode };
|
||||
|
||||
const EXTENSIONS = [
|
||||
".js",
|
||||
@@ -145,17 +153,15 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
input.declaredPath.startsWith("#")
|
||||
)
|
||||
return resolvePackageImportAlias(input, input.declaredPath);
|
||||
const rejected = rejectDeclaration(input.declaredPath);
|
||||
if (rejected !== null) return rejected;
|
||||
const candidate = contextualCandidate(input);
|
||||
if (typeof candidate !== "string") return candidate;
|
||||
const confined = confineCandidate(candidate);
|
||||
if (typeof confined !== "string") return confined;
|
||||
if (input.context === "html-reference")
|
||||
if (input.context === "html-reference" || input.context === "url-reference")
|
||||
return (
|
||||
resolveFileCandidates(input, [confined]) ??
|
||||
unresolvedCandidate("not-found", [
|
||||
`The exact HTML resource ${confined} was not found among the selected application files.`,
|
||||
`The exact ${input.context === "html-reference" ? "HTML" : "URL"} resource ${confined} was not found among the selected application files.`,
|
||||
])
|
||||
);
|
||||
const isModuleUrlPath =
|
||||
@@ -193,19 +199,32 @@ const contextualCandidate = (
|
||||
input: ResolveArtifactPathInput,
|
||||
): string | CandidateResolution => {
|
||||
const { context } = input;
|
||||
// URL suffixes are evidence, not pathname bytes. Admit only the path while
|
||||
// retaining the complete declaration on the resolution result.
|
||||
let declared =
|
||||
context === "html-reference" || context === "url-reference"
|
||||
context === "url-reference"
|
||||
? stripQueryAndFragment(input.declaredPath)
|
||||
: input.declaredPath;
|
||||
if (context === "html-reference") return htmlCandidate(input);
|
||||
if (context === "module-specifier") {
|
||||
if (context === "module-specifier" && /^file:/iu.test(declared)) {
|
||||
const fileUrl = fileUrlPath(declared);
|
||||
if (fileUrl === null)
|
||||
return unresolvedCandidate("rejected", [
|
||||
"The file URL path contains syntax that cannot identify a canonical artifact path.",
|
||||
]);
|
||||
if (fileUrl !== undefined)
|
||||
return input.moduleKind === "require"
|
||||
? unresolvedCandidate("external", [
|
||||
"Node CommonJS require specifiers do not resolve file URLs as local artifacts.",
|
||||
])
|
||||
: fileUrl;
|
||||
return unresolvedCandidate("external", [
|
||||
"File URL authorities or invalid file URL forms cannot be mapped to artifact-local paths.",
|
||||
]);
|
||||
}
|
||||
const rejected = rejectDeclaration(declared);
|
||||
if (rejected !== null) return rejected;
|
||||
if (context === "html-reference") return htmlCandidate(input);
|
||||
if (context === "module-specifier") {
|
||||
if (hasScheme(declared))
|
||||
return unresolvedCandidate("external", [
|
||||
"URL and Node builtin schemes are outside static artifact module resolution.",
|
||||
@@ -222,12 +241,39 @@ const contextualCandidate = (
|
||||
"URL schemes and protocol-relative URLs are outside this local artifact path context.",
|
||||
]);
|
||||
if (context === "url-reference") {
|
||||
// A file base gives raw drive-letter segments special meaning, including
|
||||
// after dot segments reach the root. Parse before percent decoding so an
|
||||
// encoded drive-like filename stays literal. The synthetic base establishes
|
||||
// only this ambiguity; it does not establish the source's runtime scheme.
|
||||
const sourceUrlPath = input.sourcePath
|
||||
.split("/")
|
||||
.map(encodeURIComponent)
|
||||
.join("/");
|
||||
const fileReference = URL.parse(declared, `file:///${sourceUrlPath}`);
|
||||
if (fileReference === null)
|
||||
return unresolvedCandidate("rejected", [
|
||||
"The URL reference cannot be parsed as a URL.",
|
||||
]);
|
||||
if (/^\/[A-Za-z]:(?:\/|$)/u.test(fileReference.pathname))
|
||||
return unresolvedCandidate("unavailable", [
|
||||
"Drive-letter URL paths cannot be mapped without the source URL scheme and filesystem root.",
|
||||
]);
|
||||
const decoded = percentDecodeUrlPath(declared);
|
||||
if (decoded === null)
|
||||
return unresolvedCandidate("rejected", [
|
||||
"The URL reference path percent-decodes to NUL or to bytes that are not UTF-8.",
|
||||
]);
|
||||
declared = decoded;
|
||||
// Empty URL segments are significant; canonical filesystem paths cannot
|
||||
// preserve them, including their interaction with following dot segments.
|
||||
if (decoded.includes("//"))
|
||||
return unresolvedCandidate("unavailable", [
|
||||
"Repeated URL path separators cannot be mapped to an exact canonical artifact file.",
|
||||
]);
|
||||
return exactUrlPathCandidate(
|
||||
decoded,
|
||||
relativeCandidate(input.sourcePath, decoded),
|
||||
"URL",
|
||||
);
|
||||
}
|
||||
return relativeCandidate(input.sourcePath, declared);
|
||||
};
|
||||
@@ -681,37 +727,34 @@ const htmlCandidate = (
|
||||
const basePath = decodedBase.startsWith("/")
|
||||
? decodedBase.slice(1)
|
||||
: posix.join(posix.dirname(input.sourcePath), decodedBase);
|
||||
if (declaredPath === "") return emptyHtmlReference(decodedBase, basePath);
|
||||
if (declaredPath === "")
|
||||
return exactUrlPathCandidate(decodedBase, basePath, "HTML");
|
||||
return posix.join(htmlBaseDirectory(decodedBase, basePath), declaredPath);
|
||||
};
|
||||
|
||||
const emptyHtmlReference = (
|
||||
base: string,
|
||||
basePath: string,
|
||||
const exactUrlPathCandidate = (
|
||||
declared: string,
|
||||
candidate: string,
|
||||
kind: "HTML" | "URL",
|
||||
): string | CandidateResolution => {
|
||||
if (!htmlBaseIsDirectory(base)) return basePath;
|
||||
const confined = confineCandidate(basePath);
|
||||
if (!urlPathIsDirectory(declared)) return candidate;
|
||||
const confined = confineCandidate(candidate);
|
||||
if (typeof confined !== "string") return confined;
|
||||
return unresolvedCandidate("not-found", [
|
||||
`The HTML reference resolves to directory ${confined || "."}, not an exact selected application file.`,
|
||||
`The ${kind} reference resolves to directory ${confined || "."}, not an exact selected application file.`,
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* The directory a relative HTML reference resolves against. A base path
|
||||
* ending in "/" or in a "." or ".." segment is already a directory, because a
|
||||
* relative reference resolves against the base URL's directory and those
|
||||
* segments are dropped rather than stepped through.
|
||||
*/
|
||||
const htmlBaseIsDirectory = (base: string): boolean =>
|
||||
base.endsWith("/") ||
|
||||
base.endsWith("/.") ||
|
||||
base.endsWith("/..") ||
|
||||
base === "." ||
|
||||
base === "..";
|
||||
/** Whether a URL path retains directory form after dot-segment normalization. */
|
||||
const urlPathIsDirectory = (path: string): boolean =>
|
||||
path.endsWith("/") ||
|
||||
path.endsWith("/.") ||
|
||||
path.endsWith("/..") ||
|
||||
path === "." ||
|
||||
path === "..";
|
||||
|
||||
const htmlBaseDirectory = (base: string, basePath: string): string =>
|
||||
htmlBaseIsDirectory(base) ? basePath : posix.dirname(basePath);
|
||||
urlPathIsDirectory(base) ? basePath : posix.dirname(basePath);
|
||||
|
||||
const confineCandidate = (candidate: string): string | CandidateResolution => {
|
||||
const normalized = normalizeJoinedLogicalPath(candidate);
|
||||
@@ -854,8 +897,6 @@ const resolveDirectory = (
|
||||
files: input.files,
|
||||
...(input.moduleKind === undefined ? {} : { moduleKind: input.moduleKind }),
|
||||
};
|
||||
const rejected = rejectDeclaration(entryInput.declaredPath);
|
||||
if (rejected !== null) return rejected;
|
||||
const candidate = contextualCandidate(entryInput);
|
||||
if (typeof candidate !== "string") return candidate;
|
||||
const confined = confineCandidate(candidate);
|
||||
@@ -1162,12 +1203,26 @@ const exactPackageTargetNotFound = (
|
||||
],
|
||||
});
|
||||
|
||||
const fileUrlPath = (value: string): string | undefined => {
|
||||
if (!value.startsWith("file://")) return undefined;
|
||||
const fileUrlPath = (value: string): string | null | undefined => {
|
||||
if (!/^file:\/\//iu.test(value)) return undefined;
|
||||
// URL parsing removes tabs and newlines and normalizes encoded dot segments.
|
||||
// Check the raw path first, excluding URL identity suffixes, then check the
|
||||
// parsed pathname so parser normalization cannot introduce a separator.
|
||||
const rawPath = stripQueryAndFragment(value);
|
||||
if (
|
||||
value.includes("\0") ||
|
||||
value.includes("\\") ||
|
||||
/[\t\n\r]/u.test(rawPath) ||
|
||||
!admitsCanonicalPathSyntax(rawPath)
|
||||
)
|
||||
return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "file:" || url.hostname !== "") return undefined;
|
||||
return decodeURIComponent(url.pathname).replace(/^\/+/, "");
|
||||
if (!admitsCanonicalPathSyntax(url.pathname)) return null;
|
||||
const decoded = decodeURIComponent(url.pathname);
|
||||
if (decoded.includes("\0")) return null;
|
||||
return decoded.replace(/^\/+/, "");
|
||||
} catch (cause: unknown) {
|
||||
// Unparseable file URLs have no path to resolve.
|
||||
void cause;
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
moduleKindForJavaScriptReference,
|
||||
moduleResolutionModeProperties,
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
} from "./JavaScriptArtifactPathResolution.js";
|
||||
@@ -281,6 +282,7 @@ const resolveModuleTarget = (
|
||||
input.link.kind === "require" || input.link.kind === "commonjs-export"
|
||||
? "require"
|
||||
: "static-import",
|
||||
input.link.resolutionMode,
|
||||
),
|
||||
});
|
||||
if (resolution.resolution_status !== "resolved")
|
||||
@@ -373,6 +375,7 @@ const relationshipProperties = (
|
||||
origin?: JavaScriptModuleOrigin,
|
||||
) => ({
|
||||
module_link_kind: link.kind,
|
||||
...moduleResolutionModeProperties(link.resolutionMode),
|
||||
specifier: origin?.specifier ?? link.specifier,
|
||||
imported_name: origin?.importedPath.at(-1) ?? link.importedName,
|
||||
imported_path: origin?.importedPath ?? [],
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import {
|
||||
decodeSignalRecordingInputSchema,
|
||||
signalRecordingSchema,
|
||||
type DecodeSignalRecordingInput,
|
||||
} from "../../domain/signals/signalRecording.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
export interface SignalRecordingPort {
|
||||
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
|
||||
decode(
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** One shared validation and Evidence owner for CLI and MCP. */
|
||||
export class SignalRecordingService {
|
||||
constructor(readonly provider: SignalRecordingPort) {}
|
||||
close(): Promise<void> {
|
||||
return this.provider.close();
|
||||
}
|
||||
async decode(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "decode_signal_recording";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = decodeSignalRecordingInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
if (!isAbsolute(input.data.path))
|
||||
return err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute local path.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const decoded = await this.provider.decode(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = signalRecordingSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256 ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Decoder returned malformed data or changed the selected recording identity/options.",
|
||||
),
|
||||
);
|
||||
const evidence = createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: input.data,
|
||||
result: report.data,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
});
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
partialObservation: evidence,
|
||||
}),
|
||||
)
|
||||
: ok(evidence);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { expandProviderCapabilities } from "../../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { providerCapabilitySets } from "../binary/BinarySessionStatus.js";
|
||||
import { sqliteDatabaseCapability } from "./SqliteDatabaseCapability.js";
|
||||
|
||||
it.each([
|
||||
["22.23.1", false],
|
||||
["24.11.0", false],
|
||||
["24.14.9", false],
|
||||
["24.15.0", true],
|
||||
["25.1.0", false],
|
||||
["26.0.0", true],
|
||||
["24.15.0-rc.1", false],
|
||||
["invalid", false],
|
||||
])(
|
||||
"reports SQLite inspection availability on Node %s as %s",
|
||||
(version, available) => {
|
||||
const [capability] = expandProviderCapabilities(
|
||||
providerCapabilitySets([sqliteDatabaseCapability(version)]),
|
||||
);
|
||||
expect(capability).toMatchObject({
|
||||
operation: "inspect_sqlite_database",
|
||||
available,
|
||||
reason: available
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
availability_code: available ? null : "unsupported_version",
|
||||
limitations: [expect.stringContaining("DatabaseSync.limits")],
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,33 @@
|
||||
import { satisfies } from "semver";
|
||||
import { toolContract } from "../../contracts/toolContracts.js";
|
||||
import { SQLITE_PROVIDER_IDENTITY } from "../../domain/sqlite/sqliteDatabase.js";
|
||||
|
||||
const SQLITE_RUNTIME_REQUIREMENT =
|
||||
"SQLite inspection requires Node.js 24.x >=24.15 or 26+ with the native DatabaseSync.limits API. Other REA features retain their published runtime requirements. The inspection worker verifies the API before querying the snapshot.";
|
||||
|
||||
/** Discover inspection readiness without opening a database or starting a worker. */
|
||||
export const sqliteDatabaseCapability = (nodeVersion: string) => {
|
||||
const contract = toolContract("inspect_sqlite_database");
|
||||
const facts = {
|
||||
operation: contract.name,
|
||||
provider: SQLITE_PROVIDER_IDENTITY,
|
||||
effects: {
|
||||
mutatesArtifact: contract.effects.mutatesTarget,
|
||||
launchesProcess: contract.effects.launchesProcess,
|
||||
mayShowUi: contract.effects.changesUiState,
|
||||
mayAccessNetwork: contract.effects.accessesNetwork,
|
||||
mayWriteFilesystem: contract.effects.writesFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limitations: [SQLITE_RUNTIME_REQUIREMENT],
|
||||
};
|
||||
return satisfies(nodeVersion, "^24.15.0 || >=26.0.0")
|
||||
? { ...facts, available: true as const, reason: null }
|
||||
: {
|
||||
...facts,
|
||||
available: false as const,
|
||||
reason: SQLITE_RUNTIME_REQUIREMENT,
|
||||
availabilityCode: "unsupported_version" as const,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { InspectSqliteDatabaseInput } from "../../domain/sqlite/sqliteDatabase.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Offline database inspection boundary shared by CLI and MCP. */
|
||||
export interface SqliteDatabasePort {
|
||||
/** Await and retry provider-owned snapshot cleanup. */
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectSqliteDatabaseInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { SqliteDatabaseService } from "./SqliteDatabaseService.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import { err } from "../../domain/result.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import { createAnalysisExecution } from "../AnalysisProvider.js";
|
||||
|
||||
const fixture = () => ({
|
||||
artifact: { path: "/selected.db", sha256: "a".repeat(64), bytes: 4096 },
|
||||
wal: null,
|
||||
engine: { name: "SQLite", version: "3.50.2" },
|
||||
database_encoding: "UTF-8",
|
||||
schema: {
|
||||
scope: "inventory",
|
||||
completeness: "complete",
|
||||
tables: [],
|
||||
indexes: [],
|
||||
views: [],
|
||||
triggers: [],
|
||||
},
|
||||
rows: null,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const execution = (value: unknown) =>
|
||||
createAnalysisExecution(
|
||||
value,
|
||||
{ id: "sqlite", name: "SQLite", version: "3.50.2" },
|
||||
{
|
||||
subject: { path: "/selected.db", sha256: "a".repeat(64), format: "file" },
|
||||
locations: [{ kind: "artifact-path", path: "/selected.db" }],
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ path: "relative.db" },
|
||||
{ path: "/selected.db", approval: true },
|
||||
{ path: "/selected.db", row_limit: 1 },
|
||||
{ path: "/selected.db", table: 1 },
|
||||
{ path: "/selected.db", table: "data", row_limit: 0 },
|
||||
{
|
||||
path: "/selected.db",
|
||||
table: "data",
|
||||
row_limit: Number.MAX_SAFE_INTEGER + 1,
|
||||
},
|
||||
])(
|
||||
"rejects invalid SQLite selection before provider effects: %j",
|
||||
async (input) => {
|
||||
const service = new SqliteDatabaseService({
|
||||
inspect: () => {
|
||||
throw new Error("Invalid selection must not read a database");
|
||||
},
|
||||
});
|
||||
expect(await service.inspect(input)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves producer failures and rejects pre-cancelled requests before effects", async () => {
|
||||
const failure = new AnalysisCapabilityUnavailableError(
|
||||
"rea-sqlite",
|
||||
"inspect_sqlite_database",
|
||||
"Selected worker could not start",
|
||||
);
|
||||
const service = new SqliteDatabaseService({
|
||||
inspect: () => Promise.resolve(err(failure)),
|
||||
});
|
||||
expect(await service.inspect({ path: "/selected.db" })).toEqual(err(failure));
|
||||
const signal = AbortSignal.abort();
|
||||
const untouched = new SqliteDatabaseService({
|
||||
inspect: () => {
|
||||
throw new Error("Cancelled selection must not read a database");
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await untouched.inspect({ path: "/selected.db" }, { signal }),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["path", "digest", "subject", "wal", "table"])(
|
||||
"rejects producer results with changed caller binding: %s",
|
||||
async (problem) => {
|
||||
const value = fixture();
|
||||
if (problem === "path") value.artifact.path = "/other.db";
|
||||
if (problem === "digest") value.artifact.sha256 = "b".repeat(64);
|
||||
const observed = execution({
|
||||
...value,
|
||||
...(problem === "wal"
|
||||
? { wal: { path: "/other.db-wal", sha256: "b".repeat(64), bytes: 32 } }
|
||||
: {}),
|
||||
});
|
||||
const service = new SqliteDatabaseService({
|
||||
inspect: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
...observed,
|
||||
...(problem === "subject" ? { subject: null } : {}),
|
||||
}),
|
||||
),
|
||||
});
|
||||
expect(
|
||||
await service.inspect({
|
||||
path: "/selected.db",
|
||||
...(problem === "table" ? { table: "selected" } : {}),
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves completed observed evidence when cancellation arrives after provider completion", async () => {
|
||||
const value = fixture();
|
||||
const service = new SqliteDatabaseService({
|
||||
inspect: () => Promise.resolve(ok(execution(value))),
|
||||
});
|
||||
expect(await service.inspect({ path: "/selected.db" })).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
confidence: "observed",
|
||||
subject: {
|
||||
local_path: "/selected.db",
|
||||
digest: { sha256: "a".repeat(64) },
|
||||
},
|
||||
normalized_result: value,
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const cancelled = new SqliteDatabaseService({
|
||||
inspect: () => {
|
||||
controller.abort();
|
||||
return Promise.resolve(ok(execution(value)));
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await cancelled.inspect(
|
||||
{ path: "/selected.db" },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { normalized_result: value },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { SqliteDatabasePort } from "./SqliteDatabasePort.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
createEvidence,
|
||||
type Evidence,
|
||||
type EvidenceSubjectTarget,
|
||||
} from "../../domain/evidence.js";
|
||||
import {
|
||||
inspectSqliteDatabaseInputSchema,
|
||||
sqliteDatabaseSchema,
|
||||
type InspectSqliteDatabaseInput,
|
||||
type SqliteDatabase,
|
||||
SQLITE_ROW_LIMIT_DEFAULT,
|
||||
sqliteSchemaScope,
|
||||
sqliteInspectionParameters,
|
||||
} from "../../domain/sqlite/sqliteDatabase.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
|
||||
const OPERATION = "inspect_sqlite_database";
|
||||
|
||||
const matchesSelectedDatabase = (
|
||||
report: SqliteDatabase,
|
||||
input: InspectSqliteDatabaseInput,
|
||||
subject: EvidenceSubjectTarget,
|
||||
): boolean =>
|
||||
report.artifact.path === input.path &&
|
||||
subject.path === input.path &&
|
||||
subject.sha256 === report.artifact.sha256 &&
|
||||
subject.format === "file" &&
|
||||
(report.wal === null || report.wal.path === `${input.path}-wal`) &&
|
||||
report.schema.scope === sqliteSchemaScope(input) &&
|
||||
(report.schema.scope !== "selected_table" ||
|
||||
(report.schema.tables.length === 1 &&
|
||||
report.schema.tables[0]?.name === input.table &&
|
||||
report.schema.indexes.every((index) => index.table === input.table) &&
|
||||
report.schema.triggers.every(
|
||||
(trigger) => trigger.table === input.table,
|
||||
) &&
|
||||
report.schema.views.length === 0)) &&
|
||||
(input.table === undefined
|
||||
? report.rows === null
|
||||
: report.rows?.table === input.table &&
|
||||
report.rows.row_limit === (input.row_limit ?? SQLITE_ROW_LIMIT_DEFAULT) &&
|
||||
(input.columns === undefined ||
|
||||
(report.rows.columns.length === input.columns.length &&
|
||||
report.rows.columns.every(
|
||||
(name, index) => name === input.columns?.[index],
|
||||
))));
|
||||
|
||||
/** Shared snapshot inspection and caller-selection validation for CLI and MCP. */
|
||||
export class SqliteDatabaseService {
|
||||
constructor(readonly provider: SqliteDatabasePort) {}
|
||||
|
||||
/** Await provider shutdown, retaining failed cleanup owners for retry. */
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Inspect an explicit database snapshot and preserve its original database/WAL identity. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const input = inspectSqliteDatabaseInputSchema.safeParse(rawInput);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
if (!isAbsolute(input.data.path))
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute filesystem path on this host.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
if (!inspected.ok) return inspected;
|
||||
const execution = inspected.value;
|
||||
const report = sqliteDatabaseSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
execution.subject === null ||
|
||||
!matchesSelectedDatabase(report.data, input.data, execution.subject)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"SQLite adapter returned malformed data or changed the selected database identity/table/row limit.",
|
||||
),
|
||||
);
|
||||
return ok(
|
||||
createEvidence(execution.subject, execution.provider, {
|
||||
operation: OPERATION,
|
||||
parameters: sqliteInspectionParameters(input.data),
|
||||
result: jsonValueSchema.parse(report.data),
|
||||
...(execution.rawResult === null
|
||||
? {}
|
||||
: { rawResult: execution.rawResult }),
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js";
|
||||
import type { ArtifactReader } from "./ArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import type { SafeOutputTree } from "./SafeOutputTree.js";
|
||||
import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
|
||||
/** One artifact resource and its format-specific cleanup owner. */
|
||||
export type ArtifactResourceOwner =
|
||||
@@ -38,6 +39,11 @@ export type ArtifactResourceOwner =
|
||||
readonly kind: "staged-output";
|
||||
readonly resource: string;
|
||||
readonly output: OwnedStagedOutput;
|
||||
}
|
||||
| {
|
||||
readonly kind: "private-runtime-root";
|
||||
readonly resource: string;
|
||||
readonly root: Pick<PrivateRuntimeRoot, "path" | "close">;
|
||||
};
|
||||
|
||||
export type ArtifactCleanupAttempt =
|
||||
@@ -161,5 +167,8 @@ const cleanup = async (owner: ArtifactResourceOwner): Promise<void> => {
|
||||
return;
|
||||
case "staged-output":
|
||||
await owner.output.close();
|
||||
return;
|
||||
case "private-runtime-root":
|
||||
await owner.root.close();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -625,7 +625,9 @@ const verifyFailureReason = (
|
||||
processOutput(cause, "stderr"),
|
||||
);
|
||||
switch (diagnostic) {
|
||||
// hdiutil follows AppleLanguages, so en-GB and en-AU spell it "recognised".
|
||||
case "image not recognized":
|
||||
case "image not recognised":
|
||||
return "format";
|
||||
case "invalid checksum":
|
||||
case "image data corrupted":
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Stats } from "node:fs";
|
||||
import type { BigIntStats, Stats } from "node:fs";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
NonRegularFileReadError,
|
||||
openRegularFile,
|
||||
RegularFileAdmissionFailure,
|
||||
sameRegularFileState,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
|
||||
const { mockOpen } = vi.hoisted(() => ({ mockOpen: vi.fn() }));
|
||||
@@ -66,3 +67,24 @@ it.each(["cancellation after open", "non-regular metadata", "stat failure"])(
|
||||
else expect(cause.cause).toBe(cancellation);
|
||||
},
|
||||
);
|
||||
|
||||
it("compares available nanosecond timestamps without rounding away source changes", () => {
|
||||
const before = {
|
||||
dev: 1n,
|
||||
ino: 2n,
|
||||
size: 3n,
|
||||
mode: 0o100400n,
|
||||
mtimeMs: 10n,
|
||||
ctimeMs: 20n,
|
||||
mtimeNs: 10_000_001n,
|
||||
ctimeNs: 20_000_001n,
|
||||
isFile: () => true,
|
||||
} as BigIntStats;
|
||||
expect(sameRegularFileState(before, { ...before })).toBe(true);
|
||||
expect(
|
||||
sameRegularFileState(before, { ...before, mtimeNs: before.mtimeNs + 1n }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
sameRegularFileState(before, { ...before, ctimeNs: before.ctimeNs + 1n }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ZipArtifactReader } from "./ZipArtifactReader.js";
|
||||
import {
|
||||
ARTIFACT_DECOMPRESSION_RATIO,
|
||||
artifactDecompressionBudgetBytes,
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
|
||||
} from "../domain/artifactDecompressionBudget.js";
|
||||
|
||||
/** Small real ZIP carriers with forged sizes; metadata-only controls, never decompressed. */
|
||||
const writeZipWithDeclaredSize = async (
|
||||
directory: string,
|
||||
declaredBytes: readonly number[],
|
||||
): Promise<string> => {
|
||||
const path = join(directory, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
for (const [index] of declaredBytes.entries())
|
||||
await writer.add(
|
||||
`member-${index}.bin`,
|
||||
new TextReader("real member bytes"),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
const bytes = await readFile(path);
|
||||
let offset = 0;
|
||||
for (const declared of declaredBytes) {
|
||||
const centralDirectory = bytes.indexOf(
|
||||
Buffer.from([0x50, 0x4b, 0x01, 0x02]),
|
||||
offset,
|
||||
);
|
||||
if (centralDirectory < 0)
|
||||
throw new Error("Expected a ZIP central directory");
|
||||
// Metadata-only controls: these declarations do not describe valid member streams.
|
||||
bytes.writeUInt32LE(declared, centralDirectory + 24);
|
||||
offset = centralDirectory + 46;
|
||||
}
|
||||
await writeFile(path, bytes);
|
||||
return path;
|
||||
};
|
||||
|
||||
const enumerate = async (reader: ZipArtifactReader): Promise<number> => {
|
||||
let files = 0;
|
||||
for await (const entry of reader.entries())
|
||||
if (entry.kind === "file") files += 1;
|
||||
return files;
|
||||
};
|
||||
|
||||
describe("ZipArtifactReader decompression budget", () => {
|
||||
it("refuses an archive whose entries declare more than its size can justify", async () => {
|
||||
const directory = await createTestTempDirectory("rea-zip-budget-bomb-");
|
||||
// A ~160-byte archive cannot declare 2 GiB of members without being a bomb.
|
||||
const path = await writeZipWithDeclaredSize(directory, [2_147_483_647]);
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
try {
|
||||
await expect(enumerate(reader)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "limit",
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("charges all declarations in one traversal before yielding an over-budget member", async () => {
|
||||
const directory = await createTestTempDirectory("rea-zip-budget-total-");
|
||||
const half = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2;
|
||||
const path = await writeZipWithDeclaredSize(directory, [half, half + 1]);
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
const iterator = reader.entries()[Symbol.asyncIterator]();
|
||||
try {
|
||||
expect((await iterator.next()).value?.declaredSize).toBe(half);
|
||||
await expect(iterator.next()).rejects.toMatchObject({ reason: "limit" });
|
||||
} finally {
|
||||
await iterator.return?.();
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps repeated and interleaved metadata traversals independently charged", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-zip-budget-iterators-",
|
||||
);
|
||||
const path = await writeZipWithDeclaredSize(directory, [
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
|
||||
]);
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
const first = reader.entries()[Symbol.asyncIterator]();
|
||||
const second = reader.entries()[Symbol.asyncIterator]();
|
||||
try {
|
||||
expect((await first.next()).done).toBe(false);
|
||||
expect((await second.next()).done).toBe(false);
|
||||
expect((await first.next()).done).toBe(false);
|
||||
expect((await second.next()).done).toBe(false);
|
||||
expect((await first.next()).done).toBe(true);
|
||||
expect((await second.next()).done).toBe(true);
|
||||
expect(await enumerate(reader)).toBe(2);
|
||||
} finally {
|
||||
await Promise.all([first.return?.(), second.return?.()]);
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("streams a valid small member through open", async () => {
|
||||
const directory = await createTestTempDirectory("rea-zip-budget-valid-");
|
||||
const path = join(directory, "valid.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("member.bin", new TextReader("valid member bytes"));
|
||||
await writeFile(path, await writer.close());
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries[0];
|
||||
if (entry === undefined) throw new Error("Expected a ZIP member");
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of await reader.open(entry))
|
||||
chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe("valid member bytes");
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects under-declared member output before delivering its complete actual bytes", async () => {
|
||||
const directory = await createTestTempDirectory("rea-zip-underdeclared-");
|
||||
const path = join(directory, "underdeclared.zip");
|
||||
const content = new Uint8Array(128 * 1024);
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("member.bin", new Uint8ArrayReader(content), {
|
||||
dataDescriptor: false,
|
||||
bufferedWrite: true,
|
||||
});
|
||||
const bytes = Buffer.from(await writer.close());
|
||||
const local = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||
const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
|
||||
if (local < 0 || central < 0) throw new Error("Expected ZIP entry headers");
|
||||
// Both headers agree and no descriptor remains: rejection must enforce
|
||||
// actual decompressed output, not merely detect conflicting metadata.
|
||||
expect(bytes.readUInt16LE(local + 6) & 8).toBe(0);
|
||||
expect(bytes.readUInt16LE(local + 8)).toBe(8);
|
||||
expect(bytes.readUInt32LE(local + 22)).toBe(content.length);
|
||||
expect(bytes.readUInt32LE(central + 24)).toBe(content.length);
|
||||
bytes.writeUInt32LE(1, local + 22);
|
||||
bytes.writeUInt32LE(1, central + 24);
|
||||
await writeFile(path, bytes);
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries[0];
|
||||
if (entry === undefined) throw new Error("Expected a ZIP member");
|
||||
expect(entry.declaredSize).toBe(1);
|
||||
let deliveredBytes = 0;
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const chunk of await reader.open(entry))
|
||||
deliveredBytes += Buffer.from(chunk).length;
|
||||
})(),
|
||||
).rejects.toThrow("Invalid uncompressed size");
|
||||
expect(deliveredBytes).toBeLessThan(content.length);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("artifactDecompressionBudgetBytes", () => {
|
||||
it("grants at least the floor and grows with the compressed size", () => {
|
||||
expect(artifactDecompressionBudgetBytes(0)).toBe(
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
|
||||
);
|
||||
expect(artifactDecompressionBudgetBytes(1024)).toBe(
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
|
||||
);
|
||||
const large = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES * 4;
|
||||
expect(artifactDecompressionBudgetBytes(large)).toBe(
|
||||
large * ARTIFACT_DECOMPRESSION_RATIO,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,11 @@ import {
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
|
||||
import {
|
||||
ARTIFACT_DECOMPRESSION_RATIO,
|
||||
artifactDecompressionBudgetBytes,
|
||||
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
|
||||
} from "../domain/artifactDecompressionBudget.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
@@ -132,7 +137,6 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
string,
|
||||
{ readonly source: Entry; readonly metadata: ArtifactEntry }
|
||||
>();
|
||||
|
||||
/** Optionally bound each metadata read before allocating its backing buffer. */
|
||||
constructor(
|
||||
path: string,
|
||||
@@ -153,6 +157,8 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let index = 0;
|
||||
// A traversal owns its accounting, including overlapping or repeated passes.
|
||||
let declaredFileBytes = 0;
|
||||
for await (const entry of this.#reader.getEntriesGenerator({
|
||||
decodeText: decodeZipEntryText,
|
||||
})) {
|
||||
@@ -160,6 +166,22 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
// ZIP member identity is its directory occurrence, not its filename.
|
||||
// Logical path uniqueness belongs to the artifact inventory boundary.
|
||||
const metadata = projectZipEntry(entry, index++);
|
||||
// zip.js enforces each member's declared output size, so this sum bounds streamed work.
|
||||
if (
|
||||
metadata.kind === "file" &&
|
||||
!metadata.encrypted &&
|
||||
metadata.declaredSize !== null &&
|
||||
Number.isSafeInteger(metadata.declaredSize) &&
|
||||
metadata.declaredSize >= 0
|
||||
) {
|
||||
declaredFileBytes += metadata.declaredSize;
|
||||
const budget = artifactDecompressionBudgetBytes(this.#source.size);
|
||||
if (declaredFileBytes > budget)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`ZIP entries declare ${String(declaredFileBytes)} uncompressed bytes, exceeding this archive's ${String(budget)}-byte decompression budget (${String(MINIMUM_ARTIFACT_DECOMPRESSION_BYTES)}-byte minimum, ${String(ARTIFACT_DECOMPRESSION_RATIO)}x archive size); a small archive cannot expand this far`,
|
||||
);
|
||||
}
|
||||
const stored = this.#entries.get(metadata.adapterKey);
|
||||
if (stored !== undefined && !sameArtifactEntry(metadata, stored.metadata))
|
||||
throw new ArtifactReaderFailure(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
|
||||
import { encodeNibArchiveFixture } from "./NibArchive.fixture.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import {
|
||||
analyzeAppleAssetCatalogs,
|
||||
@@ -22,6 +24,13 @@ describe("Apple asset catalog application workflow", () => {
|
||||
imageName: "Toolbar",
|
||||
title: "not-an-asset-key",
|
||||
image: 42,
|
||||
nibValues: {
|
||||
title: "not-an-asset-key",
|
||||
imageName: { value: "not-a-scalar" },
|
||||
image: 42,
|
||||
assetName: "",
|
||||
nested: { NSImageName: "not-a-direct-field" },
|
||||
},
|
||||
},
|
||||
evidence: [
|
||||
{
|
||||
@@ -34,8 +43,13 @@ describe("Apple asset catalog application workflow", () => {
|
||||
id: "ib:Main.nib:object:3",
|
||||
kind: "control",
|
||||
name: "Toolbar",
|
||||
attributes: { title: "not-an-asset-key" },
|
||||
evidence: [],
|
||||
attributes: { NSImageName: "Toolbar", imageName: "Toolbar" },
|
||||
evidence: [
|
||||
{
|
||||
artifact_path: "Contents/Resources/Main.nib",
|
||||
artifact_sha256: "d".repeat(64),
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
@@ -118,3 +132,77 @@ describe("Apple asset catalog application workflow", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([1, 2])(
|
||||
"joins NIBArchive keys against %i supplied assetutil renditions",
|
||||
async (count) => {
|
||||
const bundle = await createTestTempDirectory("rea-asset-nib-join-");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
const archive = encodeNibArchiveFixture({
|
||||
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
|
||||
{ classIndex: 1, values: { image: { ref: 2 } } },
|
||||
{ classIndex: 2, values: { NSImageName: { ref: 3 } } },
|
||||
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
|
||||
],
|
||||
});
|
||||
await writeFile(join(resources, "Panel.nib"), archive);
|
||||
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
|
||||
// Supplied metadata tests the post-engine join; it does not establish native catalog validity.
|
||||
const result = await analyzeAppleAssetCatalogs({
|
||||
environment: {},
|
||||
bundlePath: bundle,
|
||||
targetSha256: "a".repeat(64),
|
||||
runAssetUtil: () =>
|
||||
Promise.resolve(
|
||||
JSON.stringify(
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
Name: "Toolbar",
|
||||
RenditionName: `toolbar-${String(index)}.png`,
|
||||
})),
|
||||
),
|
||||
),
|
||||
});
|
||||
expect(result.resource_key_matches).toHaveLength(1);
|
||||
expect(result.resource_key_matches[0]).toMatchObject({
|
||||
field: "NSImageName",
|
||||
key: "Toolbar",
|
||||
status: count === 1 ? "matched" : "ambiguous",
|
||||
source_path: "Contents/Resources/Panel.nib",
|
||||
source_archive_sha256: createHash("sha256").update(archive).digest("hex"),
|
||||
renditions: Array.from({ length: count }, (_, index) =>
|
||||
expect.objectContaining({
|
||||
record_index: index,
|
||||
rendition_name: `toolbar-${String(index)}.png`,
|
||||
}),
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps recognized image fields on NIBArchive controls out of resource joins", async () => {
|
||||
const bundle = await createTestTempDirectory("rea-asset-nib-control-");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await writeFile(
|
||||
join(resources, "Panel.nib"),
|
||||
encodeNibArchiveFixture({
|
||||
classes: ["NSIBObjectData", "NSButton", "NSString"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
|
||||
{ classIndex: 1, values: { NSImageName: { ref: 2 } } },
|
||||
{ classIndex: 2, values: { "NS.bytes": "Toolbar" } },
|
||||
],
|
||||
}),
|
||||
);
|
||||
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
|
||||
const result = await analyzeAppleAssetCatalogs({
|
||||
environment: {},
|
||||
bundlePath: bundle,
|
||||
targetSha256: "a".repeat(64),
|
||||
runAssetUtil: () => Promise.resolve(JSON.stringify([{ Name: "Toolbar" }])),
|
||||
});
|
||||
expect(result.resource_key_matches).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
|
||||
import {
|
||||
appleAssetCatalogInputSchema,
|
||||
appleResourceKeyFields,
|
||||
parseAppleAssetCatalogRecords,
|
||||
projectAppleAssetCatalogPage,
|
||||
} from "../../domain/apple/appleAssetCatalog.js";
|
||||
@@ -16,17 +17,6 @@ import { execFileOutput } from "../../process/ExecFileOutput.js";
|
||||
const ASSETUTIL = "/usr/bin/assetutil";
|
||||
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
|
||||
const RESOURCE_KEY_FIELDS = new Set([
|
||||
"image",
|
||||
"imageName",
|
||||
"image_name",
|
||||
"resourceName",
|
||||
"resource_name",
|
||||
"assetName",
|
||||
"asset_name",
|
||||
"UIImageName",
|
||||
"NSImageName",
|
||||
]);
|
||||
|
||||
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
|
||||
export const analyzeAppleAssetCatalogs = async (input: {
|
||||
@@ -201,27 +191,22 @@ export const collectInterfaceBuilderResourceKeys = (
|
||||
}[],
|
||||
) =>
|
||||
nodes.flatMap((node) => {
|
||||
if (node.kind !== "resource") return [];
|
||||
const source = node.evidence.find(
|
||||
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
|
||||
);
|
||||
const sourcePath = source?.artifact_path;
|
||||
const sourceArchiveSha256 = source?.artifact_sha256;
|
||||
if (sourcePath == null || sourceArchiveSha256 == null) return [];
|
||||
return Object.entries(node.attributes).flatMap(([field, value]) =>
|
||||
RESOURCE_KEY_FIELDS.has(field) &&
|
||||
typeof value === "string" &&
|
||||
value.length > 0
|
||||
? [
|
||||
{
|
||||
sourceNodeId: node.id,
|
||||
sourcePath,
|
||||
sourceArchiveSha256,
|
||||
field,
|
||||
key: value,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
return appleResourceKeyFields(node.attributes).flatMap(([field, value]) => [
|
||||
{
|
||||
sourceNodeId: node.id,
|
||||
sourcePath,
|
||||
sourceArchiveSha256,
|
||||
field,
|
||||
key: value,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
const runAssetUtil = async (
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { parseBinary } from "plist";
|
||||
|
||||
import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
|
||||
import {
|
||||
interfaceBuilderConnectionFieldNames,
|
||||
isUIKitRuntimeConnectionClass,
|
||||
} from "../../domain/apple/interfaceBuilderKeyedArchive.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
@@ -28,6 +33,10 @@ import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
|
||||
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
|
||||
import {
|
||||
hasBinaryPlistSignature,
|
||||
hasNibArchiveSignature,
|
||||
} from "../../domain/apple/appleArchiveFormat.js";
|
||||
|
||||
const MAX_AGGREGATE_INPUT_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_AGGREGATE_DECODE_BYTES = 256 * 1024 * 1024;
|
||||
@@ -89,8 +98,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
|
||||
remainingInputBytes,
|
||||
);
|
||||
aggregateInputBytes += bytes.length;
|
||||
const isNibArchive =
|
||||
bytes.subarray(0, 10).toString("ascii") === "NIBArchive";
|
||||
const isNibArchive = hasNibArchiveSignature(bytes);
|
||||
let nib: ReturnType<typeof projectNibArchive> | null = null;
|
||||
let xmlText: string | undefined;
|
||||
let binaryPrototypeKeyObserved = false;
|
||||
@@ -108,7 +116,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
|
||||
"NIBArchive representation exceeds the aggregate Interface Builder decode budget",
|
||||
);
|
||||
} else {
|
||||
if (bytes.subarray(0, 8).toString("ascii") !== "bplist00")
|
||||
if (!hasBinaryPlistSignature(bytes))
|
||||
xmlText = decodeXmlPlistText(bytes);
|
||||
const decodedReservation = preflightPropertyListDecode(
|
||||
bytes,
|
||||
@@ -437,8 +445,10 @@ const projectNibArchive = (
|
||||
archive.objects
|
||||
.filter((object) => {
|
||||
const name = runtimeClass(object.id) ?? "";
|
||||
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
|
||||
name,
|
||||
return (
|
||||
!/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector)$/u.test(
|
||||
name,
|
||||
) && !isUIKitRuntimeConnectionClass(name)
|
||||
);
|
||||
})
|
||||
.map((object) => {
|
||||
@@ -459,18 +469,27 @@ const projectNibArchive = (
|
||||
break;
|
||||
}
|
||||
budget.reserveJsonStringOccurrence(name);
|
||||
const nibValues = Object.fromEntries(
|
||||
Object.entries(object.values).map(([key, value]) => {
|
||||
budget.reserveJsonPropertyNameOccurrence(key);
|
||||
return [key, dereference(value) ?? null];
|
||||
}),
|
||||
);
|
||||
// Normalize only recognized scalar fields at the format owner. A keyed
|
||||
// archive's authored nibValues dictionary must not gain this meaning.
|
||||
const resourceFields = appleResourceKeyFields(nibValues);
|
||||
for (const [field, value] of resourceFields) {
|
||||
budget.reserveJsonPropertyNameOccurrence(field);
|
||||
budget.reserveJsonStringOccurrence(value);
|
||||
}
|
||||
return [
|
||||
String(object.id),
|
||||
{
|
||||
customClass: className,
|
||||
label: name,
|
||||
objectID: String(object.id),
|
||||
nibValues: Object.fromEntries(
|
||||
Object.entries(object.values).map(([key, value]) => {
|
||||
budget.reserveJsonPropertyNameOccurrence(key);
|
||||
return [key, dereference(value) ?? null];
|
||||
}),
|
||||
),
|
||||
nibValues,
|
||||
...Object.fromEntries(resourceFields),
|
||||
},
|
||||
];
|
||||
}),
|
||||
@@ -488,15 +507,14 @@ const projectNibArchive = (
|
||||
const className = normalizeClassName(object.class_name);
|
||||
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
|
||||
// event connections use UI-prefixed keys with the same roles.
|
||||
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
|
||||
const uiKit = isUIKitRuntimeConnectionClass(className);
|
||||
if (!uiKit && !className.includes("Connector")) continue;
|
||||
const values = object.values;
|
||||
const source = reference(uiKit ? values.UISource : values.NSSource);
|
||||
const connectionFields = interfaceBuilderConnectionFieldNames(className);
|
||||
const source = reference(values[connectionFields.source]);
|
||||
if (source === null) continue;
|
||||
const destination = reference(
|
||||
uiKit ? values.UIDestination : values.NSDestination,
|
||||
);
|
||||
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
|
||||
const destination = reference(values[connectionFields.destination]);
|
||||
const label = referencedString(values[connectionFields.label]);
|
||||
const type = className.includes("Outlet")
|
||||
? "outlet"
|
||||
: className.includes("Control") || className.includes("Event")
|
||||
@@ -650,7 +668,7 @@ const decodePlist = (
|
||||
readonly value: JsonValue;
|
||||
readonly omittedPrototypeKeys: number | null;
|
||||
} => {
|
||||
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
|
||||
const binary = hasBinaryPlistSignature(bytes);
|
||||
const { value, omittedPrototypeKeys } = binary
|
||||
? {
|
||||
value: parseBinary(bytes),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
|
||||
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
|
||||
|
||||
/** Reason reported when an archive would exceed the shared decoding budget. */
|
||||
export type InterfaceBuilderBudgetReason = "aggregate_decode_budget_exhausted";
|
||||
@@ -94,13 +95,12 @@ export const preflightPropertyListDecode = (
|
||||
maxBytes: number,
|
||||
xmlText?: string,
|
||||
): PlistDecodePreflight => {
|
||||
const expansion =
|
||||
bytes.subarray(0, 8).toString("ascii") === "bplist00"
|
||||
? estimateBinaryPlistExpansion(bytes, maxBytes)
|
||||
: {
|
||||
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
|
||||
binaryPrototypeKeyObserved: false,
|
||||
};
|
||||
const expansion = hasBinaryPlistSignature(bytes)
|
||||
? estimateBinaryPlistExpansion(bytes, maxBytes)
|
||||
: {
|
||||
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
|
||||
binaryPrototypeKeyObserved: false,
|
||||
};
|
||||
if (expansion.estimatedBytes > maxBytes)
|
||||
throw new InterfaceBuilderDecodeBudgetExceeded(
|
||||
"aggregate_decode_budget_exhausted",
|
||||
@@ -170,8 +170,8 @@ export interface BinaryPlistExpansionOptions {
|
||||
readonly fail?: (kind: BinaryPlistExpansionFailure, message: string) => Error;
|
||||
/**
|
||||
* Structural bounds: "strict" keeps objects and the offset table before the
|
||||
* trailer; "decoder" admits exactly what plist.parseBinary can read, so
|
||||
* expansion is bounded without rejecting archives that decoder accepts.
|
||||
* trailer; "decoder" follows the decoder's object-table boundary policy
|
||||
* while still rejecting structures whose coercion would lose plist facts.
|
||||
*/
|
||||
readonly bounds?: "strict" | "decoder";
|
||||
}
|
||||
@@ -267,6 +267,8 @@ export const estimateBinaryPlistExpansion = (
|
||||
throw new TypeError("binary plist object offset is invalid");
|
||||
const marker = bytes[offset] ?? 0;
|
||||
const type = marker >> 4;
|
||||
if (entry.dictionaryKey && type !== 5 && type !== 6)
|
||||
throw new TypeError("binary plist dictionary key is not a string");
|
||||
let size = marker & 0x0f;
|
||||
let cursor = offset + 1;
|
||||
if (size === 0x0f && type !== 0 && type !== 8) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { build, buildBinary } from "plist";
|
||||
import { build, buildBinary, type PlistValue } from "plist";
|
||||
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
|
||||
import { deeplyNestedXmlPlist } from "../../../tests/fixtures/keyedArchiveXmlNesting.js";
|
||||
|
||||
const archive = {
|
||||
$archiver: "NSKeyedArchiver",
|
||||
@@ -22,6 +23,23 @@ const archive = {
|
||||
$top: { root: { UID: 1 }, other: { UID: 2 } },
|
||||
};
|
||||
describe("inert keyed archive decoding", () => {
|
||||
it.each(["bplist00", "NIBArchive"])(
|
||||
"rejects high-bit mutations of %s as malformed bytes rather than another archive kind",
|
||||
(signature) => {
|
||||
for (let index = 0; index < signature.length; index += 1) {
|
||||
const bytes = Buffer.from(signature);
|
||||
bytes[index] = (bytes[index] ?? 0) | 0x80;
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(bytes, { offset: 0, limit: 1 }),
|
||||
).toThrow(
|
||||
expect.objectContaining({
|
||||
code: "ERR_ENCODING_INVALID_ENCODED_DATA",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves CF$UID, malformed references and original pagination identities", () => {
|
||||
const bytes = Buffer.from(
|
||||
build({
|
||||
@@ -201,6 +219,37 @@ const keyedRoot = (payload: readonly Buffer[]): Buffer =>
|
||||
describe("binary plist reference preflight", () => {
|
||||
const selection = { offset: 0, limit: 10 };
|
||||
|
||||
it("rejects an array key that coerces to __proto__ before parsing", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(
|
||||
keyedRoot([
|
||||
plistArray([9]),
|
||||
Buffer.from([0xd1, 0, 10, 0, 11]),
|
||||
plistArray([12]),
|
||||
Buffer.from([0xd1, 0, 13, 0, 14]),
|
||||
plistString("__proto__"),
|
||||
plistString("lost"),
|
||||
plistString("value"),
|
||||
]),
|
||||
selection,
|
||||
),
|
||||
).toThrow("binary plist dictionary key is not a string");
|
||||
});
|
||||
|
||||
it("rejects binary data dictionary keys", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(
|
||||
keyedRoot([
|
||||
plistArray([9]),
|
||||
Buffer.from([0xd1, 0, 10, 0, 11]),
|
||||
Buffer.from([0x41, 0xab]),
|
||||
plistString("value"),
|
||||
]),
|
||||
selection,
|
||||
),
|
||||
).toThrow("binary plist dictionary key is not a string");
|
||||
});
|
||||
|
||||
it("reports a reference cycle as malformed, not as an oversized archive", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(keyedRoot([plistArray([8])]), selection),
|
||||
@@ -323,3 +372,66 @@ describe("binary plist reference preflight", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("XML plist nesting preflight", () => {
|
||||
const selection = { offset: 0, limit: 1 };
|
||||
|
||||
/** A valid XML NSKeyedArchiver envelope whose object 1 nests `depth` dictionaries. */
|
||||
const deeplyNestedArchive = (depth: number) => {
|
||||
let payload: PlistValue = "leaf";
|
||||
for (let level = 0; level < depth; level += 1) payload = { k: payload };
|
||||
return Buffer.from(
|
||||
build({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: ["$null", payload],
|
||||
$top: { root: { UID: 1 } },
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/** Follow the single-member chain of a decoded object to its deepest value. */
|
||||
const deepestValue = (value: unknown): unknown => {
|
||||
let cursor = value;
|
||||
while (
|
||||
cursor !== null &&
|
||||
typeof cursor === "object" &&
|
||||
!Array.isArray(cursor) &&
|
||||
"k" in cursor
|
||||
) {
|
||||
cursor = (cursor as Record<string, unknown>).k;
|
||||
}
|
||||
return cursor;
|
||||
};
|
||||
|
||||
it.each([129, 4000])(
|
||||
"rejects %i-level XML nesting as the documented resource limit",
|
||||
(depth) => {
|
||||
// Recursive decoding exceeds the call stack before the projection limit
|
||||
// can report it, so the decoder must reject the nesting up front with
|
||||
// the same bounded-resource error an in-reach document would produce.
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(
|
||||
Buffer.from(deeplyNestedXmlPlist(depth)),
|
||||
selection,
|
||||
),
|
||||
).toThrow(new RangeError("Plist exceeds 128 nesting levels"));
|
||||
},
|
||||
);
|
||||
|
||||
it("decodes a valid XML keyed archive exactly at the nesting limit", () => {
|
||||
const graph = decodeKeyedArchiveBytes(deeplyNestedArchive(126), {
|
||||
root: "root",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
expect(graph.objects).toHaveLength(1);
|
||||
expect(deepestValue(graph.objects[0]?.value)).toBe("leaf");
|
||||
});
|
||||
|
||||
it("rejects one nesting level past the limit before decoding", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(deeplyNestedArchive(127), selection),
|
||||
).toThrow(new RangeError("Plist exceeds 128 nesting levels"));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,10 @@ import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import type { ArtifactEntry } from "../ArtifactReader.js";
|
||||
|
||||
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
|
||||
import {
|
||||
hasBinaryPlistSignature,
|
||||
hasNibArchiveSignature,
|
||||
} from "../../domain/apple/appleArchiveFormat.js";
|
||||
import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";
|
||||
|
||||
const MAX_BYTES = 64 * 1024 * 1024;
|
||||
@@ -40,12 +44,12 @@ export const decodeKeyedArchiveBytes = (
|
||||
) => {
|
||||
if (bytes.length > MAX_BYTES)
|
||||
throw new RangeError("Keyed archive exceeds 64 MiB");
|
||||
if (bytes.subarray(0, 10).toString("ascii") === "NIBArchive")
|
||||
if (hasNibArchiveSignature(bytes))
|
||||
throw new KeyedArchiveKindError(
|
||||
"Selected file is a compiled NIBArchive, not a Foundation plist archive; decode it with decode_interface_builder",
|
||||
"nib-archive",
|
||||
);
|
||||
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
|
||||
const binary = hasBinaryPlistSignature(bytes);
|
||||
const xmlText = binary ? undefined : decodeXmlPlistText(bytes);
|
||||
// plist.parseBinary recurses on every object reference and copies shared
|
||||
// containers, so a few hundred bytes can exhaust memory or the stack.
|
||||
|
||||
@@ -21,6 +21,7 @@ export const CPU = {
|
||||
i386: { type: 7, subtype: 3 },
|
||||
arm64: { type: 0x0100000c, subtype: 0 },
|
||||
arm64e: { type: 0x0100000c, subtype: 0x80000002 },
|
||||
arm64eX1: { type: 0x0100000c, subtype: 0x8000000c },
|
||||
x86_64: { type: 0x01000007, subtype: 3 },
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "./MachoLoadCommandReader.js";
|
||||
import { traceDylibResolution } from "./DylibResolutionReader.js";
|
||||
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
|
||||
import { javaClassFile } from "../../../tests/fixtures/javaClassFile.js";
|
||||
|
||||
const read = (bytes: Uint8Array) =>
|
||||
readMachoImage(readerOf(bytes), bytes.length);
|
||||
@@ -135,6 +136,98 @@ it("uses legacy simulator and device platform facts when resolving dylibs", asyn
|
||||
);
|
||||
});
|
||||
|
||||
it("selects matching arm64e subtype slices when tracing a mixed FAT image", async () => {
|
||||
const root = await createTestTempDirectory("rea-macho-arm64e-subtypes-");
|
||||
const executablePath = "Contents/MacOS/App";
|
||||
const dylibPath = "Contents/MacOS/libVariant.dylib";
|
||||
const installName = "@executable_path/libVariant.dylib";
|
||||
const arm64eDependency = "@executable_path/libArm64e.dylib";
|
||||
const arm64eX1Dependency = "@executable_path/libArm64eX1.dylib";
|
||||
const executableSlice = (cpu: typeof CPU.arm64e | typeof CPU.arm64eX1) =>
|
||||
machoImage({
|
||||
cpu,
|
||||
commands: [
|
||||
buildVersionCommand(1),
|
||||
dylibCommand(LC.LOAD_DYLIB, installName),
|
||||
],
|
||||
});
|
||||
const executable = fatImage([
|
||||
{
|
||||
cpu: CPU.arm64eX1,
|
||||
bytes: executableSlice(CPU.arm64eX1),
|
||||
},
|
||||
{
|
||||
cpu: CPU.arm64e,
|
||||
bytes: executableSlice(CPU.arm64e),
|
||||
},
|
||||
]);
|
||||
const variantSlice = (
|
||||
cpu: typeof CPU.arm64e | typeof CPU.arm64eX1,
|
||||
dependencyName: string,
|
||||
) =>
|
||||
machoImage({
|
||||
cpu,
|
||||
fileType: FILE_TYPE.dylib,
|
||||
commands: [
|
||||
buildVersionCommand(1),
|
||||
dylibCommand(LC.ID_DYLIB, installName),
|
||||
dylibCommand(LC.LOAD_DYLIB, dependencyName),
|
||||
],
|
||||
});
|
||||
const completeDylib = fatImage([
|
||||
{
|
||||
cpu: CPU.arm64e,
|
||||
bytes: variantSlice(CPU.arm64e, arm64eDependency),
|
||||
},
|
||||
{
|
||||
cpu: CPU.arm64eX1,
|
||||
bytes: variantSlice(CPU.arm64eX1, arm64eX1Dependency),
|
||||
},
|
||||
]);
|
||||
await mkdir(join(root, "Contents/MacOS"), { recursive: true });
|
||||
await writeFile(join(root, executablePath), executable);
|
||||
await writeFile(join(root, dylibPath), completeDylib);
|
||||
|
||||
const trace = () =>
|
||||
traceDylibResolution({
|
||||
rootPath: root,
|
||||
targetPath: join(root, executablePath),
|
||||
targetSha256: createHash("sha256").update(executable).digest("hex"),
|
||||
enumerateRoots: false,
|
||||
parameters: { roots: [executablePath] },
|
||||
});
|
||||
|
||||
const complete = await trace();
|
||||
expect(
|
||||
complete.edges
|
||||
.filter(({ loader }) => loader === dylibPath)
|
||||
.map(({ install_name: dependencyName }) => dependencyName),
|
||||
).toEqual([arm64eX1Dependency, arm64eDependency]);
|
||||
|
||||
const onlyArm64e = fatImage([
|
||||
{
|
||||
cpu: CPU.arm64e,
|
||||
bytes: variantSlice(CPU.arm64e, arm64eDependency),
|
||||
},
|
||||
]);
|
||||
await writeFile(join(root, dylibPath), onlyArm64e);
|
||||
const missingVariant = await trace();
|
||||
expect(
|
||||
missingVariant.edges
|
||||
.filter(
|
||||
({ loader, install_name: dependencyName }) =>
|
||||
loader === executablePath && dependencyName === installName,
|
||||
)
|
||||
.map(({ candidates, resolution }) => [
|
||||
candidates[0]?.outcome,
|
||||
resolution.status,
|
||||
]),
|
||||
).toEqual([
|
||||
["architecture-missing", "unresolved"],
|
||||
["resolved", "resolved"],
|
||||
]);
|
||||
});
|
||||
|
||||
describe("Mach-O load command reader: decodes thin-image load commands", () => {
|
||||
it("decodes dylib loading commands of a thin image", async () => {
|
||||
const image = machoImage({
|
||||
@@ -345,10 +438,13 @@ describe("Mach-O load command reader inputs", () => {
|
||||
expect(i386.status === "parsed" && i386.slices[0]?.architecture).toBe(
|
||||
"i386",
|
||||
);
|
||||
// A Java class file shares the FAT magic; its version is not a slice count.
|
||||
const javaClass = Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);
|
||||
expect(hasMachoMagic(javaClass)).toBe(true);
|
||||
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
|
||||
// A Java class file shares the FAT magic; version fields are not a slice count.
|
||||
const javaClasses = [javaClassFile(), javaClassFile(4000)];
|
||||
expect(javaClasses.map(({ length }) => length)).toEqual([57, 4060]);
|
||||
for (const javaClass of javaClasses) {
|
||||
expect(hasMachoMagic(javaClass)).toBe(true);
|
||||
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
|
||||
}
|
||||
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
|
||||
status: "not-mach-o",
|
||||
});
|
||||
@@ -489,6 +585,16 @@ describe("Mach-O load command reader failures", () => {
|
||||
reason: "FAT architecture 0 slice range extends beyond the file",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves unsupported status for an unsupported FAT alignment exponent", async () => {
|
||||
const fat = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
|
||||
new DataView(fat.buffer).setUint32(24, 53, false);
|
||||
|
||||
expect(await read(fat)).toMatchObject({
|
||||
status: "unsupported",
|
||||
reason: expect.stringContaining("alignment exponent 53 is unsupported"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
|
||||
@@ -3,9 +3,11 @@ import type {
|
||||
MachoImageFacts,
|
||||
MachoSlice,
|
||||
} from "../../domain/apple/dylibResolution.js";
|
||||
import { machoCpuSubtypeBase } from "../../domain/apple/machoCpuIdentity.js";
|
||||
import {
|
||||
readFatSliceDeclarations,
|
||||
validateFatSlice,
|
||||
classifyFatContainerIdentity,
|
||||
readFatContainerHeader,
|
||||
validateFatSliceIdentity,
|
||||
type FatSliceDeclaration,
|
||||
} from "../../domain/apple/machoContainer.js";
|
||||
|
||||
@@ -14,13 +16,6 @@ export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
|
||||
|
||||
/** Load commands larger than this are refused instead of buffered. */
|
||||
export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
|
||||
/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
|
||||
const MAX_FAT_ARCHITECTURES = 128;
|
||||
/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
|
||||
const KNOWN_CPU_TYPES: readonly number[] = [
|
||||
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
|
||||
];
|
||||
|
||||
const MH_MAGIC = 0xfeedface;
|
||||
const MH_MAGIC_64 = 0xfeedfacf;
|
||||
const MH_CIGAM = 0xcefaedfe;
|
||||
@@ -146,69 +141,41 @@ export const readMachoImage = async (
|
||||
: { status: "not-mach-o" };
|
||||
const view = viewOf(head);
|
||||
const magic = view.getUint32(0, false);
|
||||
if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
|
||||
// FAT headers are big-endian; the swapped magics store them little-endian.
|
||||
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
|
||||
const count = view.getUint32(4, littleEndian);
|
||||
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
|
||||
// A Java class file's nonzero major version reads as the count, so an
|
||||
// empty architecture table can only be a malformed universal header.
|
||||
if (count === 0)
|
||||
return {
|
||||
status: "malformed",
|
||||
reason: "FAT header declares no architectures",
|
||||
};
|
||||
if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
|
||||
return { status: "not-mach-o" };
|
||||
const tableBytes = await readExact(
|
||||
readAt,
|
||||
8,
|
||||
count * (wide ? 32 : 20),
|
||||
"FAT table",
|
||||
);
|
||||
const declarations = readFatSliceDeclarations(tableBytes, {
|
||||
count,
|
||||
wide,
|
||||
littleEndian,
|
||||
});
|
||||
if (declarations.status !== "parsed")
|
||||
throw new MachoFormatIssue("malformed", declarations.reason);
|
||||
// A Java class file's version fields read as a FAT count; its "table" names no CPU.
|
||||
if (
|
||||
!declarations.slices.some(({ cpuType }) =>
|
||||
KNOWN_CPU_TYPES.includes(cpuType),
|
||||
)
|
||||
) {
|
||||
let hasMachOSliceHeader = false;
|
||||
for (const declaration of declarations.slices) {
|
||||
if (
|
||||
validateFatSlice(
|
||||
declaration,
|
||||
size,
|
||||
8 + count * (wide ? 32 : 20),
|
||||
) !== null
|
||||
)
|
||||
continue;
|
||||
const bytes = await readAt(declaration.offset, 4);
|
||||
if (bytes.byteLength < 4) continue;
|
||||
const sliceMagic = viewOf(bytes).getUint32(0, false);
|
||||
if (
|
||||
[MH_MAGIC, MH_MAGIC_64, MH_CIGAM, MH_CIGAM_64].includes(sliceMagic)
|
||||
) {
|
||||
hasMachOSliceHeader = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!hasMachOSliceHeader) return { status: "not-mach-o" };
|
||||
let header = readFatContainerHeader(head, size);
|
||||
if (header.state !== "not-fat") {
|
||||
if (header.state === "needs-data") {
|
||||
header = readFatContainerHeader(
|
||||
await readAt(0, header.requiredBytes),
|
||||
size,
|
||||
);
|
||||
}
|
||||
if (header.state === "not-fat") return { status: "not-mach-o" };
|
||||
if (header.state === "needs-data")
|
||||
throw new MachoFormatIssue("malformed", "FAT table is truncated");
|
||||
if (header.state === "malformed")
|
||||
throw new MachoFormatIssue("malformed", header.reason);
|
||||
let identity = classifyFatContainerIdentity(header, () => undefined);
|
||||
if (identity.state === "needs-slice-header") {
|
||||
const sliceHeaders = new Map<number, number | null>();
|
||||
for (const offset of identity.offsets) {
|
||||
const bytes = await readAt(offset, 4);
|
||||
sliceHeaders.set(
|
||||
offset,
|
||||
bytes.byteLength < 4 ? null : viewOf(bytes).getUint32(0, false),
|
||||
);
|
||||
}
|
||||
identity = classifyFatContainerIdentity(header, (offset) =>
|
||||
sliceHeaders.get(offset),
|
||||
);
|
||||
}
|
||||
if (identity.state === "not-mach-o") return { status: "not-mach-o" };
|
||||
if (identity.state === "malformed")
|
||||
throw new MachoFormatIssue(identity.category, identity.reason);
|
||||
if (identity.state === "needs-slice-header")
|
||||
return { status: "not-mach-o" };
|
||||
return {
|
||||
status: "parsed",
|
||||
slices: await readFatSlices(
|
||||
readAt,
|
||||
size,
|
||||
8 + count * (wide ? 32 : 20),
|
||||
declarations.slices,
|
||||
),
|
||||
slices: await readFatSlices(readAt, header.slices),
|
||||
};
|
||||
}
|
||||
if (magic === MH_CIGAM || magic === MH_CIGAM_64)
|
||||
@@ -228,25 +195,17 @@ export const readMachoImage = async (
|
||||
|
||||
const readFatSlices = async (
|
||||
readAt: ReadAt,
|
||||
size: number,
|
||||
tableEnd: number,
|
||||
declarations: readonly FatSliceDeclaration[],
|
||||
): Promise<MachoSlice[]> => {
|
||||
const slices: MachoSlice[] = [];
|
||||
for (const declaration of declarations) {
|
||||
const { offset, size: length, cpuType, cpuSubtype } = declaration;
|
||||
const rangeIssue = validateFatSlice(declaration, size, tableEnd);
|
||||
if (rangeIssue !== null)
|
||||
throw new MachoFormatIssue(
|
||||
rangeIssue.includes("unsupported") ? "unsupported" : "malformed",
|
||||
rangeIssue,
|
||||
);
|
||||
const slice = await readSlice(readAt, offset, length, {
|
||||
fatCpuType: cpuType,
|
||||
fatCpuSubtype: cpuSubtype,
|
||||
alignmentExponent: declaration.alignmentExponent,
|
||||
});
|
||||
const identityIssue = validateFatSlice(declaration, size, tableEnd, {
|
||||
const identityIssue = validateFatSliceIdentity(declaration, {
|
||||
cpuType: slice.cpu_type,
|
||||
cpuSubtype: slice.cpu_subtype,
|
||||
});
|
||||
@@ -524,13 +483,12 @@ const CPU_ARCH_ABI64 = 0x01000000;
|
||||
const CPU_ARCH_ABI64_32 = 0x02000000;
|
||||
const CPU_TYPE_X86 = 7;
|
||||
const CPU_TYPE_ARM = 12;
|
||||
const CPU_SUBTYPE_MASK = 0xff000000;
|
||||
const CPU_SUBTYPE_ARM64E = 2;
|
||||
const CPU_SUBTYPE_ARM64E_X1 = 12;
|
||||
const CPU_SUBTYPE_X86_64_H = 8;
|
||||
|
||||
const architectureName = (cpuType: number, cpuSubtype: number): string => {
|
||||
const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
|
||||
const subtype = machoCpuSubtypeBase(cpuSubtype);
|
||||
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
|
||||
// Both pointer-authentication subtypes belong to the arm64e family.
|
||||
return subtype === CPU_SUBTYPE_ARM64E || subtype === CPU_SUBTYPE_ARM64E_X1
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { hasNibArchiveSignature } from "../../domain/apple/appleArchiveFormat.js";
|
||||
import { TextDecoder } from "node:util";
|
||||
import {
|
||||
InterfaceBuilderDecodeBudget,
|
||||
InterfaceBuilderDecodeBudgetExceeded,
|
||||
} from "./InterfaceBuilderDecodeBudget.js";
|
||||
|
||||
const MAGIC = Buffer.from("NIBArchive", "ascii");
|
||||
const DEFAULT_DECODE_BUDGET_BYTES = 128 * 1024 * 1024;
|
||||
|
||||
interface NibObjectRecord {
|
||||
@@ -39,7 +39,7 @@ export const decodeNibArchive = (
|
||||
bytes: Buffer,
|
||||
budget = new InterfaceBuilderDecodeBudget(DEFAULT_DECODE_BUDGET_BYTES),
|
||||
): NibArchiveDocument => {
|
||||
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
|
||||
if (bytes.length < 50 || !hasNibArchiveSignature(bytes))
|
||||
throw new TypeError("NIBArchive magic or header is invalid");
|
||||
|
||||
const formatVersion = readU32(bytes, 10);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PlistNumberLiterals } from "../../domain/apple/plistNumbers.js";
|
||||
import { decodeXmlText } from "../../domain/propertyListKeys.js";
|
||||
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
|
||||
|
||||
const collector = () => {
|
||||
const integers = new Map<number, Set<string>>();
|
||||
@@ -124,10 +125,7 @@ export const binaryPlistNumberLiterals = (
|
||||
bytes: Buffer,
|
||||
): PlistNumberLiterals => {
|
||||
const output = collector();
|
||||
if (
|
||||
bytes.length < 40 ||
|
||||
bytes.subarray(0, 8).toString("ascii") !== "bplist00"
|
||||
)
|
||||
if (bytes.length < 40 || !hasBinaryPlistSignature(bytes))
|
||||
return output.result(true);
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const trailer = bytes.length - 32;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
|
||||
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
|
||||
import {
|
||||
artifactEdgeId,
|
||||
artifactIdForContent,
|
||||
@@ -18,7 +19,14 @@ import {
|
||||
zipPackageFormatForPath,
|
||||
type ZipPackageFormat,
|
||||
} from "../../domain/zipPackageFormat.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
|
||||
import {
|
||||
observeMzWindowsHeader,
|
||||
parseDosMzHeader,
|
||||
} from "../../domain/dosMz.js";
|
||||
import {
|
||||
classifyFatContainerIdentity,
|
||||
readFatContainerHeader,
|
||||
} from "../../domain/apple/machoContainer.js";
|
||||
import {
|
||||
nesContainerFormat,
|
||||
parseInesLayout,
|
||||
@@ -445,11 +453,11 @@ export const classifyArtifactBytes = (
|
||||
)
|
||||
return "ines";
|
||||
if (hasZipSignature(prefix)) return "zip";
|
||||
if (prefix.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist";
|
||||
if (hasBinaryPlistSignature(prefix)) return "plist";
|
||||
const fatFormat = classifyFatArtifact(prefix, fileSize);
|
||||
if (fatFormat !== null) return fatFormat;
|
||||
if (prefix.length >= 4) {
|
||||
const magic = prefix.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
|
||||
return "mach-o-universal";
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
|
||||
return "mach-o";
|
||||
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
|
||||
@@ -462,22 +470,40 @@ export const classifyArtifactBytes = (
|
||||
prefix.length < Math.min(fileSize, 64)
|
||||
)
|
||||
return "unknown";
|
||||
const windowsOffset = mzWindowsHeaderOffset(prefix);
|
||||
if (windowsOffset !== null) {
|
||||
const windowsHeader = observeMzWindowsHeader(prefix, fileSize);
|
||||
if (windowsHeader.state === "signature-needed") return "unknown";
|
||||
if (windowsHeader.state === "declared") {
|
||||
const windowsOffset = windowsHeader.offset;
|
||||
if (
|
||||
windowsHeader.signature === "PE" &&
|
||||
windowsOffset >= 64 &&
|
||||
windowsOffset <= prefix.length - 4 &&
|
||||
prefix
|
||||
.subarray(windowsOffset, windowsOffset + 4)
|
||||
.equals(Buffer.from([0x50, 0x45, 0, 0]))
|
||||
windowsOffset <= prefix.length - 4
|
||||
)
|
||||
return "pe";
|
||||
} else if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
|
||||
return "unknown";
|
||||
}
|
||||
if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
|
||||
return "unknown";
|
||||
}
|
||||
return "file";
|
||||
};
|
||||
|
||||
const classifyFatArtifact = (
|
||||
prefix: Buffer,
|
||||
fileSize: number,
|
||||
): ArtifactNode["format"] | null => {
|
||||
const fatHeader = readFatContainerHeader(prefix, fileSize);
|
||||
if (fatHeader.state === "needs-data" || fatHeader.state === "malformed")
|
||||
return "unknown";
|
||||
if (fatHeader.state === "not-fat") return null;
|
||||
const identity = classifyFatContainerIdentity(fatHeader, (offset) => {
|
||||
if (offset >= prefix.length) return undefined;
|
||||
if (offset + 4 > prefix.length) return null;
|
||||
return prefix.readUInt32BE(offset);
|
||||
});
|
||||
return identity.state === "mach-o" ? "mach-o-universal" : "unknown";
|
||||
};
|
||||
|
||||
const relationFor = (path: string): ArtifactEdge["relation"] => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.endsWith(".map")) return "maps-source";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
artifactInventoryOutputSchema,
|
||||
type ArtifactInventoryOutput,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import { abortIfNeeded } from "../ArtifactHash.js";
|
||||
import { scanCanonicalArtifactInventoryInScope } from "./scanCanonical.js";
|
||||
@@ -13,9 +13,9 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySn
|
||||
export const inventoryArtifact = async (
|
||||
inputPath: string,
|
||||
options: ArtifactInventoryOptions,
|
||||
): Promise<ArtifactInventoryResult> => {
|
||||
): Promise<ArtifactInventoryOutput> => {
|
||||
const snapshot = await scanArtifactInventory(inputPath, options);
|
||||
return artifactInventoryResultSchema.parse(snapshot);
|
||||
return artifactInventoryOutputSchema.parse(snapshot);
|
||||
};
|
||||
|
||||
/** Scan an artifact once and retain the complete immutable graph for projection. */
|
||||
|
||||
@@ -6,7 +6,11 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
|
||||
import type {
|
||||
ArtifactInventoryCoverage,
|
||||
ArtifactOccurrence,
|
||||
IntegrityContradiction,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
isZipPackageFormat,
|
||||
ZIP_NON_ENTRY_TAIL_LIMITATION,
|
||||
@@ -45,21 +49,43 @@ export const createReader = (
|
||||
}
|
||||
};
|
||||
|
||||
export const inventoryLimitations = (
|
||||
/** Classify source coverage and preserve its user-facing explanation once. */
|
||||
export const inventoryAssessment = (
|
||||
format: ArtifactOccurrence["artifact_format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
): string[] => {
|
||||
if (format === "ines") return [INES_LIMITATION];
|
||||
if (reader !== undefined)
|
||||
return isZipPackageFormat(reader.format)
|
||||
? [ZIP_NON_ENTRY_TAIL_LIMITATION]
|
||||
: [];
|
||||
// dmg and pkg reach here only after classifyRootFormat matched their bytes.
|
||||
if (format === "dmg" || format === "pkg")
|
||||
return [
|
||||
integrityContradictions: readonly IntegrityContradiction[],
|
||||
caseCollisionLimitation: string | undefined,
|
||||
): {
|
||||
readonly coverage_status: ArtifactInventoryCoverage;
|
||||
readonly limitations: string[];
|
||||
} => {
|
||||
let coverageStatus: ArtifactInventoryCoverage = "complete";
|
||||
const limitations: string[] = [];
|
||||
if (format === "ines") limitations.push(INES_LIMITATION);
|
||||
if (reader !== undefined) {
|
||||
if (isZipPackageFormat(reader.format))
|
||||
limitations.push(ZIP_NON_ENTRY_TAIL_LIMITATION);
|
||||
} else if (format === "dmg" || format === "pkg") {
|
||||
coverageStatus = "partial";
|
||||
limitations.push(
|
||||
`${format.toUpperCase()} root hash is observed; child inventory requires a native macOS adapter.`,
|
||||
];
|
||||
if (format === "mach-o-universal" && process.platform !== "darwin")
|
||||
return ["Universal Mach-O slices require the native macOS lipo adapter."];
|
||||
return ["Artifact has no child container entries."];
|
||||
);
|
||||
} else if (format === "mach-o-universal" && process.platform !== "darwin") {
|
||||
coverageStatus = "partial";
|
||||
limitations.push(
|
||||
"Universal Mach-O slices require the native macOS lipo adapter.",
|
||||
);
|
||||
} else {
|
||||
// The graph's modeled scope is the root itself for recognized leaf formats.
|
||||
limitations.push("Artifact has no child container entries.");
|
||||
}
|
||||
if (caseCollisionLimitation !== undefined) {
|
||||
coverageStatus = "partial";
|
||||
limitations.push(caseCollisionLimitation);
|
||||
}
|
||||
if (integrityContradictions.length > 0)
|
||||
limitations.push(
|
||||
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
|
||||
);
|
||||
return { coverage_status: coverageStatus, limitations };
|
||||
};
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
hashStableRootArtifact,
|
||||
hashStableRootArtifactHandle,
|
||||
} from "./hashStableRootArtifact.js";
|
||||
import { createReader, inventoryLimitations } from "./reader.js";
|
||||
import { createReader, inventoryAssessment } from "./reader.js";
|
||||
import {
|
||||
scanReader,
|
||||
type PendingIntegrityContradiction,
|
||||
@@ -269,6 +269,12 @@ const buildInventorySnapshot = async (
|
||||
orderedOccurrences,
|
||||
orderedEdges,
|
||||
});
|
||||
const assessment = inventoryAssessment(
|
||||
rootFormat,
|
||||
reader,
|
||||
integrityContradictions,
|
||||
input.caseCollisionLimitation,
|
||||
);
|
||||
return {
|
||||
manifest,
|
||||
...(reader instanceof InesArtifactReader && rootDigest !== null
|
||||
@@ -279,12 +285,8 @@ const buildInventorySnapshot = async (
|
||||
edges: orderedEdges,
|
||||
provenance: reader?.provenance() ?? [],
|
||||
integrity_contradictions: integrityContradictions,
|
||||
limitations: buildLimitations(
|
||||
rootFormat,
|
||||
reader,
|
||||
integrityContradictions,
|
||||
input.caseCollisionLimitation,
|
||||
),
|
||||
coverage_status: assessment.coverage_status,
|
||||
limitations: assessment.limitations,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -397,18 +399,3 @@ const buildManifest = ({
|
||||
occurrence_count: orderedOccurrences.length,
|
||||
edge_count: orderedEdges.length,
|
||||
});
|
||||
|
||||
const buildLimitations = (
|
||||
rootFormat: ArtifactOccurrence["artifact_format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
integrityContradictions: readonly IntegrityContradiction[],
|
||||
caseCollisionLimitation: string | undefined,
|
||||
): string[] => [
|
||||
...inventoryLimitations(rootFormat, reader),
|
||||
...(caseCollisionLimitation === undefined ? [] : [caseCollisionLimitation]),
|
||||
...(integrityContradictions.length === 0
|
||||
? []
|
||||
: [
|
||||
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
|
||||
]),
|
||||
];
|
||||
|
||||
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
|
||||
import { constants, type BigIntStats } from "node:fs";
|
||||
import { lstat, open, type FileHandle } from "node:fs/promises";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import type { ArtifactResourceScope } from "./ArtifactResourceScope.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
|
||||
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
|
||||
export interface StableArtifactFileSystem {
|
||||
@@ -42,6 +44,7 @@ export const readStableArtifact = async (
|
||||
maximumBytes: number,
|
||||
signal?: AbortSignal,
|
||||
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
|
||||
resourceScope?: ArtifactResourceScope,
|
||||
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
|
||||
signal?.throwIfAborted();
|
||||
const before = await fileSystem.lstat(path);
|
||||
@@ -61,6 +64,9 @@ export const readStableArtifact = async (
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
),
|
||||
);
|
||||
const owner =
|
||||
resourceScope === undefined ? undefined : new OwnedFileHandle(file);
|
||||
let failure: unknown;
|
||||
try {
|
||||
const initial = await file.stat({ bigint: true });
|
||||
if (
|
||||
@@ -116,7 +122,22 @@ export const readStableArtifact = async (
|
||||
);
|
||||
const bytes = Buffer.concat(chunks, count);
|
||||
return { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
throw cause;
|
||||
} finally {
|
||||
await file.close();
|
||||
if (owner === undefined || resourceScope === undefined) await file.close();
|
||||
else {
|
||||
const cleanup = await resourceScope.release({
|
||||
kind: "file-handle",
|
||||
resource: path,
|
||||
handle: owner,
|
||||
});
|
||||
if (cleanup.kind === "failed")
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
failure ?? cleanup.cause,
|
||||
ArtifactReaderFailure.cleanupObservation(cleanup.cause, path),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -80,6 +80,49 @@ const baseScenario = () => ({
|
||||
},
|
||||
});
|
||||
|
||||
describe("browser scenario secret redaction", () => {
|
||||
it("matches percent-escape hex case without case-folding raw secrets", () => {
|
||||
const secrets = BrowserScenarioSecrets.resolve(
|
||||
browserScenarioSchema.parse(baseScenario()),
|
||||
{
|
||||
REA_TEST_SESSION: "a/b?",
|
||||
REA_TEST_PASSWORD: "password",
|
||||
REA_TEST_COOKIE: "cookie",
|
||||
},
|
||||
);
|
||||
if (secrets === undefined) throw new Error("Expected resolved secrets");
|
||||
|
||||
expect(secrets.redact("logged a%2fb%3f, a%2Fb%3F and a%2fb%3F")).toBe(
|
||||
"logged [REDACTED:session], [REDACTED:session] and [REDACTED:session]",
|
||||
);
|
||||
expect(secrets.redact("raw A/B? remains case-sensitive")).toBe(
|
||||
"raw A/B? remains case-sensitive",
|
||||
);
|
||||
expect(
|
||||
secrets.redactBytes(
|
||||
Buffer.concat([
|
||||
Buffer.from([0xff, 0]),
|
||||
Buffer.from("a%2fb%3F"),
|
||||
Buffer.from([0x80]),
|
||||
]),
|
||||
),
|
||||
).toEqual(
|
||||
Buffer.concat([
|
||||
Buffer.from([0xff, 0]),
|
||||
Buffer.from("[REDACTED:session]"),
|
||||
Buffer.from([0x80]),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
secrets.sanitizeUrl("https://app.example.test/?token=a%2fb%3F").url,
|
||||
).toBe("https://app.example.test/?token=[REDACTED:session]");
|
||||
expect(secrets.fingerprint("stored a%2fb%3F")).toEqual({
|
||||
value_state: "redacted-secret",
|
||||
value_sha256: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
|
||||
@@ -89,6 +89,7 @@ export const browserScenarioCaptureData = (input: {
|
||||
.map(({ secret_id: id }) => id)
|
||||
.sort(),
|
||||
network_content: input.scenario.capture.network,
|
||||
event_families: [...new Set(input.scenario.capture.events)].sort(),
|
||||
},
|
||||
duration_ms: Date.now() - input.startedAt,
|
||||
steps: [...input.steps],
|
||||
|
||||
@@ -15,84 +15,229 @@ const REDACTION_PREFIX = "[REDACTED:";
|
||||
|
||||
const encodedSecretValues = (secret: string): ReadonlySet<string> =>
|
||||
new Set([
|
||||
secret,
|
||||
encodeURIComponent(secret),
|
||||
new URLSearchParams([["value", secret]]).toString().slice("value=".length),
|
||||
]);
|
||||
|
||||
type SecretSpellings = "raw" | "url" | "bytes";
|
||||
type SecretSpellings = "url" | "text";
|
||||
interface SecretPattern {
|
||||
readonly text: string;
|
||||
readonly searchText: string;
|
||||
readonly percentInsensitive: boolean;
|
||||
}
|
||||
interface SecretReplacement extends SecretPattern {
|
||||
readonly id: string;
|
||||
}
|
||||
interface SecretNeedle {
|
||||
readonly id: string;
|
||||
readonly needle: Buffer;
|
||||
readonly percentInsensitive: boolean;
|
||||
readonly marker: Buffer;
|
||||
}
|
||||
|
||||
const secretSpellings = (
|
||||
secret: string,
|
||||
spellings: SecretSpellings,
|
||||
): readonly string[] => {
|
||||
if (secret === "") return [];
|
||||
if (spellings === "raw") return [secret];
|
||||
const values = [...encodedSecretValues(secret)];
|
||||
if (spellings === "bytes") values.push(JSON.stringify(secret).slice(1, -1));
|
||||
return [...new Set(values)].filter((value) => value !== "");
|
||||
const normalizePercentEscapes = (value: string): string => {
|
||||
if (!value.includes("%")) return value;
|
||||
return value.replace(/%[0-9a-f]{2}/giu, (escape) => escape.toLowerCase());
|
||||
};
|
||||
|
||||
const declaredLiterals = (
|
||||
const secretPatterns = (
|
||||
secret: string,
|
||||
spellings: SecretSpellings,
|
||||
): readonly SecretPattern[] => {
|
||||
if (secret === "") return [];
|
||||
const patterns: SecretPattern[] = [
|
||||
{ text: secret, searchText: secret, percentInsensitive: false },
|
||||
...[...encodedSecretValues(secret)].map((text) => ({
|
||||
text,
|
||||
searchText: normalizePercentEscapes(text),
|
||||
percentInsensitive: true,
|
||||
})),
|
||||
];
|
||||
if (spellings === "text")
|
||||
patterns.push({
|
||||
text: JSON.stringify(secret).slice(1, -1),
|
||||
searchText: JSON.stringify(secret).slice(1, -1),
|
||||
percentInsensitive: false,
|
||||
});
|
||||
const seen = new Set<string>();
|
||||
return patterns.filter(({ text, percentInsensitive }) => {
|
||||
if (text === "") return false;
|
||||
const key = `${percentInsensitive ? "percent" : "literal"}:${text}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
const declaredPatterns = (
|
||||
values: ReadonlyMap<string, string>,
|
||||
spellings: SecretSpellings,
|
||||
): readonly string[] => [
|
||||
...new Set(
|
||||
[...values.values()].flatMap((secret) =>
|
||||
secretSpellings(secret, spellings),
|
||||
),
|
||||
),
|
||||
];
|
||||
): readonly SecretPattern[] => {
|
||||
const seen = new Set<string>();
|
||||
return [...values.values()]
|
||||
.flatMap((secret) => secretPatterns(secret, spellings))
|
||||
.filter(({ text, percentInsensitive }) => {
|
||||
const key = `${percentInsensitive ? "percent" : "literal"}:${text}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
/** Pick a marker that does not itself contain a declared secret spelling. */
|
||||
const redactionMarker = (id: string, literals: readonly string[]): string =>
|
||||
[`${REDACTION_PREFIX}${id}]`, "[REDACTED]", "…", ""].find((candidate) =>
|
||||
literals.every((literal) => !candidate.includes(literal)),
|
||||
) ?? "";
|
||||
|
||||
const replaceSecretLiterals = (
|
||||
value: string,
|
||||
const secretReplacements = (
|
||||
values: ReadonlyMap<string, string>,
|
||||
spellings: SecretSpellings,
|
||||
literals: readonly string[],
|
||||
): string => {
|
||||
const replacements = [...values]
|
||||
): readonly SecretReplacement[] =>
|
||||
[...values]
|
||||
.flatMap(([id, secret]) =>
|
||||
secretSpellings(secret, spellings).map((text) => ({ id, text })),
|
||||
secretPatterns(secret, spellings).map((pattern) => ({ id, ...pattern })),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.text.length - left.text.length ||
|
||||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
|
||||
);
|
||||
let output = value;
|
||||
for (const replacement of replacements)
|
||||
output = output.replaceAll(
|
||||
replacement.text,
|
||||
redactionMarker(replacement.id, literals),
|
||||
);
|
||||
return output;
|
||||
|
||||
const normalizePercentEscapesBytes = (value: Buffer): Buffer => {
|
||||
if (value.indexOf(37) < 0) return value;
|
||||
const normalized = Buffer.from(value);
|
||||
for (let index = 0; index + 2 < normalized.length; index += 1)
|
||||
if (
|
||||
normalized[index] === 37 &&
|
||||
isHexByte(normalized[index + 1]) &&
|
||||
isHexByte(normalized[index + 2])
|
||||
) {
|
||||
normalized[index + 1] = lowercaseHexByte(normalized[index + 1]!);
|
||||
normalized[index + 2] = lowercaseHexByte(normalized[index + 2]!);
|
||||
index += 2;
|
||||
}
|
||||
return normalized;
|
||||
};
|
||||
|
||||
const isHexByte = (value: number | undefined): boolean =>
|
||||
value !== undefined &&
|
||||
((value >= 48 && value <= 57) ||
|
||||
(value >= 65 && value <= 70) ||
|
||||
(value >= 97 && value <= 102));
|
||||
|
||||
const lowercaseHexByte = (value: number): number =>
|
||||
value >= 65 && value <= 70 ? value + 32 : value;
|
||||
|
||||
const patternMatches = (
|
||||
value: string,
|
||||
normalizedValue: string,
|
||||
pattern: SecretPattern,
|
||||
): boolean =>
|
||||
(pattern.percentInsensitive ? normalizedValue : value).includes(
|
||||
pattern.searchText,
|
||||
);
|
||||
|
||||
const containsSecretPattern = (
|
||||
value: string,
|
||||
normalizedValue: string,
|
||||
patterns: readonly SecretPattern[],
|
||||
): boolean => {
|
||||
if (patterns.length === 0) return false;
|
||||
return patterns.some((pattern) =>
|
||||
patternMatches(value, normalizedValue, pattern),
|
||||
);
|
||||
};
|
||||
|
||||
const containsSecretBytePattern = (
|
||||
value: Buffer,
|
||||
normalizedValue: Buffer,
|
||||
needles: readonly SecretNeedle[],
|
||||
): boolean =>
|
||||
needles.some((needle) =>
|
||||
(needle.percentInsensitive ? normalizedValue : value).includes(
|
||||
needle.needle,
|
||||
),
|
||||
);
|
||||
|
||||
/** Pick a marker that does not itself contain a declared secret spelling. */
|
||||
const redactionMarker = (
|
||||
id: string,
|
||||
patterns: readonly SecretPattern[],
|
||||
): string => {
|
||||
const candidates = [`${REDACTION_PREFIX}${id}]`, "[REDACTED]", "…", ""];
|
||||
return (
|
||||
candidates.find((candidate) =>
|
||||
patterns.every(
|
||||
(pattern) =>
|
||||
!patternMatches(
|
||||
candidate,
|
||||
normalizePercentEscapes(candidate),
|
||||
pattern,
|
||||
),
|
||||
),
|
||||
) ?? ""
|
||||
);
|
||||
};
|
||||
|
||||
const replaceSecretLiterals = (
|
||||
value: string,
|
||||
replacements: readonly SecretReplacement[],
|
||||
patterns: readonly SecretPattern[],
|
||||
): string => {
|
||||
const normalizedValue = replacements.some(
|
||||
({ percentInsensitive }) => percentInsensitive,
|
||||
)
|
||||
? normalizePercentEscapes(value)
|
||||
: value;
|
||||
const parts: string[] = [];
|
||||
let offset = 0;
|
||||
while (offset < value.length) {
|
||||
let next:
|
||||
| ((typeof replacements)[number] & { readonly index: number })
|
||||
| undefined;
|
||||
for (const replacement of replacements) {
|
||||
const search = replacement.searchText;
|
||||
const view = replacement.percentInsensitive ? normalizedValue : value;
|
||||
const index = view.indexOf(search, offset);
|
||||
if (
|
||||
index >= 0 &&
|
||||
(next === undefined ||
|
||||
index < next.index ||
|
||||
(index === next.index && replacement.text.length > next.text.length))
|
||||
)
|
||||
next = { ...replacement, index };
|
||||
}
|
||||
if (next === undefined) break;
|
||||
const marker = redactionMarker(next.id, patterns);
|
||||
parts.push(value.slice(offset, next.index), marker);
|
||||
offset = next.index + next.text.length;
|
||||
}
|
||||
if (parts.length === 0) return value;
|
||||
parts.push(value.slice(offset));
|
||||
return parts.join("");
|
||||
};
|
||||
|
||||
const secretNeedles = (
|
||||
values: ReadonlyMap<string, string>,
|
||||
literals: readonly string[],
|
||||
): Array<{
|
||||
readonly id: string;
|
||||
readonly needle: Buffer;
|
||||
readonly marker: Buffer;
|
||||
}> =>
|
||||
[...values].flatMap(([id, secret]) =>
|
||||
secretSpellings(secret, "bytes").map((text) => ({
|
||||
id,
|
||||
needle: Buffer.from(text),
|
||||
marker: Buffer.from(redactionMarker(id, literals)),
|
||||
})),
|
||||
);
|
||||
replacements: readonly SecretReplacement[],
|
||||
patterns: readonly SecretPattern[],
|
||||
): SecretNeedle[] =>
|
||||
replacements.map((pattern) => ({
|
||||
id: pattern.id,
|
||||
needle: Buffer.from(pattern.searchText),
|
||||
percentInsensitive: pattern.percentInsensitive,
|
||||
marker: Buffer.from(redactionMarker(pattern.id, patterns)),
|
||||
}));
|
||||
|
||||
/** Resolved secret values kept only for one in-memory scenario session. */
|
||||
export class BrowserScenarioSecrets {
|
||||
private constructor(private readonly values: ReadonlyMap<string, string>) {}
|
||||
private readonly urlPatterns: readonly SecretPattern[];
|
||||
private readonly textPatterns: readonly SecretPattern[];
|
||||
private readonly urlReplacements: readonly SecretReplacement[];
|
||||
private readonly textReplacements: readonly SecretReplacement[];
|
||||
private readonly textNeedles: readonly SecretNeedle[];
|
||||
|
||||
private constructor(private readonly values: ReadonlyMap<string, string>) {
|
||||
this.urlPatterns = declaredPatterns(values, "url");
|
||||
this.textPatterns = declaredPatterns(values, "text");
|
||||
this.urlReplacements = secretReplacements(values, "url");
|
||||
this.textReplacements = secretReplacements(values, "text");
|
||||
this.textNeedles = secretNeedles(this.textReplacements, this.textPatterns);
|
||||
}
|
||||
|
||||
static resolve(
|
||||
scenario: BrowserScenario,
|
||||
@@ -127,18 +272,40 @@ export class BrowserScenarioSecrets {
|
||||
}
|
||||
|
||||
redact(value: string): string {
|
||||
const literals = declaredLiterals(this.values, "raw");
|
||||
const output = replaceSecretLiterals(value, this.values, "raw", literals);
|
||||
return literals.some((literal) => output.includes(literal)) ? "" : output;
|
||||
const patterns = this.textPatterns;
|
||||
if (patterns.length === 0) return value;
|
||||
const output = replaceSecretLiterals(
|
||||
value,
|
||||
this.textReplacements,
|
||||
patterns,
|
||||
);
|
||||
return containsSecretPattern(
|
||||
output,
|
||||
normalizePercentEscapes(output),
|
||||
patterns,
|
||||
)
|
||||
? ""
|
||||
: output;
|
||||
}
|
||||
|
||||
/** Replace declared UTF-8, URI/form, and JSON-escaped secrets without decoding binary data. */
|
||||
/** Replace declared UTF-8, URI/form, and JSON-escaped secret spellings. */
|
||||
redactBytes(value: Buffer): Buffer {
|
||||
const literals = declaredLiterals(this.values, "bytes");
|
||||
const candidates = secretNeedles(this.values, literals)
|
||||
const patterns = this.textPatterns;
|
||||
if (patterns.length === 0) return value;
|
||||
const candidates = this.textNeedles;
|
||||
const hasPercentPatterns = candidates.some(
|
||||
({ percentInsensitive }) => percentInsensitive,
|
||||
);
|
||||
const normalizedValue =
|
||||
hasPercentPatterns && value.indexOf(37) >= 0
|
||||
? normalizePercentEscapesBytes(value)
|
||||
: value;
|
||||
const sortedCandidates = candidates
|
||||
.map((candidate) => ({
|
||||
...candidate,
|
||||
index: value.indexOf(candidate.needle),
|
||||
index: (candidate.percentInsensitive ? normalizedValue : value).indexOf(
|
||||
candidate.needle,
|
||||
),
|
||||
}))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
@@ -148,13 +315,18 @@ export class BrowserScenarioSecrets {
|
||||
const parts: Buffer[] = [];
|
||||
let offset = 0;
|
||||
while (true) {
|
||||
let next: (typeof candidates)[number] | undefined;
|
||||
for (const candidate of candidates) {
|
||||
let next: (typeof sortedCandidates)[number] | undefined;
|
||||
for (const candidate of sortedCandidates) {
|
||||
if (candidate.index >= 0 && candidate.index < offset)
|
||||
candidate.index = value.indexOf(candidate.needle, offset);
|
||||
candidate.index = (
|
||||
candidate.percentInsensitive ? normalizedValue : value
|
||||
).indexOf(candidate.needle, offset);
|
||||
if (
|
||||
candidate.index >= 0 &&
|
||||
(next === undefined || candidate.index < next.index)
|
||||
(next === undefined ||
|
||||
candidate.index < next.index ||
|
||||
(candidate.index === next.index &&
|
||||
candidate.needle.length > next.needle.length))
|
||||
)
|
||||
next = candidate;
|
||||
}
|
||||
@@ -165,16 +337,23 @@ export class BrowserScenarioSecrets {
|
||||
if (parts.length === 0) return value;
|
||||
parts.push(value.subarray(offset));
|
||||
const redacted = Buffer.concat(parts);
|
||||
return literals.some((literal) => redacted.includes(Buffer.from(literal)))
|
||||
const normalizedRedacted =
|
||||
hasPercentPatterns && redacted.indexOf(37) >= 0
|
||||
? normalizePercentEscapesBytes(redacted)
|
||||
: redacted;
|
||||
return containsSecretBytePattern(redacted, normalizedRedacted, candidates)
|
||||
? Buffer.alloc(0)
|
||||
: redacted;
|
||||
}
|
||||
|
||||
/** Remove only declared secret values from one URL and report that action. */
|
||||
sanitizeUrl(value: string): SanitizedBrowserUrl {
|
||||
const literals = declaredLiterals(this.values, "url");
|
||||
const output = replaceSecretLiterals(value, this.values, "url", literals);
|
||||
if (literals.some((literal) => output.includes(literal)))
|
||||
const patterns = this.urlPatterns;
|
||||
if (patterns.length === 0) return sanitizeBrowserUrl(value);
|
||||
const output = replaceSecretLiterals(value, this.urlReplacements, patterns);
|
||||
if (
|
||||
containsSecretPattern(output, normalizePercentEscapes(output), patterns)
|
||||
)
|
||||
return {
|
||||
url: "",
|
||||
origin: null,
|
||||
@@ -189,14 +368,15 @@ export class BrowserScenarioSecrets {
|
||||
}
|
||||
|
||||
fingerprint(value: string): BrowserStorageValueFingerprint {
|
||||
for (const secret of this.values.values())
|
||||
if (secret !== "" && value.includes(secret))
|
||||
return { value_state: "redacted-secret", value_sha256: null };
|
||||
const patterns = this.textPatterns;
|
||||
if (
|
||||
patterns.length > 0 &&
|
||||
containsSecretPattern(value, normalizePercentEscapes(value), patterns)
|
||||
)
|
||||
return { value_state: "redacted-secret", value_sha256: null };
|
||||
return {
|
||||
value_state: "hashed",
|
||||
value_sha256: createHash("sha256")
|
||||
.update(this.redact(value))
|
||||
.digest("hex"),
|
||||
value_sha256: createHash("sha256").update(value).digest("hex"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+96
-17
@@ -1,4 +1,4 @@
|
||||
import { request } from "node:http";
|
||||
import { request, type ClientRequest, type IncomingMessage } from "node:http";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -7,6 +7,7 @@ import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import { urlDeclaresQueryOrFragment } from "../domain/urlComponents.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
@@ -28,6 +29,17 @@ const endpointTargetSchema = z.object({
|
||||
});
|
||||
const endpointTargetsSchema = z.array(endpointTargetSchema);
|
||||
|
||||
/** Per-response bounds for loopback CDP discovery documents. */
|
||||
const CDP_DISCOVERY_RESPONSE_LIMITS = {
|
||||
bytes: 8 * 1024 * 1024,
|
||||
timeoutMs: 10_000,
|
||||
} as const;
|
||||
|
||||
interface CdpDiscoveryResponseLimits {
|
||||
readonly bytes: number;
|
||||
readonly timeoutMs: number;
|
||||
}
|
||||
|
||||
/** Validated direct CDP WebSocket bound to one discovered page target. */
|
||||
interface CdpPageWebSocketEndpoint {
|
||||
readonly scope: "page";
|
||||
@@ -230,8 +242,7 @@ const safeCdpWebSocketEndpoint = (
|
||||
parsed.port !== trustedEndpoint.port ||
|
||||
parsed.username !== "" ||
|
||||
parsed.password !== "" ||
|
||||
parsed.search !== "" ||
|
||||
parsed.hash !== "" ||
|
||||
urlDeclaresQueryOrFragment(parsed) ||
|
||||
path === undefined
|
||||
)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
||||
@@ -291,29 +302,71 @@ export const readCdpJson = async (
|
||||
url: URL,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
limits: CdpDiscoveryResponseLimits = CDP_DISCOVERY_RESPONSE_LIMITS,
|
||||
): Promise<unknown> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
if (signal?.aborted === true) {
|
||||
reject(new AnalysisCancelledError(operation));
|
||||
return;
|
||||
}
|
||||
const request_ = request(
|
||||
let response: IncomingMessage | undefined;
|
||||
let request_: ClientRequest | undefined;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
let settled = false;
|
||||
const removeAbort = (): void =>
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
const finish = (error?: Error, value?: unknown): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
removeAbort();
|
||||
if (error !== undefined) {
|
||||
reject(error);
|
||||
response?.destroy();
|
||||
request_?.destroy();
|
||||
} else resolve(value);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (signal?.aborted === true)
|
||||
finish(new AnalysisCancelledError(operation));
|
||||
};
|
||||
request_ = request(
|
||||
url,
|
||||
{ method: "GET", signal, headers: { Accept: "application/json" } },
|
||||
(response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
response.resume();
|
||||
reject(
|
||||
{ method: "GET", headers: { Accept: "application/json" } },
|
||||
(received) => {
|
||||
response = received;
|
||||
if (settled) {
|
||||
received.destroy();
|
||||
return;
|
||||
}
|
||||
if (received.statusCode !== 200) {
|
||||
finish(
|
||||
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
response.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
response.on("end", () => {
|
||||
const parsed = safeParseJson(Buffer.concat(chunks).toString("utf8"));
|
||||
let bytes = 0;
|
||||
received.on("data", (chunk: Buffer) => {
|
||||
if (settled) return;
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > limits.bytes) {
|
||||
finish(
|
||||
new BrowserObservationError(operation, "payload_limit", {
|
||||
detail: `CDP discovery response exceeds its ${String(limits.bytes)} byte limit.`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
received.on("end", () => {
|
||||
if (settled) return;
|
||||
const parsed = safeParseJson(
|
||||
Buffer.concat(chunks, bytes).toString("utf8"),
|
||||
);
|
||||
if (!parsed.ok) {
|
||||
reject(
|
||||
finish(
|
||||
new BrowserObservationError(
|
||||
operation,
|
||||
"invalid_endpoint_response",
|
||||
@@ -322,15 +375,41 @@ export const readCdpJson = async (
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve(parsed.value);
|
||||
finish(undefined, parsed.value);
|
||||
});
|
||||
response.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
received.on("aborted", () =>
|
||||
finish(
|
||||
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
||||
),
|
||||
);
|
||||
received.on("close", () => {
|
||||
if (!settled && !received.complete)
|
||||
finish(
|
||||
new BrowserObservationError(
|
||||
operation,
|
||||
"invalid_endpoint_response",
|
||||
),
|
||||
);
|
||||
});
|
||||
received.on("error", (cause: unknown) =>
|
||||
finish(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
},
|
||||
);
|
||||
request_.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
finish(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
onAbort();
|
||||
if (settled) return;
|
||||
timer = setTimeout(
|
||||
() =>
|
||||
finish(
|
||||
new BrowserObservationError(operation, "timeout", {
|
||||
detail: `CDP discovery response exceeded its ${String(limits.timeoutMs)} ms deadline.`,
|
||||
}),
|
||||
),
|
||||
limits.timeoutMs,
|
||||
);
|
||||
request_.end();
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import { mainFrameUrl } from "./CdpCaptureDocuments.js";
|
||||
import { captureFrames } from "./CdpCaptureDocuments.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";
|
||||
import { readPngHeaderDimensions } from "../domain/pngHeader.js";
|
||||
|
||||
interface ScreenshotContext {
|
||||
readonly connection: CdpConnection;
|
||||
@@ -94,7 +95,9 @@ export const captureCdpScreenshot = async (
|
||||
encoded === undefined ? undefined : decodeCanonicalBase64(encoded);
|
||||
if (bytes === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "payload_limit");
|
||||
const dimensions = pngDimensions(bytes);
|
||||
const dimensions = readPngHeaderDimensions(bytes);
|
||||
if (dimensions === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
if (navigation.leftScope)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
const afterUrl = mainFrameUrl(after);
|
||||
@@ -158,21 +161,3 @@ const observeScreenshotNavigation = (
|
||||
if (allowedSanitizedUrl(frame?.url, origins) === undefined)
|
||||
state.leftScope = true;
|
||||
};
|
||||
|
||||
const pngDimensions = (
|
||||
bytes: Buffer,
|
||||
): { readonly width: number; readonly height: number } => {
|
||||
if (
|
||||
bytes.byteLength < 24 ||
|
||||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
||||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
const width = bytes.readUInt32BE(16);
|
||||
const height = bytes.readUInt32BE(20);
|
||||
if (width === 0 || height === 0)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return { width, height };
|
||||
};
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
@@ -14,10 +14,13 @@ import type { BrowserScenarioAction } from "../domain/browserScenarioValues.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserScenarioEventFamily,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../domain/browserScenarioCaptureValues.js";
|
||||
import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../domain/browserNetworkEvidence.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { compareBrowserScenarios } from "../domain/browserScenarioDiff.js";
|
||||
import { compareBrowserScenariosInputSchema } from "../domain/browserScenarioDiffValues.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
@@ -373,6 +376,56 @@ describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider comparison coverage", () => {
|
||||
it("keeps quiet captures with different event families from comparing unchanged", async () => {
|
||||
const capture = async (events: readonly BrowserScenarioEventFamily[]) => {
|
||||
const provider = new PlaywrightBrowserScenarioProvider(() =>
|
||||
Promise.resolve(new FakeSession("launch")),
|
||||
);
|
||||
const result = await provider.captureScenario(scenario({ events }));
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
const compare = async (
|
||||
before: readonly BrowserScenarioEventFamily[],
|
||||
after: readonly BrowserScenarioEventFamily[],
|
||||
) =>
|
||||
compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: await capture(before),
|
||||
after_scenario: await capture(after),
|
||||
}),
|
||||
);
|
||||
|
||||
const recorded = await capture(["page-errors", "console", "console"]);
|
||||
expect(recorded.completeness.equality_eligible).toBe(true);
|
||||
expect(recorded.scenario.event_families).toEqual([
|
||||
"console",
|
||||
"page-errors",
|
||||
]);
|
||||
for (const [before, after] of [
|
||||
[[], ["console"]],
|
||||
[["console"], ["page-errors"]],
|
||||
] as const) {
|
||||
const compared = await compare(before, after);
|
||||
expect(compared.overall_status).toBe("unknown");
|
||||
expect(
|
||||
compared.steps.flatMap((step) => step.artifact_diffs),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
artifact: "events",
|
||||
status: "unknown",
|
||||
reason: expect.stringContaining("Event family selections differ"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(
|
||||
(await compare(["console", "page-errors"], ["page-errors", "console"]))
|
||||
.overall_status,
|
||||
).toBe("unchanged");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider cleanup", () => {
|
||||
it("returns a cleanup failure with completed observations when close fails", async () => {
|
||||
const session = new FakeSession("launch", {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import * as processOwnership from "../process/ProcessOwnership.js";
|
||||
import * as electronActions from "./PlaywrightElectronActiveActions.js";
|
||||
@@ -28,12 +29,13 @@ it("passes the selected environment and ownership token to Electron launch", asy
|
||||
throw new Error("launch boundary reached");
|
||||
},
|
||||
);
|
||||
const result = await provider.capture(
|
||||
electronActiveObservationInputSchema.parse({
|
||||
const result = await provider.capture({
|
||||
...electronActiveObservationInputSchema.parse({
|
||||
executable_path: process.execPath,
|
||||
application_path: process.execPath,
|
||||
}),
|
||||
);
|
||||
application_root: dirname(process.execPath),
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(launchedEnvironment).toEqual({
|
||||
@@ -151,12 +153,13 @@ it("retains the partial capture without taskkill when Windows lineage is unavail
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await provider.capture(
|
||||
electronActiveObservationInputSchema.parse({
|
||||
const result = await provider.capture({
|
||||
...electronActiveObservationInputSchema.parse({
|
||||
executable_path: process.execPath,
|
||||
application_path: process.execPath,
|
||||
}),
|
||||
);
|
||||
application_root: dirname(process.execPath),
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Expected unverified cleanup to fail");
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -9,11 +7,11 @@ import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { ElectronActiveObservationPort } from "../application/javascript/ElectronActiveObservationPort.js";
|
||||
import type {
|
||||
ElectronActiveObservationInput,
|
||||
ElectronActiveObservationResult,
|
||||
} from "../domain/javascript/electronActiveObservation.js";
|
||||
CanonicalElectronActiveObservationInput,
|
||||
ElectronActiveObservationPort,
|
||||
} from "../application/javascript/ElectronActiveObservationPort.js";
|
||||
import type { ElectronActiveObservationResult } from "../domain/javascript/electronActiveObservation.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
@@ -70,7 +68,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
}
|
||||
|
||||
async capture(
|
||||
input: ElectronActiveObservationInput,
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<ElectronActiveObservationResult, AnalysisError>> {
|
||||
let application: ElectronApplication | undefined;
|
||||
@@ -89,7 +87,11 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
await prepareProcessOwnershipInspection(options.signal);
|
||||
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
paths = await canonicalPaths(input);
|
||||
paths = {
|
||||
executable: input.executable_path,
|
||||
application: input.application_path,
|
||||
root: input.application_root,
|
||||
};
|
||||
const captureBaseline =
|
||||
await systemProcessOwnershipHost.captureBaseline?.(options.signal);
|
||||
if (options.signal?.aborted)
|
||||
@@ -353,20 +355,6 @@ export const cleanupElectronProcesses = async (
|
||||
};
|
||||
};
|
||||
|
||||
const canonicalPaths = async (
|
||||
input: ElectronActiveObservationInput,
|
||||
): Promise<ElectronPaths> => {
|
||||
const [executable, application] = await Promise.all([
|
||||
realpath(input.executable_path),
|
||||
realpath(input.application_path),
|
||||
]);
|
||||
const root =
|
||||
input.application_root === undefined
|
||||
? dirname(application)
|
||||
: await realpath(input.application_root);
|
||||
return { executable, application, root };
|
||||
};
|
||||
|
||||
const safeElectronEnvironment = (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
runId: string,
|
||||
|
||||
@@ -5,6 +5,77 @@ import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
|
||||
|
||||
describe("declared secrets in scenario events", () => {
|
||||
it("redacts encoded declared secrets from text evidence and fingerprints", () => {
|
||||
const listeners = new Map<string, (value: unknown) => void>();
|
||||
const socketListeners = new Map<string, (value: unknown) => void>();
|
||||
const page = {
|
||||
on: (name: string, listener: (value: unknown) => void) => {
|
||||
listeners.set(name, listener);
|
||||
},
|
||||
} as unknown as Page;
|
||||
const secret = "a/b&c\n d";
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "/opt/chromium" },
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
actions: [
|
||||
{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },
|
||||
],
|
||||
secrets: [
|
||||
{ secret_id: "login_input", environment_variable: "REA_TEST_TOKEN" },
|
||||
],
|
||||
capture: { events: ["console", "page-errors", "websockets"] },
|
||||
});
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {
|
||||
REA_TEST_TOKEN: secret,
|
||||
});
|
||||
if (secrets === undefined) throw new Error("Expected resolved secrets");
|
||||
const events = new PlaywrightScenarioEvents({
|
||||
page,
|
||||
enabled: new Set(["console", "page-errors", "websockets"]),
|
||||
secrets,
|
||||
});
|
||||
|
||||
listeners.get("console")?.({
|
||||
type: () => "log",
|
||||
text: () => encodeURIComponent(secret),
|
||||
location: () => ({ url: "https://app.example.test/app.js" }),
|
||||
});
|
||||
const escapedSecret = JSON.stringify(secret).slice(1, -1);
|
||||
const error = new Error(`failure ${escapedSecret}`);
|
||||
error.stack = `failure ${escapedSecret}`;
|
||||
listeners.get("pageerror")?.(error);
|
||||
listeners.get("websocket")?.({
|
||||
url: () => "wss://app.example.test/socket",
|
||||
on: (name: string, listener: (value: unknown) => void) => {
|
||||
socketListeners.set(name, listener);
|
||||
},
|
||||
});
|
||||
const formEncodedSecret = new URLSearchParams([["value", secret]])
|
||||
.toString()
|
||||
.slice("value=".length);
|
||||
socketListeners.get("framesent")?.({ payload: formEncodedSecret });
|
||||
|
||||
const items = events.result().items;
|
||||
expect(items).toMatchObject([
|
||||
{ kind: "console", text: "[REDACTED:login_input]" },
|
||||
{
|
||||
kind: "page-error",
|
||||
message: "failure [REDACTED:login_input]",
|
||||
stack: "failure [REDACTED:login_input]",
|
||||
},
|
||||
{ kind: "websocket-opened" },
|
||||
{
|
||||
kind: "websocket-frame-sent",
|
||||
payload_text: "[REDACTED:login_input]",
|
||||
},
|
||||
]);
|
||||
expect(secrets.fingerprint(`stored ${encodeURIComponent(secret)}`)).toEqual(
|
||||
{ value_state: "redacted-secret", value_sha256: null },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightScenarioEvents", () => {
|
||||
it("observes requested popup page errors independently of popup lifecycle events", () => {
|
||||
const listeners = new Map<string, (value: unknown) => void>();
|
||||
@@ -42,7 +113,7 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds oversized page errors before validating captured events", () => {
|
||||
it("retains oversized page errors without truncating their text", () => {
|
||||
const listeners = new Map<string, (value: Error) => void>();
|
||||
const page = {
|
||||
url: () => "https://app.example.test/",
|
||||
@@ -88,7 +159,7 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
const error = new Error("m".repeat(70_000));
|
||||
error.stack = "s".repeat(300_000);
|
||||
|
||||
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
|
||||
listeners.get("pageerror")?.(error);
|
||||
expect(events.result().items[0]).toMatchObject({
|
||||
kind: "page-error",
|
||||
message: "m".repeat(70_000),
|
||||
|
||||
@@ -82,6 +82,8 @@ const fixture = () => {
|
||||
const page = Object.assign(new EventEmitter(), {
|
||||
url: () => "about:blank",
|
||||
goto: vi.fn(async () => undefined),
|
||||
evaluate: vi.fn(async (_script: unknown) => false),
|
||||
addInitScript: vi.fn(async (_script: unknown) => undefined),
|
||||
context: () => context,
|
||||
});
|
||||
const context = Object.assign(new EventEmitter(), {
|
||||
@@ -116,7 +118,7 @@ const fixture = () => {
|
||||
settle: vi.fn(async () => undefined),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
return { cleanup, storage: mocks.storage };
|
||||
return { cleanup, page, storage: mocks.storage };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -137,6 +139,81 @@ it("uses browser disconnect as terminal storage release after detach failure", a
|
||||
expect(storage.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves attached service-worker state alone when the policy allows it", async () => {
|
||||
const { cleanup, page } = fixture();
|
||||
const attached = browserScenarioSchema.parse({
|
||||
...scenario,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "target",
|
||||
},
|
||||
environment: { service_workers: "allow" },
|
||||
});
|
||||
const session = await PlaywrightScenarioSession.open(attached, {}, {});
|
||||
|
||||
expect(mocks.openBrowser).toHaveBeenCalledWith(
|
||||
attached,
|
||||
{},
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(page.evaluate).not.toHaveBeenCalled();
|
||||
expect(page.addInitScript).not.toHaveBeenCalled();
|
||||
await expect(session.close()).resolves.toBe("disconnected-external");
|
||||
expect(cleanup.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("blocks new attached service-worker registration without removing existing registrations", async () => {
|
||||
const { cleanup, page } = fixture();
|
||||
const attached = browserScenarioSchema.parse({
|
||||
...scenario,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "target",
|
||||
},
|
||||
environment: { service_workers: "block" },
|
||||
});
|
||||
const session = await PlaywrightScenarioSession.open(attached, {}, {});
|
||||
|
||||
expect(page.evaluate).toHaveBeenCalledTimes(2);
|
||||
expect(page.addInitScript).toHaveBeenCalledTimes(1);
|
||||
expect(page.addInitScript).toHaveBeenCalledWith(
|
||||
expect.stringContaining("service workers are blocked by scenario policy"),
|
||||
);
|
||||
expect(page.addInitScript).toHaveBeenCalledWith(
|
||||
expect.not.stringContaining("getRegistrations"),
|
||||
);
|
||||
expect(page.addInitScript).toHaveBeenCalledWith(
|
||||
expect.not.stringContaining("unregister"),
|
||||
);
|
||||
await expect(session.close()).resolves.toBe("disconnected-external");
|
||||
expect(cleanup.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects attached block when caller-owned registrations already exist", async () => {
|
||||
const { cleanup, page } = fixture();
|
||||
page.evaluate.mockResolvedValueOnce(true);
|
||||
const attached = browserScenarioSchema.parse({
|
||||
...scenario,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "target",
|
||||
},
|
||||
environment: { service_workers: "block" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
PlaywrightScenarioSession.open(attached, {}, {}),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "target_not_allowed",
|
||||
});
|
||||
expect(page.addInitScript).not.toHaveBeenCalled();
|
||||
expect(cleanup.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves both cleanup failures and retries retained owners", async () => {
|
||||
const { cleanup, storage } = fixture();
|
||||
const detachFailure = new Error("CDP detach rejected");
|
||||
|
||||
@@ -51,15 +51,18 @@ const installCookies = async (
|
||||
};
|
||||
|
||||
const blockAttachedServiceWorkers = async (page: Page): Promise<void> => {
|
||||
const controller = await page.evaluate(
|
||||
"Boolean(navigator.serviceWorker?.controller)",
|
||||
);
|
||||
if (controller)
|
||||
const hasServiceWorker = await page.evaluate(`(async () => {
|
||||
if (!("serviceWorker" in navigator)) return false;
|
||||
const serviceWorker = navigator.serviceWorker;
|
||||
if (serviceWorker.controller !== null) return true;
|
||||
return (await serviceWorker.getRegistrations()).length > 0;
|
||||
})()`);
|
||||
// An attached context belongs to the caller. Reject a block request when it
|
||||
// already has a worker instead of unregistering that caller-owned resource.
|
||||
if (hasServiceWorker)
|
||||
throw new BrowserObservationError(OPERATION, "target_not_allowed");
|
||||
const blockRegistration = `(() => {
|
||||
if (!("serviceWorker" in navigator)) return;
|
||||
void navigator.serviceWorker.getRegistrations()
|
||||
.then((registrations) => Promise.all(registrations.map((item) => item.unregister())));
|
||||
Object.defineProperty(ServiceWorkerContainer.prototype, "register", {
|
||||
configurable: false,
|
||||
value: () => Promise.reject(new Error("service workers are blocked by scenario policy"))
|
||||
@@ -77,7 +80,10 @@ const initializePage = async (
|
||||
): Promise<void> => {
|
||||
context.setDefaultTimeout(0);
|
||||
context.setDefaultNavigationTimeout(0);
|
||||
if (scenario.browser.mode === "connect")
|
||||
if (
|
||||
scenario.browser.mode === "connect" &&
|
||||
scenario.environment.service_workers === "block"
|
||||
)
|
||||
await blockAttachedServiceWorkers(page);
|
||||
await installCookies(context, scenario, secrets);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
import {
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
} from "../process/LinuxResourceLimits.js";
|
||||
import { parsePacketOutput } from "./parsePacketOutput.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { access, mkdir, realpath, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisExecution,
|
||||
type ExecutionOptions,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { PacketCapturePort } from "../application/captures/PacketCaptureService.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import {
|
||||
ArtifactAnalysisResources,
|
||||
type ArtifactAnalysisRuntime,
|
||||
} from "../process/ArtifactAnalysisResources.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisCapturedOutput,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import {
|
||||
type InspectPacketCaptureInput,
|
||||
packetCaptureSchema,
|
||||
} from "../domain/captures/packetCapture.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
runOwnedCommand,
|
||||
OwnedCommandFailure,
|
||||
} from "../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
|
||||
const OPERATION = "inspect_packet_capture";
|
||||
export const TSHARK_PROVIDER_IDENTITY = {
|
||||
id: "tshark-capture",
|
||||
name: "REA TShark capture adapter",
|
||||
version: "tshark@4",
|
||||
} as const;
|
||||
// Bound the resident input copy and retained text before allocation/collection.
|
||||
const LIMITS = {
|
||||
input_bytes: 32 * 1024 * 1024,
|
||||
output_bytes: 4 * 1024 * 1024,
|
||||
command_timeout_ms: 30_000,
|
||||
address_space_bytes: 1024 * 1024 * 1024,
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
|
||||
export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
readonly #resources: ArtifactAnalysisResources;
|
||||
constructor(
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
readonly launcher?: Launcher,
|
||||
readonly createRuntime: () => Promise<ArtifactAnalysisRuntime> = () =>
|
||||
PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }),
|
||||
readonly platform: NodeJS.Platform = process.platform,
|
||||
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
|
||||
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
|
||||
) {
|
||||
this.#resources = new ArtifactAnalysisResources(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
readArtifact,
|
||||
readLimits,
|
||||
{
|
||||
message:
|
||||
"A packet inspection is already active; retry after it completes.",
|
||||
details: { max_concurrent_inspections: 1 },
|
||||
},
|
||||
);
|
||||
}
|
||||
inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#inspect(input, options),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
async #inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
let phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
| "workspace"
|
||||
| "producer"
|
||||
| "integrity" = "configuration";
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
let resourcePath = input.path;
|
||||
let effectiveLimits: LinuxResourceLimits | undefined;
|
||||
let root: ArtifactAnalysisRuntime | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
await this.#resources.release();
|
||||
if (this.platform !== "linux")
|
||||
throw new Error(
|
||||
"Packet inspection requires Linux with util-linux prlimit and REA_TSHARK_COMMAND so expanded captures are processed under an enforced address-space limit.",
|
||||
);
|
||||
const configured = this.environment.REA_TSHARK_COMMAND ?? "";
|
||||
if (!isAbsolute(configured))
|
||||
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
|
||||
const command = await realpath(configured);
|
||||
await access(command, constants.X_OK);
|
||||
const tool = await this.#resources.read(
|
||||
command,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
const configuredLimiter =
|
||||
this.environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
if (!isAbsolute(configuredLimiter))
|
||||
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
|
||||
const limiter = await realpath(configuredLimiter);
|
||||
await access(limiter, constants.X_OK);
|
||||
const limiterIdentity = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.#resources.readLimits(LIMITS);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
];
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined);
|
||||
const snapshotPath = join(root.path, "capture");
|
||||
const configurationPath = join(root.path, "configuration");
|
||||
await mkdir(configurationPath, { mode: 0o700 });
|
||||
const execute = async (args: readonly string[]) => {
|
||||
const output = await runOwnedCommand(
|
||||
{
|
||||
command: limiter,
|
||||
arguments: [...limitArguments, ...args],
|
||||
...(root === undefined ? {} : { cwd: root.path }),
|
||||
expectedCommand: null,
|
||||
runId: `rea-tshark-${randomUUID()}`,
|
||||
hostEnvironment: {
|
||||
...this.environment,
|
||||
WIRESHARK_CONFIG_DIR: configurationPath,
|
||||
},
|
||||
},
|
||||
{
|
||||
timeoutMs: LIMITS.command_timeout_ms,
|
||||
diagnosticBytes: LIMITS.output_bytes,
|
||||
acceptNonZeroExit: true,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined
|
||||
? {}
|
||||
: { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
},
|
||||
);
|
||||
capturedOutput = {
|
||||
stdout: output.stdout.text,
|
||||
stderr: output.stderr.text,
|
||||
truncated: output.diagnosticTruncated ?? false,
|
||||
exit_code: output.exitCode ?? null,
|
||||
signal: output.signal ?? null,
|
||||
};
|
||||
// Finish bounded integrity checks after output; service handles late cancellation with Evidence.
|
||||
const previousPhase = phase;
|
||||
phase = "integrity";
|
||||
resourcePath = command;
|
||||
const current = await this.#resources.read(command, 64 * 1024 * 1024);
|
||||
resourcePath = limiter;
|
||||
const currentLimiter = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
);
|
||||
if (currentLimiter.sha256 !== limiterIdentity.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
limiter,
|
||||
"Configured resource limiter changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
if (current.sha256 !== tool.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
command,
|
||||
"Configured TShark executable changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
phase = previousPhase;
|
||||
resourcePath = input.path;
|
||||
if (output.exitCode !== 0)
|
||||
throw new ProviderAdapterError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
{
|
||||
diagnostics: {
|
||||
exit_code: output.exitCode ?? null,
|
||||
stdout: output.stdout.text,
|
||||
stderr: output.stderr.text,
|
||||
},
|
||||
},
|
||||
);
|
||||
return output;
|
||||
};
|
||||
phase = "configuration";
|
||||
const version = await execute(["--version"]);
|
||||
if (
|
||||
!/^TShark \(Wireshark\) 4\.[0-9]+\.[0-9]+(?:[ .(\r\n]|$)/u.test(
|
||||
version.stdout.text,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"Expected TShark 4.x; inspect the selected installation.",
|
||||
);
|
||||
phase = "artifact";
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "workspace";
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
});
|
||||
phase = "producer";
|
||||
const args = [
|
||||
"-n",
|
||||
"-r",
|
||||
"capture",
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
"--temp-dir=.",
|
||||
...(input.two_pass ? ["-2"] : []),
|
||||
...(input.packet_limit === null
|
||||
? []
|
||||
: ["-c", String(input.packet_limit)]),
|
||||
...(input.display_filter === null ? [] : ["-Y", input.display_filter]),
|
||||
...input.decode_as.flatMap((value) => ["-d", value]),
|
||||
...[...new Set(["frame.number", ...input.fields])].flatMap((field) => [
|
||||
"-e",
|
||||
field,
|
||||
]),
|
||||
];
|
||||
const output = await execute(args);
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
snapshotPath,
|
||||
"TShark changed the private capture copy.",
|
||||
capturedOutput === undefined ? {} : { capturedOutput },
|
||||
);
|
||||
phase = "producer";
|
||||
resourcePath = input.path;
|
||||
const matchingPackets = parsePacketOutput(
|
||||
output.stdout.text,
|
||||
input.fields,
|
||||
);
|
||||
const start = Math.min(input.match_offset, matchingPackets.length);
|
||||
const end =
|
||||
input.match_limit === null
|
||||
? matchingPackets.length
|
||||
: start + Math.min(input.match_limit, matchingPackets.length - start);
|
||||
const packets = matchingPackets.slice(start, end);
|
||||
const report = packetCaptureSchema.parse({
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
bytes: selected.bytes.length,
|
||||
},
|
||||
selection: input,
|
||||
packets,
|
||||
output_window: {
|
||||
matching_packets: matchingPackets.length,
|
||||
returned_packets: packets.length,
|
||||
has_more: end < matchingPackets.length,
|
||||
},
|
||||
read_scope:
|
||||
input.packet_limit === null ? "to-eof" : "up-to-input-packet-limit",
|
||||
configuration: "private-empty-personal-profile",
|
||||
diagnostics: output.stderr.text,
|
||||
tool: {
|
||||
configured_path: configured,
|
||||
path: command,
|
||||
sha256: tool.sha256,
|
||||
version_banner: version.stdout.text,
|
||||
version_diagnostics: version.stderr.text,
|
||||
arguments: args,
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: configuredLimiter,
|
||||
path: limiter,
|
||||
sha256: limiterIdentity.sha256,
|
||||
arguments: limitArguments,
|
||||
},
|
||||
limits: { ...LIMITS, ...effectiveLimits },
|
||||
hardware_acquisition: "not-performed",
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
format: "file",
|
||||
},
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"Fields are TShark dissector observations under the selected filter/decode-as/pass settings, not independently verified protocol semantics. Missing fields are absent from the producer output, not known zero or empty values.",
|
||||
"Packet limits count input packets before display filtering. Filtered results do not establish whole-capture or device traffic absence. Two-pass reassembly cannot recover bytes missing from the recording or beyond the read limit.",
|
||||
"Repeated field values remain ordered string arrays; raw packet bytes are included only when explicitly selected as a supported field. Export index/score metadata are omitted. All stderr, including warnings on exit zero, is retained.",
|
||||
"A private empty personal configuration is used. Installed libraries, global configuration and dissector plugins are trusted and not fully fingerprinted. File-only analysis and disabled name resolution do not constitute an OS sandbox.",
|
||||
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
root !== undefined &&
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.cleanupOwner !== undefined
|
||||
)
|
||||
this.#resources.retain(root, cause.cleanupOwner);
|
||||
result = err(
|
||||
this.#failure(
|
||||
cause,
|
||||
phase,
|
||||
resourcePath,
|
||||
root?.path ?? null,
|
||||
effectiveLimits,
|
||||
capturedOutput,
|
||||
),
|
||||
);
|
||||
}
|
||||
return this.#resources.finish(result, (execution) =>
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
);
|
||||
}
|
||||
#failure(
|
||||
cause: unknown,
|
||||
phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
| "workspace"
|
||||
| "producer"
|
||||
| "integrity",
|
||||
path: string,
|
||||
workspacePath: string | null,
|
||||
effectiveLimits: LinuxResourceLimits | undefined,
|
||||
observedOutput: AnalysisCapturedOutput | undefined,
|
||||
): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
return this.#resources.cleanupFailure(
|
||||
cause.cleanup,
|
||||
cause,
|
||||
observedOutput,
|
||||
);
|
||||
if (
|
||||
(cause instanceof Error && cause.name === "AbortError") ||
|
||||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION, { cause });
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OwnedCommandFailure)
|
||||
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
|
||||
if (phase === "workspace") {
|
||||
const code =
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? cause.code
|
||||
: null;
|
||||
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
`Private analysis workspace failed (${code}): ${reason}`,
|
||||
{ workspace_path: workspacePath, system_code: code },
|
||||
{ cause },
|
||||
);
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
cause,
|
||||
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
|
||||
diagnostics: {
|
||||
stage: "workspace",
|
||||
workspace_path: workspacePath,
|
||||
system_code: code,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (phase === "integrity") {
|
||||
const detail = {
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
};
|
||||
if (
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
["limit", "integrity", "path"].includes(cause.reason)
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
path,
|
||||
`Post-run identity verification failed for ${path}: ${reason}`,
|
||||
detail,
|
||||
);
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
...detail,
|
||||
diagnostics: { stage: "integrity", resource_path: path, reason },
|
||||
});
|
||||
}
|
||||
if (phase === "configuration")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
reason,
|
||||
{
|
||||
cause,
|
||||
userMessage: `${reason} On Linux, configure TShark 4.x through REA_TSHARK_COMMAND and util-linux prlimit through REA_TSHARK_PRLIMIT_COMMAND (default /usr/bin/prlimit).`,
|
||||
},
|
||||
);
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "limit"
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
reason,
|
||||
{ input_bytes: LIMITS.input_bytes },
|
||||
{ cause },
|
||||
);
|
||||
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
|
||||
cause,
|
||||
});
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
if (phase === "artifact")
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{ path: ["path"], reason: "invalid_value", message: reason },
|
||||
]);
|
||||
return new AnalysisOutputError(OPERATION, reason, { cause });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import { packetFieldsSchema } from "../domain/captures/packetCapture.js";
|
||||
|
||||
// _index/_score are TShark export metadata, not captured packet fields.
|
||||
const producerSchema = z.array(
|
||||
z.object({ _source: z.object({ layers: packetFieldsSchema }) }),
|
||||
);
|
||||
export const parsePacketOutput = (text: string, fields: readonly string[]) => {
|
||||
const decoded: unknown = JSON.parse(text);
|
||||
const packets = producerSchema
|
||||
.parse(decoded)
|
||||
.map((packet) => packet._source.layers);
|
||||
const selected = new Set(["frame.number", ...fields]);
|
||||
let previous = 0n;
|
||||
for (const packet of packets) {
|
||||
const frame = BigInt(packet["frame.number"][0]);
|
||||
if (
|
||||
frame <= previous ||
|
||||
Object.keys(packet).some((name) => !selected.has(name))
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_packet_capture",
|
||||
"TShark returned unordered frames or unselected fields.",
|
||||
);
|
||||
previous = frame;
|
||||
}
|
||||
return packets;
|
||||
};
|
||||
+27
-7
@@ -5,20 +5,33 @@ import { z } from "zod";
|
||||
|
||||
import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./contracts/toolContracts.js";
|
||||
import type { ToolContract } from "./contracts/toolContractTypes.js";
|
||||
import { CLI_COMMAND_NAMES } from "./cliCommandNames.js";
|
||||
import { compareUnicodeCodePoints } from "./domain/unicodeCodePointOrder.js";
|
||||
|
||||
const sortedToolContracts = [...TOOL_CONTRACTS].sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.name, right.name),
|
||||
);
|
||||
const sortByName = (
|
||||
contracts: readonly ToolContract[],
|
||||
): readonly ToolContract[] =>
|
||||
[...contracts].sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.name, right.name),
|
||||
);
|
||||
|
||||
const createToolCatalog = () =>
|
||||
sortedToolContracts.map((contract) => ({
|
||||
const sortedToolContracts = sortByName(TOOL_CONTRACTS);
|
||||
|
||||
/**
|
||||
* Digested per-tool projection. Every contract field that changes what a
|
||||
* client receives belongs here, including `returns_target_content`: a server
|
||||
* that predates the untrusted-content framing must not digest equal to one
|
||||
* that emits `_meta.provenance`, or a stale process would report aligned.
|
||||
*/
|
||||
const createToolCatalog = (contracts: readonly ToolContract[]) =>
|
||||
contracts.map((contract) => ({
|
||||
name: contract.name,
|
||||
title: contract.title,
|
||||
surface: contract.kind,
|
||||
description: contract.description,
|
||||
effects: { ...contract.effects },
|
||||
returns_target_content: contract.returnsTargetContent,
|
||||
annotations: contract.annotations,
|
||||
input_schema: {
|
||||
type: "object",
|
||||
@@ -49,8 +62,15 @@ const digest = (value: unknown): string => {
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const createCatalogDigests = () => {
|
||||
const tools = createToolCatalog();
|
||||
/**
|
||||
* Catalog digests over the given tool contracts. Exported so tests can prove
|
||||
* which contract fields the identity covers; production uses
|
||||
* {@link CATALOG_IDENTITY}.
|
||||
*/
|
||||
export const createCatalogDigests = (
|
||||
contracts: readonly ToolContract[] = TOOL_CONTRACTS,
|
||||
) => {
|
||||
const tools = createToolCatalog(sortByName(contracts));
|
||||
return {
|
||||
tools_sha256: digest(tools),
|
||||
prompts_sha256: digest(promptCatalog),
|
||||
|
||||
+9
-1
@@ -1,8 +1,11 @@
|
||||
import { registerCaptureCommands } from "./cli/captureCommands.js";
|
||||
import { registerSignalCommands } from "./cli/signalCommands.js";
|
||||
import { registerWasmCommands } from "./cli/wasmCommands.js";
|
||||
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
|
||||
import { createDirectAnalysis } from "./composition/directAnalysis.js";
|
||||
import { registerEvmCommands } from "./cli/evmCommands.js";
|
||||
import { registerGoCommands } from "./cli/goCommands.js";
|
||||
import { registerSqliteCommands } from "./cli/sqliteCommands.js";
|
||||
import { registerAnalysisViewCommands } from "./cli/analysisViewCommands.js";
|
||||
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
|
||||
import { registerFridaCommands } from "./cli/fridaCommands.js";
|
||||
@@ -21,6 +24,7 @@ import { registerManagedCommands } from "./cli/managedCommands.js";
|
||||
import { registerFirmwareCommands } from "./cli/firmwareCommands.js";
|
||||
import { registerAndroidCommands } from "./cli/androidCommands.js";
|
||||
import { registerApktoolCommands } from "./cli/apktoolCommands.js";
|
||||
import { registerFlutterCommands } from "./cli/flutterCommands.js";
|
||||
import { registerJebCommands } from "./cli/jebCommands.js";
|
||||
import { registerAdbCommands } from "./cli/adbCommands.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
@@ -42,7 +46,7 @@ import type { CliInstance } from "./cli/types.js";
|
||||
import {
|
||||
streamCliCommandResults,
|
||||
type CliResultOutput,
|
||||
} from "./cli/streamedJsonOutput.js";
|
||||
} from "./cli/cliResultOutput.js";
|
||||
|
||||
/** Describe CLI settings that are invalid before any command runs, as MCP does. */
|
||||
export const cliConfigurationError = (
|
||||
@@ -92,12 +96,16 @@ export const createCli = (
|
||||
registerCoreAnalysisCommands(cli, logger, analysis.runDirectAnalysis);
|
||||
registerUtilityCommands(cli, logger, environment, analysis);
|
||||
registerWasmCommands(cli, logger, environment);
|
||||
registerCaptureCommands(cli, logger, environment);
|
||||
registerSignalCommands(cli, logger, environment);
|
||||
registerEvmCommands(cli, logger, environment);
|
||||
registerGoCommands(cli, logger);
|
||||
registerSqliteCommands(cli, logger, environment);
|
||||
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerAndroidCommands(cli, logger, environment);
|
||||
registerApktoolCommands(cli, logger, environment);
|
||||
registerFlutterCommands(cli, logger);
|
||||
registerJebCommands(cli, logger, environment);
|
||||
registerAdbCommands(cli, logger, environment);
|
||||
registerFirmwareCommands(cli, logger, environment);
|
||||
|
||||
@@ -53,7 +53,7 @@ export const registerBinaryDiagnosticsCommands = (
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectBinaryLayout, async () => {
|
||||
const result = await service.inspect(
|
||||
const result = await service.inspectAndClose(
|
||||
{ path: resolve(args.path) },
|
||||
{ signal },
|
||||
);
|
||||
@@ -75,7 +75,7 @@ export const registerBinaryDiagnosticsCommands = (
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectRecordedCrash, async () => {
|
||||
const result = await recorded.inspect(
|
||||
const result = await recorded.inspectAndClose(
|
||||
{
|
||||
path: resolve(args.path),
|
||||
include_debugger_context: options.debuggerContext,
|
||||
|
||||
@@ -14,7 +14,9 @@ import {
|
||||
AnalysisInputError,
|
||||
type AnalysisInputIssue,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../domain/browserCaptureComparison.js";
|
||||
import { compareBrowserScenariosInputSchema } from "../domain/browserScenarioDiffValues.js";
|
||||
import { browserScenarioCaptureSchema } from "../domain/browserScenarioCapture.js";
|
||||
import { compareWebCapturesInputSchema } from "../domain/webCaptureDiffSchemas.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "../domain/webMcpDiscovery.js";
|
||||
import {
|
||||
@@ -59,13 +61,18 @@ const registerWebMcp = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "discover-webmcp-tools", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = discoverWebMcpToolsInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
observation_ms: options.observationMs,
|
||||
});
|
||||
if (!parsed.success) return inputError("discover_webmcp_tools");
|
||||
};
|
||||
const parsed = discoverWebMcpToolsInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return inputError(
|
||||
"discover_webmcp_tools",
|
||||
projectInputIssues(parsed.error.issues, input),
|
||||
);
|
||||
const result = await discoverWebMcpTools(context.provider, parsed.data);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
@@ -104,16 +111,28 @@ const registerCaptureDiff = (
|
||||
});
|
||||
if (!inputs.ok) return inputs.error;
|
||||
const { before, after, normalization } = inputs.value;
|
||||
const scenarioComparison =
|
||||
browserCaptureComparisonInputSchema.safeParse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization,
|
||||
});
|
||||
const parsed = scenarioComparison.success
|
||||
? scenarioComparison
|
||||
: browserCaptureComparisonInputSchema.safeParse({ before, after });
|
||||
if (!parsed.success) return inputError("compare_web_captures");
|
||||
// Passive snapshots own the inspection wrapper. Otherwise recognize
|
||||
// scenario-owned fields even when the scenario manifest is missing.
|
||||
const scenarioInput = [before, after].some(
|
||||
(capture) =>
|
||||
typeof capture === "object" &&
|
||||
capture !== null &&
|
||||
!("inspection" in capture) &&
|
||||
Object.keys(browserScenarioCaptureSchema.shape).some(
|
||||
(field) => field in capture,
|
||||
),
|
||||
);
|
||||
const input = scenarioInput
|
||||
? { before_scenario: before, after_scenario: after, normalization }
|
||||
: { before, after };
|
||||
const parsed = scenarioInput
|
||||
? compareBrowserScenariosInputSchema.safeParse(input)
|
||||
: compareWebCapturesInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return inputError(
|
||||
"compare_web_captures",
|
||||
projectInputIssues(parsed.error.issues, input),
|
||||
);
|
||||
const result = await compareWebCaptureEvidence(
|
||||
new CdpBrowserProvider(),
|
||||
parsed.data,
|
||||
@@ -140,12 +159,17 @@ const registerScreenshot = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "capture-web-screenshot", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = captureWebScreenshotInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
});
|
||||
if (!parsed.success) return inputError("capture_web_screenshot");
|
||||
};
|
||||
const parsed = captureWebScreenshotInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return inputError(
|
||||
"capture_web_screenshot",
|
||||
projectInputIssues(parsed.error.issues, input),
|
||||
);
|
||||
const result = await captureWebScreenshot(
|
||||
context.provider,
|
||||
parsed.data,
|
||||
|
||||
+39
-13
@@ -14,7 +14,7 @@ import {
|
||||
} from "../domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "../domain/webBundleAnalysis.js";
|
||||
import { observeWebSessionInputSchema } from "../domain/browserSession.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import {
|
||||
@@ -48,13 +48,18 @@ const registerTargetList = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "list-browser-targets", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = listBrowserTargetsInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
});
|
||||
};
|
||||
const parsed = listBrowserTargetsInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return browserCliError(
|
||||
new AnalysisInputError("list_browser_targets"),
|
||||
analysisInputErrorFromIssues(
|
||||
"list_browser_targets",
|
||||
parsed.error.issues,
|
||||
input,
|
||||
),
|
||||
);
|
||||
const result = await listBrowserTargets(context.provider, parsed.data);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
@@ -77,7 +82,7 @@ const registerPageInspection = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-web-page", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = inspectWebPageInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
@@ -89,9 +94,16 @@ const registerPageInspection = (
|
||||
include_script_sources: options.includeScriptSources,
|
||||
include_storage_keys: options.includeStorageKeys,
|
||||
include_storage_fingerprints: options.includeStorageFingerprints,
|
||||
});
|
||||
};
|
||||
const parsed = inspectWebPageInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return browserCliError(new AnalysisInputError("inspect_web_page"));
|
||||
return browserCliError(
|
||||
analysisInputErrorFromIssues(
|
||||
"inspect_web_page",
|
||||
parsed.error.issues,
|
||||
input,
|
||||
),
|
||||
);
|
||||
const result = await inspectWebPage(context.provider, parsed.data);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
@@ -120,16 +132,23 @@ const registerBundleAnalysis = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "analyze-web-bundle", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = analyzeWebBundleInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
observation_ms: options.observationMs,
|
||||
include_script_sources: true,
|
||||
fetch_source_maps: options.fetchSourceMaps,
|
||||
});
|
||||
};
|
||||
const parsed = analyzeWebBundleInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return browserCliError(new AnalysisInputError("analyze_web_bundle"));
|
||||
return browserCliError(
|
||||
analysisInputErrorFromIssues(
|
||||
"analyze_web_bundle",
|
||||
parsed.error.issues,
|
||||
input,
|
||||
),
|
||||
);
|
||||
const result = await analyzeWebBundle(context.provider, parsed.data);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
@@ -153,14 +172,21 @@ const registerObservationSession = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "observe-web-session", async () => {
|
||||
const context = browserContext();
|
||||
const parsed = observeWebSessionInputSchema.safeParse({
|
||||
const input = {
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins: options.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
observation_ms: options.observationMs,
|
||||
});
|
||||
};
|
||||
const parsed = observeWebSessionInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return browserCliError(new AnalysisInputError("observe_web_session"));
|
||||
return browserCliError(
|
||||
analysisInputErrorFromIssues(
|
||||
"observe_web_session",
|
||||
parsed.error.issues,
|
||||
input,
|
||||
),
|
||||
);
|
||||
const result = await observeWebSession(context.provider, parsed.data);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { z } from "incur";
|
||||
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { resolve } from "node:path";
|
||||
import { createPacketCaptureService } from "../composition/captures.js";
|
||||
import {
|
||||
packetCaptureOptionsSchema,
|
||||
packetCaptureSelectorBudgetIssue,
|
||||
withinPacketCaptureSelectorBudget,
|
||||
} from "../domain/captures/packetCapture.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
export const registerCaptureCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
service: Pick<
|
||||
PacketCaptureService,
|
||||
"inspect" | "close"
|
||||
> = createPacketCaptureService(environment),
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.inspectPacketCapture, {
|
||||
description:
|
||||
"Inspect an existing packet capture with caller-supplied TShark",
|
||||
args: z.object({ path: z.string().describe("Local packet capture") }),
|
||||
options: z
|
||||
.object({
|
||||
...packetCaptureOptionsSchema.shape,
|
||||
match_limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("Returned matching frames per page; default 50"),
|
||||
all_matches: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe(
|
||||
"Return all remaining matching frames instead of a bounded page",
|
||||
),
|
||||
})
|
||||
.superRefine((options, context) => {
|
||||
if (options.all_matches && options.match_limit !== undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["all_matches"],
|
||||
message: "all_matches and match_limit are mutually exclusive",
|
||||
});
|
||||
})
|
||||
.refine(
|
||||
withinPacketCaptureSelectorBudget,
|
||||
packetCaptureSelectorBudgetIssue,
|
||||
),
|
||||
run: ({ args, options: { all_matches, ...options } }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectPacketCapture, async () => {
|
||||
const result = await service.inspect(
|
||||
{
|
||||
...options,
|
||||
...(all_matches ? { match_limit: null } : {}),
|
||||
path: resolve(args.path),
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: "inspect_packet_capture" },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
"inspect_packet_capture",
|
||||
),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -1,15 +1,24 @@
|
||||
import { constants } from "node:buffer";
|
||||
import type { Writable } from "node:stream";
|
||||
|
||||
import { Cli, Filter } from "incur";
|
||||
import { Cli, Filter, Formatter } from "incur";
|
||||
import { estimateTokenCount, sliceByTokens } from "tokenx";
|
||||
|
||||
import { parseCliOutputArguments } from "../cliOutput.js";
|
||||
import {
|
||||
parseCliOutputArguments,
|
||||
validateCliOutputArguments,
|
||||
} from "../cliOutput.js";
|
||||
import { cliOperationFailurePayload } from "../cliLogging.js";
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
projectAnalysisError,
|
||||
type AnalysisErrorProjection,
|
||||
} from "../domain/analysisErrorProjection.js";
|
||||
import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js";
|
||||
import {
|
||||
jsonOutputParts,
|
||||
writeJsonOutput,
|
||||
writeOutputText,
|
||||
} from "./jsonOutput.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
/** Result metadata supplied by the command that actually ran. */
|
||||
@@ -100,19 +109,15 @@ const wrapCommand = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Preserve Incur's JSON controls while streaming the complete result. */
|
||||
export const createStreamedCliJsonOutput = (
|
||||
/** Preserve Incur output controls and stream JSON while framing failures. */
|
||||
export const createCliResultOutput = (
|
||||
arguments_: readonly string[],
|
||||
destination: Writable,
|
||||
): CliResultOutput | undefined => {
|
||||
const options = parseCliOutputArguments(arguments_);
|
||||
if (
|
||||
options.parseError ||
|
||||
options.tokenWindow ||
|
||||
(options.format !== "json" && options.format !== "jsonl")
|
||||
)
|
||||
if (options.parseError || !validateCliOutputArguments(arguments_).ok)
|
||||
return undefined;
|
||||
const format = options.format;
|
||||
const format = options.format as "json" | "jsonl" | "yaml" | "toon" | "md";
|
||||
let handled = false;
|
||||
let failed = false;
|
||||
let error: AnalysisErrorProjection | undefined;
|
||||
@@ -128,27 +133,53 @@ export const createStreamedCliJsonOutput = (
|
||||
},
|
||||
async write(value, metadata) {
|
||||
if (metadata.format !== format) return false;
|
||||
const failure = options.fullOutput
|
||||
? cliOperationFailurePayload(value)
|
||||
: undefined;
|
||||
const filtered: unknown = options.filterOutput
|
||||
? Filter.apply(value, Filter.parse(options.filterOutput))
|
||||
: value;
|
||||
const meta = {
|
||||
command: metadata.command,
|
||||
duration: metadata.duration,
|
||||
};
|
||||
// Leave successful YAML and bare YAML rendering to Incur. The custom
|
||||
// boundary is needed only for a full failure envelope, whose error
|
||||
// sentinel otherwise drops category, remediation, and details.
|
||||
if (format !== "json" && format !== "jsonl" && failure === undefined)
|
||||
return false;
|
||||
if (options.tokenCount) {
|
||||
// Incur/tokenx materialize the formatted value. Measure its UTF-16
|
||||
// expansion before allowing that allocation, independently of UTF-8 bytes.
|
||||
// Incur/tokenx materialize JSON. Measure its UTF-16 expansion before
|
||||
// allowing that allocation, independently of UTF-8 bytes. Other formats
|
||||
// retain Incur's materializing behavior.
|
||||
const tokenValue = failure ?? filtered;
|
||||
let characters = 0;
|
||||
if (
|
||||
filtered !== undefined &&
|
||||
filtered !== null &&
|
||||
typeof filtered !== "function" &&
|
||||
typeof filtered !== "symbol"
|
||||
)
|
||||
for (const part of jsonOutputParts(filtered, format))
|
||||
characters += part.length;
|
||||
characters = Math.max(0, characters - 1);
|
||||
if (characters <= constants.MAX_STRING_LENGTH) return false;
|
||||
tokenValue !== undefined &&
|
||||
tokenValue !== null &&
|
||||
typeof tokenValue !== "function" &&
|
||||
typeof tokenValue !== "symbol"
|
||||
) {
|
||||
if (format === "json" || format === "jsonl") {
|
||||
for (const part of jsonOutputParts(
|
||||
tokenValue,
|
||||
format,
|
||||
format === "json",
|
||||
))
|
||||
characters += part.length;
|
||||
characters = Math.max(0, characters - 1);
|
||||
}
|
||||
}
|
||||
if (characters <= constants.MAX_STRING_LENGTH) {
|
||||
if (failure === undefined) return false;
|
||||
handled = true;
|
||||
try {
|
||||
await writeOutputText(
|
||||
destination,
|
||||
`${estimateTokenCount(Formatter.format(failure, format))}\n`,
|
||||
);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
error = projectAnalysisError(
|
||||
new AnalysisResourceConstraintError(
|
||||
metadata.command,
|
||||
@@ -165,10 +196,26 @@ export const createStreamedCliJsonOutput = (
|
||||
),
|
||||
);
|
||||
}
|
||||
const meta = {
|
||||
command: metadata.command,
|
||||
duration: metadata.duration,
|
||||
};
|
||||
const errorDocument =
|
||||
options.fullOutput && failure !== undefined
|
||||
? fullFailureEnvelope(
|
||||
failure,
|
||||
meta,
|
||||
format,
|
||||
options.tokenLimit,
|
||||
options.tokenOffset,
|
||||
)
|
||||
: undefined;
|
||||
const document = options.fullOutput
|
||||
? filtered === undefined
|
||||
? { ok: true, meta }
|
||||
: { ok: true, data: filtered, meta }
|
||||
? failure !== undefined
|
||||
? errorDocument
|
||||
: filtered === undefined
|
||||
? { ok: true, meta }
|
||||
: { ok: true, data: filtered, meta }
|
||||
: filtered === undefined ||
|
||||
filtered === null ||
|
||||
typeof filtered === "function" ||
|
||||
@@ -179,15 +226,24 @@ export const createStreamedCliJsonOutput = (
|
||||
// document from Incur's error formatter.
|
||||
handled = true;
|
||||
try {
|
||||
await writeJsonOutput(
|
||||
error === undefined
|
||||
? document
|
||||
: options.fullOutput
|
||||
? { ok: false, error, meta }
|
||||
: error,
|
||||
destination,
|
||||
format,
|
||||
);
|
||||
if (failure !== undefined && format !== "json" && format !== "jsonl") {
|
||||
// Incur's error sentinel only carries code/message/retryable. Render
|
||||
// the full caller-visible failure at this output boundary.
|
||||
await writeOutputText(
|
||||
destination,
|
||||
`${Formatter.format(document, format)}\n`,
|
||||
);
|
||||
} else {
|
||||
await writeJsonOutput(
|
||||
error === undefined
|
||||
? document
|
||||
: options.fullOutput
|
||||
? { ok: false, error, meta }
|
||||
: error,
|
||||
destination,
|
||||
format as "json" | "jsonl",
|
||||
);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
throw cause;
|
||||
@@ -196,3 +252,26 @@ export const createStreamedCliJsonOutput = (
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const fullFailureEnvelope = (
|
||||
failure: unknown,
|
||||
meta: Readonly<Record<string, unknown>>,
|
||||
format: "json" | "jsonl" | "yaml" | "toon" | "md",
|
||||
tokenLimit: number | undefined,
|
||||
tokenOffset: number | undefined,
|
||||
): Readonly<Record<string, unknown>> => {
|
||||
if (tokenLimit === undefined && tokenOffset === undefined)
|
||||
return { ok: false, error: failure, meta };
|
||||
const formatted = Formatter.format(failure, format);
|
||||
const total = estimateTokenCount(formatted);
|
||||
const offset = tokenOffset ?? 0;
|
||||
const end = tokenLimit === undefined ? total : offset + tokenLimit;
|
||||
if (offset === 0 && end >= total) return { ok: false, error: failure, meta };
|
||||
const actualEnd = Math.min(end, total);
|
||||
const nextOffset = actualEnd < total ? actualEnd : undefined;
|
||||
return {
|
||||
ok: false,
|
||||
error: `${sliceByTokens(formatted, offset, end)}\n[truncated: showing tokens ${offset}–${actualEnd} of ${total}]`,
|
||||
meta: { ...meta, ...(nextOffset === undefined ? {} : { nextOffset }) },
|
||||
};
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { createEvmInterfaceService } from "../composition/evm.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { evmInterfaceModule } from "../composition/evm.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
@@ -14,8 +13,8 @@ export const registerEvmCommands = (
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createEvmInterfaceService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectEvmInterface, {
|
||||
const service = evmInterfaceModule.create(environment);
|
||||
cli.command(evmInterfaceModule.cliCommand, {
|
||||
description: "Infer interface candidates from explicit local EVM bytecode",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local bytecode carrier"),
|
||||
@@ -28,7 +27,7 @@ export const registerEvmCommands = (
|
||||
try {
|
||||
return await logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectEvmInterface,
|
||||
evmInterfaceModule.cliCommand,
|
||||
async () => {
|
||||
const result = await service.inspect(
|
||||
{ path: resolve(args.path), encoding: args.encoding },
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { z } from "incur";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { FlutterBuildAnalysisService } from "../application/flutter/FlutterBuildAnalysisService.js";
|
||||
import type { FlutterBuildAnalysisPort } from "../application/flutter/FlutterBuildAnalysisPort.js";
|
||||
import { createFlutterBuildAnalysisProvider } from "../composition/flutter.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { FlutterOperation } from "../domain/flutter/flutterBuildAnalysis.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** One flutter command: CLI shape and the request it produces. */
|
||||
interface FlutterCommandSpec {
|
||||
readonly command: string;
|
||||
readonly description: string;
|
||||
readonly argumentSchema: z.ZodObject<z.ZodRawShape>;
|
||||
readonly optionSchema?: z.ZodObject<z.ZodRawShape>;
|
||||
readonly operation: FlutterOperation;
|
||||
readonly toInput: (
|
||||
arguments_: Record<string, unknown>,
|
||||
options: Record<string, unknown>,
|
||||
) => unknown;
|
||||
}
|
||||
|
||||
/** Expose the same explicit Flutter requests through one-shot CLI commands. */
|
||||
export const registerFlutterCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
provider: FlutterBuildAnalysisPort = createFlutterBuildAnalysisProvider(),
|
||||
): void => {
|
||||
const specs: readonly FlutterCommandSpec[] = [
|
||||
{
|
||||
command: CLI_COMMANDS.identifyFlutterBuild,
|
||||
description:
|
||||
"Identify a Flutter build's Dart snapshot hash and engine facts by pure APK parsing",
|
||||
argumentSchema: z.object({
|
||||
path: z.string().min(1).describe("Local APK file to inspect"),
|
||||
}),
|
||||
operation: "identify_flutter_build",
|
||||
toInput: (arguments_) => arguments_,
|
||||
},
|
||||
{
|
||||
command: CLI_COMMANDS.inspectDartAot,
|
||||
description:
|
||||
"Inspect one ABI's Dart AOT snapshot: sections, headers, and the string pool",
|
||||
argumentSchema: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Local APK carrying a Flutter payload"),
|
||||
}),
|
||||
optionSchema: z.object({
|
||||
abi: z
|
||||
.string()
|
||||
.min(2)
|
||||
.max(16)
|
||||
.optional()
|
||||
.describe("ABI under lib/ to inspect; defaults to the preferred one"),
|
||||
}),
|
||||
operation: "inspect_dart_aot",
|
||||
toInput: (arguments_, options) => ({
|
||||
path: arguments_.path,
|
||||
...(options.abi === undefined ? {} : { abi: options.abi }),
|
||||
}),
|
||||
},
|
||||
];
|
||||
for (const spec of specs) {
|
||||
cli.command(spec.command, {
|
||||
description: spec.description,
|
||||
...(spec.optionSchema === undefined
|
||||
? { args: spec.argumentSchema }
|
||||
: { args: spec.argumentSchema, options: spec.optionSchema }),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, spec.command, async () => {
|
||||
const settled = await new FlutterBuildAnalysisService(
|
||||
provider,
|
||||
).execute(spec.operation, spec.toInput(args, options ?? {}), {
|
||||
signal,
|
||||
});
|
||||
try {
|
||||
await provider.close();
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisError)
|
||||
return projectAnalysisError(cause);
|
||||
throw cause;
|
||||
}
|
||||
return settled.ok
|
||||
? settled.value
|
||||
: projectAnalysisError(settled.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -220,7 +220,18 @@ export const registerFridaCommands = (
|
||||
(options.scriptFile === undefined)
|
||||
)
|
||||
return projectAnalysisError(
|
||||
new AnalysisInputError(CLI_COMMANDS.instrumentWithFrida),
|
||||
new AnalysisInputError(
|
||||
CLI_COMMANDS.instrumentWithFrida,
|
||||
undefined,
|
||||
[
|
||||
{
|
||||
path: ["script"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Provide exactly one of --script or --script-file.",
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
const remote = remoteFrom(options);
|
||||
const selected =
|
||||
@@ -248,7 +259,17 @@ export const registerFridaCommands = (
|
||||
};
|
||||
if (targetInput === undefined)
|
||||
return projectAnalysisError(
|
||||
new AnalysisInputError(CLI_COMMANDS.instrumentWithFrida),
|
||||
new AnalysisInputError(
|
||||
CLI_COMMANDS.instrumentWithFrida,
|
||||
undefined,
|
||||
[
|
||||
{
|
||||
path: ["target"],
|
||||
reason: "invalid_value",
|
||||
message: "attach mode needs a positive integer process ID.",
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
const result = await withProviderCleanup(() =>
|
||||
service.instrument(
|
||||
|
||||
@@ -82,6 +82,13 @@ export const renderSetupProgress = (event: SetupProgressEvent): void => {
|
||||
writeLine(`${symbol} ${event.label}${suffix}`);
|
||||
};
|
||||
|
||||
/** Show the resolved dry-run plan to a human at an interactive terminal. */
|
||||
export const renderSetupDryRun = (actions: readonly SetupAction[]): void => {
|
||||
intro("REA setup plan", promptStreams);
|
||||
renderPreflight(actions);
|
||||
outro("Dry run complete. No changes were made.", promptStreams);
|
||||
};
|
||||
|
||||
/** Finish an interactive setup journey without exposing the full doctor catalog. */
|
||||
export const renderInteractiveSetupResult = (
|
||||
result: SetupResult,
|
||||
|
||||
@@ -19,13 +19,16 @@ export const writeJsonOutput = async (
|
||||
for (const part of bufferedJsonParts(
|
||||
jsonOutputParts(value, format, isTerminal(destination)),
|
||||
))
|
||||
await writePart(destination, part);
|
||||
await writeOutputText(destination, part);
|
||||
};
|
||||
|
||||
const isTerminal = (destination: Writable): boolean =>
|
||||
"isTTY" in destination && destination.isTTY === true;
|
||||
|
||||
const writePart = (destination: Writable, part: string): Promise<void> =>
|
||||
export const writeOutputText = (
|
||||
destination: Writable,
|
||||
part: string,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const onError = (cause: unknown): void => reject(cause);
|
||||
destination.once("error", onError);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
||||
import { isUpdateFailure } from "../application/UpdateFailure.js";
|
||||
import {
|
||||
confirmInteractiveSetup,
|
||||
renderSetupDryRun,
|
||||
renderInteractiveSetupResult,
|
||||
renderSetupProgress,
|
||||
} from "./interactiveSetup.js";
|
||||
@@ -225,6 +226,8 @@ const runSetupCommand = async (
|
||||
: undefined,
|
||||
);
|
||||
if (interactive) renderInteractiveSetupResult(result, environment);
|
||||
else if (options.dryRun && !input.formatExplicit && hasInteractiveTerminal())
|
||||
renderSetupDryRun(result.plannedActions);
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -282,6 +285,9 @@ const setupIsInteractive = (
|
||||
!options.yes &&
|
||||
!options.dryRun &&
|
||||
!formatExplicit &&
|
||||
hasInteractiveTerminal();
|
||||
|
||||
const hasInteractiveTerminal = (): boolean =>
|
||||
process.stdin.isTTY === true &&
|
||||
process.stdout.isTTY === true &&
|
||||
process.stderr.isTTY === true;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user