refactor(test): keep coverage at behavioral boundaries (#474)
* refactor(test): keep coverage at behavioral boundaries * fix(ci): restore package workflow temp-root classification
This commit is contained in:
@@ -0,0 +1,421 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisProviderRegistry,
|
||||
type AnalysisProviderBinding,
|
||||
} from "./AnalysisProviderRegistry.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
type AnalysisProviderCandidate,
|
||||
type CapabilityDescriptor,
|
||||
type ProviderAvailability,
|
||||
type ProviderIdentity,
|
||||
type ProviderTargetSupport,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { createAnalysisProfile } from "../domain/analysisProfile.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
ProviderAdapterError,
|
||||
ProviderSelectionError,
|
||||
projectAnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
|
||||
const DATABASE_TARGET: BinaryTarget = {
|
||||
path: "/tmp/fixture.hop",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
};
|
||||
const ARTIFACT_TARGET: BinaryTarget = {
|
||||
path: "/tmp/app.asar",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
};
|
||||
|
||||
describe("analysis provider registry: discovery and selection", () => {
|
||||
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
|
||||
expect(registry.identities().map(({ id }) => id)).toEqual([
|
||||
"alpha",
|
||||
"beta",
|
||||
]);
|
||||
expect(
|
||||
registry.candidates().map(({ provider, targetSupport }) => ({
|
||||
id: provider.id,
|
||||
support: targetSupport.status,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "alpha", support: "unknown" },
|
||||
{ id: "beta", support: "unknown" },
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
|
||||
).toThrow(/Duplicate analysis provider ID: alpha/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => {
|
||||
const descriptor = capability(alpha.provider.identity());
|
||||
return [descriptor, descriptor];
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toThrow(/declares operation address_name more than once/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => [
|
||||
capability({
|
||||
...alpha.provider.identity(),
|
||||
name: "mismatched provider",
|
||||
}),
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toThrow(/published mismatched capability provenance/u);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([candidate("auto").provider]),
|
||||
).toThrow(/Invalid analysis provider ID: auto/u);
|
||||
});
|
||||
|
||||
it("selects the sole usable candidate without creating a client", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta", { available: false });
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
|
||||
const selected = await registry.select(DATABASE_TARGET);
|
||||
expect(selected.ok).toBe(true);
|
||||
if (!selected.ok || selected.value.binding === null) return;
|
||||
expect(bindingProjection(selected.value.binding)).toEqual({
|
||||
id: "alpha",
|
||||
source: "auto-single-candidate",
|
||||
version: "1",
|
||||
});
|
||||
expect(selected.value.candidates).toMatchObject([
|
||||
{ provider: { id: "alpha", version: "1" }, selected: true },
|
||||
{
|
||||
provider: { id: "beta" },
|
||||
selected: false,
|
||||
availability: { status: "unavailable", code: "runtime_missing" },
|
||||
},
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
});
|
||||
|
||||
it("makes auto ambiguity explicit and honors request over environment", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry(
|
||||
[alpha.provider, beta.provider],
|
||||
"beta",
|
||||
);
|
||||
|
||||
const environment = await registry.select(DATABASE_TARGET);
|
||||
expect(environment.ok).toBe(true);
|
||||
if (environment.ok)
|
||||
expect(environment.value.binding?.selectionSource).toBe("environment");
|
||||
expect(environment.ok && environment.value.binding?.identity.id).toBe(
|
||||
"beta",
|
||||
);
|
||||
|
||||
const request = await registry.select(DATABASE_TARGET, "alpha");
|
||||
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
|
||||
if (request.ok)
|
||||
expect(request.value.binding?.selectionSource).toBe("request");
|
||||
|
||||
const automatic = await registry.select(DATABASE_TARGET, "auto");
|
||||
expect(automatic.ok).toBe(false);
|
||||
if (automatic.ok) return;
|
||||
expect(automatic.error).toMatchObject({
|
||||
reason: "ambiguous",
|
||||
requestedProviderId: "auto",
|
||||
candidateIds: ["alpha", "beta"],
|
||||
});
|
||||
expect(projectAnalysisError(automatic.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "ambiguous",
|
||||
candidate_ids: ["alpha", "beta"],
|
||||
},
|
||||
});
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis provider registry: binding failures and cancellation", () => {
|
||||
it("returns actionable unknown, unavailable, and unsupported failures", async () => {
|
||||
const unavailable = candidate("alpha", { available: false });
|
||||
const registry = new AnalysisProviderRegistry([unavailable.provider]);
|
||||
|
||||
const unknown = await registry.select(DATABASE_TARGET, "missing");
|
||||
expect(unknown.ok).toBe(false);
|
||||
if (!unknown.ok)
|
||||
expect(projectAnalysisError(unknown.error)).toMatchObject({
|
||||
details: {
|
||||
selection_reason: "unknown_provider",
|
||||
requested_provider_id: "missing",
|
||||
candidate_ids: ["alpha"],
|
||||
},
|
||||
});
|
||||
|
||||
const rejected = await registry.select(DATABASE_TARGET, "alpha");
|
||||
expect(rejected.ok).toBe(false);
|
||||
if (!rejected.ok)
|
||||
expect(projectAnalysisError(rejected.error)).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
rejections: [
|
||||
{
|
||||
provider_id: "alpha",
|
||||
code: "runtime_missing",
|
||||
diagnostics: { executable_path: "/opt/alpha/bin/analyze" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const unsupported = await new AnalysisProviderRegistry([
|
||||
candidate("alpha", { available: false }).provider,
|
||||
]).select(ARTIFACT_TARGET, "alpha");
|
||||
expect(unsupported.ok).toBe(false);
|
||||
if (
|
||||
!unsupported.ok &&
|
||||
unsupported.error instanceof ProviderSelectionError
|
||||
) {
|
||||
expect(unsupported.error).toMatchObject({
|
||||
reason: "target_unsupported",
|
||||
});
|
||||
expect(unsupported.error.rejections.map(({ code }) => code)).toEqual([
|
||||
"runtime_missing",
|
||||
"target_kind_unsupported",
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps artifact-only targets unbound under auto or environment preference", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const environment = new AnalysisProviderRegistry([alpha.provider], "alpha");
|
||||
const automatic = new AnalysisProviderRegistry([alpha.provider]);
|
||||
|
||||
for (const registry of [environment, automatic]) {
|
||||
const selected = await registry.select(ARTIFACT_TARGET);
|
||||
expect(selected).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: null,
|
||||
candidates: [
|
||||
{
|
||||
selected: false,
|
||||
targetSupport: {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
const explicit = await automatic.select(ARTIFACT_TARGET, "alpha");
|
||||
expect(explicit.ok).toBe(false);
|
||||
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
|
||||
expect(explicit.error.reason).toBe("target_unsupported");
|
||||
});
|
||||
|
||||
it("does not bind a profile with unresolved version or adapter failure", async () => {
|
||||
const unresolved = candidate("unresolved", { profile: "missing" });
|
||||
const failed = candidate("failed", { profile: "error" });
|
||||
|
||||
const automatic = await new AnalysisProviderRegistry([
|
||||
unresolved.provider,
|
||||
]).select(DATABASE_TARGET);
|
||||
expect(automatic).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: null,
|
||||
candidates: [
|
||||
{
|
||||
availability: {
|
||||
status: "unavailable",
|
||||
code: "version_unresolved",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const explicit = await new AnalysisProviderRegistry([
|
||||
failed.provider,
|
||||
]).select(DATABASE_TARGET, "failed");
|
||||
expect(explicit.ok).toBe(false);
|
||||
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
|
||||
expect(explicit.error.rejections).toMatchObject([
|
||||
{
|
||||
providerId: "failed",
|
||||
code: "version_unresolved",
|
||||
diagnostics: { error_tag: "ProviderAdapterError" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("cancels a pending profile probe even when the adapter ignores its signal", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
const ignoresCancellation: AnalysisProviderCandidate = {
|
||||
...alpha.provider,
|
||||
resolveAnalysisProfile: (_target, options) => {
|
||||
observedSignal = options?.signal;
|
||||
return new Promise<never>(() => undefined);
|
||||
},
|
||||
};
|
||||
const controller = new AbortController();
|
||||
const selecting = new AnalysisProviderRegistry([
|
||||
ignoresCancellation,
|
||||
]).select(DATABASE_TARGET, "alpha", { signal: controller.signal });
|
||||
expect(observedSignal).toBe(controller.signal);
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(selecting).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
||||
});
|
||||
expect(alpha.created).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
interface CandidateFixture {
|
||||
readonly provider: AnalysisProviderCandidate;
|
||||
readonly created: string[];
|
||||
}
|
||||
|
||||
const candidate = (
|
||||
id: string,
|
||||
options: {
|
||||
readonly available?: boolean;
|
||||
readonly profile?: "resolved" | "missing" | "error";
|
||||
} = {},
|
||||
): CandidateFixture => {
|
||||
const identity: ProviderIdentity = {
|
||||
id,
|
||||
name: `${id} provider`,
|
||||
version: null,
|
||||
};
|
||||
const created: string[] = [];
|
||||
const available = options.available ?? true;
|
||||
const provider: AnalysisProviderCandidate = {
|
||||
identity: () => identity,
|
||||
capabilities: () => [capability(identity)],
|
||||
inspectAvailability: (): ProviderAvailability =>
|
||||
available
|
||||
? {
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
||||
}
|
||||
: {
|
||||
status: "unavailable",
|
||||
code: "runtime_missing",
|
||||
reason: `${id} runtime is unavailable`,
|
||||
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
||||
},
|
||||
inspectTargetSupport: (target): ProviderTargetSupport =>
|
||||
target.kind === "database"
|
||||
? {
|
||||
status: "supported",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: { target_kind: target.kind },
|
||||
}
|
||||
: {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
reason: `${id} only accepts analysis databases in this fixture`,
|
||||
diagnostics: { target_kind: target.kind },
|
||||
},
|
||||
resolveAnalysisProfile: () => {
|
||||
if (options.profile === "error")
|
||||
return Promise.resolve(
|
||||
err(new ProviderAdapterError(id, "resolve_analysis_profile")),
|
||||
);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile:
|
||||
options.profile === "missing"
|
||||
? null
|
||||
: createAnalysisProfile(
|
||||
{ id, name: identity.name, version: "1" },
|
||||
1,
|
||||
{ fixture: id },
|
||||
),
|
||||
compatibility: {},
|
||||
}),
|
||||
);
|
||||
},
|
||||
createClient: (_target, profile): AnalysisClient => {
|
||||
created.push(id);
|
||||
const executionIdentity = profile?.provider ?? identity;
|
||||
return {
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
operation === "health" ? null : `${id}:${operation}`,
|
||||
executionIdentity,
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
},
|
||||
};
|
||||
return { provider, created };
|
||||
};
|
||||
|
||||
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: { maxResults: null, maxPayloadBytes: 1_000, timeoutMs: 1_000 },
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const bindingProjection = (binding: AnalysisProviderBinding) => ({
|
||||
id: binding.identity.id,
|
||||
source: binding.selectionSource,
|
||||
version: binding.identity.version,
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import type { DoctorHost } from "./Doctor.js";
|
||||
|
||||
/** Healthy recording host for focused doctor and projection tests. */
|
||||
export const createDoctorHostFixture = (
|
||||
overrides: Partial<DoctorHost> = {},
|
||||
): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("14.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
|
||||
import { runDoctor } from "./Doctor.js";
|
||||
|
||||
describe("doctor runtime executable diagnostics", () => {
|
||||
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
runtimeExecutables: () =>
|
||||
Promise.resolve({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/healthy/node",
|
||||
canonical_path: "/healthy/node",
|
||||
path_index: null,
|
||||
selection: "rea-launcher",
|
||||
version: "v24.18.0",
|
||||
healthy: true,
|
||||
failure: null,
|
||||
},
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/opt/homebrew/bin/node",
|
||||
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
|
||||
path_index: 2,
|
||||
selection: "path-shadowed",
|
||||
version: null,
|
||||
healthy: false,
|
||||
failure: {
|
||||
code: "runtime_dynamic_library_missing",
|
||||
exit_code: 134,
|
||||
signal: null,
|
||||
dependency:
|
||||
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
|
||||
stderr: "dyld: Library not loaded",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.runtime_executables).toMatchObject({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{ healthy: true, selection: "rea-launcher" },
|
||||
{
|
||||
healthy: false,
|
||||
failure: { code: "runtime_dynamic_library_missing" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "node-toolchains"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("Do not create"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,429 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
|
||||
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
|
||||
import { runDoctor } from "./Doctor.js";
|
||||
|
||||
describe("doctor", () => {
|
||||
it("returns exact recovery for every failed diagnostic", async () => {
|
||||
const result = await runDoctor(
|
||||
"/missing/app",
|
||||
host({
|
||||
nodeVersion: "20.0.0",
|
||||
macosVersion: () => Promise.resolve("11.7"),
|
||||
executable: () => Promise.resolve(false),
|
||||
validTarget: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
Object.fromEntries(
|
||||
result.checks.map(({ name, remediation }) => [name, remediation]),
|
||||
),
|
||||
).toEqual({
|
||||
node: "Install Node.js 22.19+ or 24.11+.",
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
target: "Supply a readable local app or program path.",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["11.7", undefined])(
|
||||
"rejects unsupported macOS version %s",
|
||||
async (version) => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ macosVersion: () => Promise.resolve(version) }),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("admits only the experimental Windows x64 host boundary", async () => {
|
||||
const windows = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
const arm = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "arm64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(windows.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(arm.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: false,
|
||||
detail: "win32 arm64",
|
||||
});
|
||||
});
|
||||
it("detects a manual configured Hopper before Homebrew", async () => {
|
||||
let brewProbes = 0;
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: "/manual/Hopper",
|
||||
executable: (path) => Promise.resolve(path === "/manual/Hopper"),
|
||||
brewHopperPath: () => {
|
||||
brewProbes += 1;
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe("/manual/Hopper");
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(brewProbes).toBe(0);
|
||||
});
|
||||
|
||||
it("reports optional BYO ilspycmd diagnostics only when configured", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/tools/ilspycmd",
|
||||
ilspyCmdVersion: (path) =>
|
||||
Promise.resolve(
|
||||
path === "/tools/ilspycmd" ? "ilspycmd: 9.1.0.7988" : undefined,
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
detail: "/tools/ilspycmd (ilspycmd: 9.1.0.7988)",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports configured ilspycmd drift without installing it", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/missing/ilspycmd",
|
||||
ilspyCmdVersion: () => Promise.resolve(undefined),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "/missing/ilspycmd",
|
||||
remediation:
|
||||
"Unset REA_ILSPY_CMD_PATH or point it at a runnable ilspycmd executable.",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not fall back when the configured Hopper launcher is invalid", async () => {
|
||||
const configuredPath = "/invalid/custom/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ configuredHopperPath: configuredPath }),
|
||||
);
|
||||
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks.find(({ name }) => name === "hopper")).toEqual({
|
||||
name: "hopper",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: configuredPath,
|
||||
remediation:
|
||||
"Unset or update HOPPER_LAUNCHER_PATH to an executable Hopper launcher.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor installation identity", () => {
|
||||
it("distinguishes stale skills, path shadowing, and unobservable live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
installationPaths: () =>
|
||||
Promise.resolve(["/usr/local/bin/rea", "/home/user/bin/rea"]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: "10",
|
||||
toolCount: null,
|
||||
catalogDigest: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
installations: { state: "multiple" },
|
||||
skill: {
|
||||
installed_version: "10",
|
||||
state: "stale",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("reports a missing installed skill as unhealthy", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ installedSkillIdentity: () => Promise.resolve(undefined) }),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.skill).toMatchObject({
|
||||
state: "missing",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "skill:identity",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "Installed REA skill identity is missing.",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
});
|
||||
it("reports stale client registration paths without claiming live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
clientRegistrations: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale",
|
||||
remediation:
|
||||
"Run rea setup to refresh this registration, then restart the client.",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
registrations: [{ client: "codex", state: "stale" }],
|
||||
});
|
||||
expect(result.checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "registration:codex",
|
||||
classification: "config_drift",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor scoped readiness", () => {
|
||||
it("scopes effective readiness to selected clients without hiding drift", async () => {
|
||||
const registrations: readonly ClientRegistrationStatus[] = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/current/rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
config_path: "/home/user/.cursor/mcp.json",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale",
|
||||
remediation: "Run rea setup to refresh this registration.",
|
||||
},
|
||||
];
|
||||
const scoped = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["codex"] },
|
||||
);
|
||||
|
||||
expect(scoped).toMatchObject({
|
||||
healthy: true,
|
||||
environment_healthy: false,
|
||||
scope: { mode: "explicit", clients: ["codex"] },
|
||||
});
|
||||
expect(scoped.scope_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:codex", ok: true }),
|
||||
);
|
||||
expect(scoped.informational_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:cursor", ok: false }),
|
||||
);
|
||||
|
||||
const staleSelected = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["cursor"] },
|
||||
);
|
||||
expect(staleSelected.healthy).toBe(false);
|
||||
});
|
||||
|
||||
it("requires explicitly selected providers instead of any available provider", async () => {
|
||||
const ghidra = {
|
||||
id: "ghidra",
|
||||
configured: true,
|
||||
available: true,
|
||||
providerVersion: "12.1.2",
|
||||
registrationEnvironment: { GHIDRA_INSTALL_DIR: "/tools/ghidra" },
|
||||
checks: [
|
||||
{
|
||||
name: "configuration",
|
||||
ok: true,
|
||||
code: null,
|
||||
detail: "/tools/ghidra",
|
||||
remediation: null,
|
||||
classification: "config_drift" as const,
|
||||
},
|
||||
],
|
||||
};
|
||||
const noHopper = host({
|
||||
executable: () => Promise.resolve(false),
|
||||
providerInspections: () => Promise.resolve([ghidra]),
|
||||
});
|
||||
|
||||
const hopper = await runDoctor(undefined, noHopper, {
|
||||
providers: ["hopper"],
|
||||
});
|
||||
expect(hopper).toMatchObject({
|
||||
healthy: false,
|
||||
environment_healthy: true,
|
||||
});
|
||||
|
||||
const selectedGhidra = await runDoctor(undefined, noHopper, {
|
||||
providers: ["ghidra"],
|
||||
});
|
||||
expect(selectedGhidra.healthy).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor Linux and Hopper discovery", () => {
|
||||
it("accepts an officially supported Linux distribution", async () => {
|
||||
const path = "/home/user/.local/share/rea/hopper/bin/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
configuredHopperPath: path,
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
it("reports missing Linux demo-session dependencies", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: "Install Xvfb, xauth, Python 3, libX11, and libXtst.",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-demo-runtime"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("xauth"),
|
||||
});
|
||||
});
|
||||
it("explains how to recover from an unsupported configured launcher", async () => {
|
||||
const path = "/custom/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
configuredHopperPath: path,
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
supportedLinuxHopper: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-version")?.remediation,
|
||||
).toContain("Unset or update HOPPER_LAUNCHER_PATH");
|
||||
});
|
||||
it("detects a Homebrew cask installed outside /Applications", async () => {
|
||||
const path =
|
||||
"/opt/homebrew/Caskroom/hopper/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
brewHopperPath: () => Promise.resolve(path),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("detects a manually installed Hopper application", async () => {
|
||||
const path = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
manualHopperPaths: () => Promise.resolve([path]),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("uses shared app target validation when a target is supplied", async () => {
|
||||
const result = await runDoctor(
|
||||
"/Applications/Notes.app",
|
||||
host({
|
||||
validTarget: (path) =>
|
||||
Promise.resolve(path === "/Applications/Notes.app"),
|
||||
}),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a readable Hopper launcher without execute permission", async () => {
|
||||
const path = "/manual/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: path,
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installLinuxHopper,
|
||||
linuxHopperInstallDisclosure,
|
||||
linuxPackageManagerCommands,
|
||||
linuxSharedLibrariesAvailable,
|
||||
parseLinuxDistribution,
|
||||
type LinuxDistribution,
|
||||
type LinuxHopperDownload,
|
||||
type LinuxHopperInstallHost,
|
||||
type LinuxHopperLauncherStatus,
|
||||
type LinuxPackageFamily,
|
||||
} from "./LinuxHopper.js";
|
||||
|
||||
class RecordingLinuxHost implements LinuxHopperInstallHost {
|
||||
distributionValue: LinuxDistribution | undefined = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
archive = new Uint8Array([1, 2, 3]);
|
||||
archiveOk = true;
|
||||
installSucceeds = true;
|
||||
launcherStatusValue: LinuxHopperLauncherStatus = "ready";
|
||||
downloads: string[] = [];
|
||||
installed: Array<{ family: LinuxPackageFamily; archive: string }> = [];
|
||||
cleaned: string[] = [];
|
||||
|
||||
distribution = (): Promise<LinuxDistribution | undefined> =>
|
||||
Promise.resolve(this.distributionValue);
|
||||
download = (url: string): Promise<LinuxHopperDownload> => {
|
||||
this.downloads.push(url);
|
||||
return Promise.resolve({ ok: this.archiveOk, bytes: this.archive });
|
||||
};
|
||||
createTemporaryDirectory = (): Promise<string> =>
|
||||
Promise.resolve("/tmp/rea test");
|
||||
writeArchive = (): Promise<void> => Promise.resolve();
|
||||
installPackage = (
|
||||
family: LinuxPackageFamily,
|
||||
archive: string,
|
||||
): Promise<boolean> => {
|
||||
this.installed.push({ family, archive });
|
||||
return Promise.resolve(this.installSucceeds);
|
||||
};
|
||||
launcherStatus = (): Promise<LinuxHopperLauncherStatus> =>
|
||||
Promise.resolve(this.launcherStatusValue);
|
||||
cleanup = (path: string): Promise<void> => {
|
||||
this.cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
};
|
||||
}
|
||||
|
||||
describe("Linux Hopper host classification", () => {
|
||||
it.each([
|
||||
['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
|
||||
["ID=fedora\nVERSION_ID=41\n", "rpm"],
|
||||
["ID=arch\n", "arch"],
|
||||
] as const)("accepts an official Hopper distribution", (document, family) => {
|
||||
expect(parseLinuxDistribution(document)).toMatchObject({
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects unresolved or loader-reported shared libraries", () => {
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"libQt6Network.so.6 => not found\nlibc.so.6 => /lib/libc.so.6",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"error while loading shared libraries: libQt6Gui.so.6",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"libQt6Network.so.6 => /usr/lib/libQt6Network.so.6",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'ID=ubuntu\nVERSION_ID="22.04"\n',
|
||||
"ID=fedora\nVERSION_ID=40\n",
|
||||
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
|
||||
])("rejects unsupported vendor/version combinations", (document) => {
|
||||
expect(parseLinuxDistribution(document).supported).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Linux Hopper installation", () => {
|
||||
it("discloses the exact download, integrity evidence, and privileged command", () => {
|
||||
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
|
||||
downloadUrl:
|
||||
"https://www.hopperapp.com:443/downloader/public/Hopper-6.4.2-Linux-demo.deb",
|
||||
expectedBytes: 35_755_772,
|
||||
expectedSha1: "e4f79dff602648a8ff4a88b773875b6bfac0dc65",
|
||||
commands: [
|
||||
"pkexec apt-get install -y <verified-hopper.deb> xvfb xauth python3 libx11-6 libxtst6",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deb", "apt-get"],
|
||||
["rpm", "dnf"],
|
||||
["arch", "pacman"],
|
||||
] as const)("selects the %s native package manager", (family, executable) => {
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
executable,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", false),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
executable: "pkexec",
|
||||
args: expect.arrayContaining([executable, "/tmp/Hopper package"]),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deb", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]],
|
||||
[
|
||||
"rpm",
|
||||
[
|
||||
"xorg-x11-server-Xvfb",
|
||||
"xorg-x11-xauth",
|
||||
"python3",
|
||||
"libX11",
|
||||
"libXtst",
|
||||
],
|
||||
],
|
||||
["arch", ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"]],
|
||||
] as const)(
|
||||
"installs the %s demo-session dependencies",
|
||||
(family, packages) => {
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
args: expect.arrayContaining([...packages]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["deb", "rpm", "arch"] as const)(
|
||||
"downloads, verifies, installs, reads back, and cleans a %s package",
|
||||
async (family) => {
|
||||
const host = new RecordingLinuxHost();
|
||||
host.distributionValue = {
|
||||
id: family,
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
};
|
||||
const result = await installFixture(host);
|
||||
expect(result).toEqual({
|
||||
status: "installed",
|
||||
launcherPath: "/opt/hopper/bin/Hopper",
|
||||
});
|
||||
expect(host.installed).toEqual([
|
||||
{ family, archive: `/tmp/rea test/hopper.${family}` },
|
||||
]);
|
||||
expect(host.cleaned).toEqual(["/tmp/rea test"]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["unsupported host", "unsupported_host"],
|
||||
["package request failure", "download"],
|
||||
["checksum mismatch", "integrity"],
|
||||
["package manager failure", "authorization_or_package_manager"],
|
||||
["missing launcher", "launcher_missing"],
|
||||
["missing runtime", "runtime_dependencies"],
|
||||
["unsupported build", "unsupported_hopper_build"],
|
||||
] as const)("classifies %s", async (scenario, reason) => {
|
||||
const host = new RecordingLinuxHost();
|
||||
if (scenario === "unsupported host")
|
||||
host.distributionValue = {
|
||||
id: "debian",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
if (scenario === "package request failure") host.archiveOk = false;
|
||||
if (scenario === "checksum mismatch") host.archive = new Uint8Array([9]);
|
||||
if (scenario === "package manager failure") host.installSucceeds = false;
|
||||
if (scenario === "missing launcher") host.launcherStatusValue = "missing";
|
||||
if (scenario === "missing runtime")
|
||||
host.launcherStatusValue = "runtime_dependencies";
|
||||
if (scenario === "unsupported build")
|
||||
host.launcherStatusValue = "unsupported_hopper_build";
|
||||
expect(await installFixture(host)).toEqual({
|
||||
status: "failed",
|
||||
reason,
|
||||
});
|
||||
if (host.installed.length > 0)
|
||||
expect(host.cleaned).toEqual(["/tmp/rea test"]);
|
||||
});
|
||||
|
||||
it("cancels before network or mutation", async () => {
|
||||
const host = new RecordingLinuxHost();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect(
|
||||
await installLinuxHopper(host, { signal: controller.signal }),
|
||||
).toEqual({
|
||||
status: "failed",
|
||||
reason: "cancelled",
|
||||
});
|
||||
expect(host.downloads).toEqual([]);
|
||||
expect(host.installed).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
function releasesFor(
|
||||
bytes: Uint8Array,
|
||||
): Record<
|
||||
LinuxPackageFamily,
|
||||
{ filename: string; file_length: string; file_hash: string }
|
||||
> {
|
||||
const release = (extension: string) => ({
|
||||
filename: `https://www.hopperapp.com:443/downloader/public/Hopper.${extension}`,
|
||||
file_length: String(bytes.byteLength),
|
||||
file_hash: createHash("sha1").update(bytes).digest("hex"),
|
||||
});
|
||||
return {
|
||||
deb: release("deb"),
|
||||
rpm: release("rpm"),
|
||||
arch: release("pkg.tar.xz"),
|
||||
};
|
||||
}
|
||||
|
||||
const installFixture = (host: RecordingLinuxHost) =>
|
||||
installLinuxHopper(host, {
|
||||
releases: releasesFor(new Uint8Array([1, 2, 3])),
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installMacHopper,
|
||||
macHopperInstallDisclosure,
|
||||
type MacHopperInstallHost,
|
||||
} from "./MacHopper.js";
|
||||
|
||||
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||
archiveOk = true;
|
||||
valid = true;
|
||||
existing = false;
|
||||
mountSucceeds = true;
|
||||
copySucceeds = true;
|
||||
launcherSucceeds = true;
|
||||
badHash = false;
|
||||
unmounts = 0;
|
||||
cleanups = 0;
|
||||
opens = 0;
|
||||
replaces = false;
|
||||
|
||||
download = (url: string) =>
|
||||
Promise.resolve(
|
||||
url.includes("files-api")
|
||||
? {
|
||||
ok: true,
|
||||
bytes: new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
"OS X": {
|
||||
filename:
|
||||
"https://www.hopperapp.com:443/downloader/public/Hopper-demo.dmg",
|
||||
file_length: String(this.archive.byteLength),
|
||||
file_hash: this.badHash
|
||||
? "0".repeat(40)
|
||||
: createHash("sha1").update(this.archive).digest("hex"),
|
||||
},
|
||||
}),
|
||||
),
|
||||
}
|
||||
: { ok: this.archiveOk, bytes: this.archive },
|
||||
);
|
||||
createTemporaryDirectory = () => Promise.resolve("/tmp/rea-hopper-test");
|
||||
createMountDirectory = () => Promise.resolve();
|
||||
writePackage = () => Promise.resolve();
|
||||
mount = () => Promise.resolve(this.mountSucceeds);
|
||||
unmount = () => {
|
||||
this.unmounts += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||
validBundle = () => Promise.resolve(this.valid);
|
||||
destinationExists = () => Promise.resolve(this.existing);
|
||||
installBundle = (
|
||||
_source: string,
|
||||
_destination: string,
|
||||
_stage: string,
|
||||
replaceExisting: boolean,
|
||||
) => {
|
||||
this.replaces = replaceExisting;
|
||||
return Promise.resolve(this.copySucceeds);
|
||||
};
|
||||
launcherReady = () => Promise.resolve(this.launcherSucceeds);
|
||||
openApplication = () => {
|
||||
this.opens += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
cleanup = () => {
|
||||
this.cleanups += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
destination = () => "/home/user/Applications/Hopper Disassembler.app";
|
||||
}
|
||||
|
||||
describe("macOS Hopper installation", () => {
|
||||
it("discloses network and command boundaries before installation", () => {
|
||||
expect(macHopperInstallDisclosure).toMatchObject({
|
||||
networkOrigins: [
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true",
|
||||
"https://www.hopperapp.com:443/downloader/public/",
|
||||
],
|
||||
});
|
||||
expect(macHopperInstallDisclosure.commands).toContain(
|
||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||
);
|
||||
});
|
||||
|
||||
it("installs, verifies, opens, and cleans the official package", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "installed",
|
||||
launcherPath:
|
||||
"/home/user/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
});
|
||||
expect(host.opens).toBe(1);
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects an integrity mismatch before mounting", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.badHash = true;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "integrity",
|
||||
});
|
||||
expect(host.unmounts).toBe(0);
|
||||
expect(host.cleanups).toBe(0);
|
||||
});
|
||||
|
||||
it("refuses to overwrite an existing application", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.existing = true;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "destination_exists",
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces the managed application when explicitly requested", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.existing = true;
|
||||
|
||||
await expect(
|
||||
installMacHopper({ replaceExisting: true }, host),
|
||||
).resolves.toMatchObject({ status: "installed" });
|
||||
expect(host.replaces).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans and detaches after bundle validation fails", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.valid = false;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "bundle",
|
||||
});
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../contracts/managedWorkflowExamples.js";
|
||||
import {
|
||||
importManagedReconstruction,
|
||||
managedReconstructionImportInputSchema,
|
||||
} from "../domain/managedReconstruction.js";
|
||||
import { managedMemberInspectionSchema } from "../domain/managedArtifact.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { importManagedReconstructionEvidence } from "./ManagedReconstructionService.js";
|
||||
|
||||
const exampleInput = () =>
|
||||
managedReconstructionImportInputSchema.parse(
|
||||
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
|
||||
);
|
||||
|
||||
const exampleMethod = () => {
|
||||
const method = exampleInput().methods[0];
|
||||
if (method === undefined) throw new Error("missing example method");
|
||||
return method;
|
||||
};
|
||||
|
||||
describe("managed decompiler reconstruction import", () => {
|
||||
it("imports decompiler output as inference locked to static IL evidence", () => {
|
||||
const result = importManagedReconstruction(exampleInput());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
schema_version: 1,
|
||||
phase: "reconstruction-import",
|
||||
executed: false,
|
||||
static_observation: {
|
||||
artifact_sha256: "2".repeat(64),
|
||||
mvid: "11112222-3333-4444-9555-666677778888",
|
||||
},
|
||||
decompiler: {
|
||||
name: "ilspycmd",
|
||||
version: "9.1.0.7988",
|
||||
family: "ilspy",
|
||||
},
|
||||
summary: {
|
||||
imported_methods: 1,
|
||||
decompiled_csharp_methods: 1,
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
token: "0x06000001",
|
||||
signature_sha256: "3".repeat(64),
|
||||
normalized_il_sha256: "5".repeat(64),
|
||||
validation: {
|
||||
matched_static_member: true,
|
||||
exact_build_required: true,
|
||||
canonical_observation: false,
|
||||
confidence_floor: "inference",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.reconstruction_id).toMatch(/^mre_[a-f0-9]{64}$/u);
|
||||
expect(result.methods[0]?.reconstruction.text_sha256).toBe(
|
||||
createHash("sha256")
|
||||
.update("internal static void Main() { }")
|
||||
.digest("hex"),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toContain(
|
||||
"metadata and IL observations remain canonical",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects reconstruction text hash drift", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...exampleInput(),
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
reconstruction: {
|
||||
...exampleMethod().reconstruction,
|
||||
text_sha256: "0".repeat(64),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/text hash mismatch/u);
|
||||
});
|
||||
|
||||
it("rejects stale method locks", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...exampleInput(),
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
normalized_il_sha256: "6".repeat(64),
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/does not match/u);
|
||||
});
|
||||
|
||||
it("rejects reconstruction locks for partial CIL without normalized identity", () => {
|
||||
const input = exampleInput();
|
||||
const observed = managedMemberInspectionSchema.parse(
|
||||
input.static_members.normalized_result,
|
||||
);
|
||||
const method = observed.methods.items[0];
|
||||
if (method === undefined) throw new Error("missing observed method");
|
||||
const partial = {
|
||||
...observed,
|
||||
methods: {
|
||||
...observed.methods,
|
||||
items: [
|
||||
{
|
||||
...method,
|
||||
body: {
|
||||
...method.body,
|
||||
status: "partial" as const,
|
||||
normalized_il_sha256: null,
|
||||
truncated_instructions: 1,
|
||||
issue: "instruction limit reached",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
coverage: { state: "partial" as const, issues: [] },
|
||||
};
|
||||
const partialEvidence = createEvidence(
|
||||
undefined,
|
||||
input.static_members.provider,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: partial,
|
||||
rawResult: null,
|
||||
limitations: partial.limitations,
|
||||
},
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...input,
|
||||
static_members: partialEvidence,
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
normalized_il_sha256: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/does not match/u);
|
||||
});
|
||||
|
||||
it("wraps imported reconstruction in Evidence v2", () => {
|
||||
const evidence = importManagedReconstructionEvidence(exampleInput());
|
||||
|
||||
expect(evidence.ok).toBe(true);
|
||||
if (!evidence.ok) return;
|
||||
expect(evidence.value).toMatchObject({
|
||||
operation: "import_managed_reconstruction",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
normalized_result: {
|
||||
phase: "reconstruction-import",
|
||||
methods: [
|
||||
{
|
||||
reconstruction: {
|
||||
kind: "decompiled-csharp",
|
||||
language: "csharp",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { functionDossierSchema } from "../domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../domain/hopperValues.fixture.js";
|
||||
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
|
||||
import { projectNativeApiInspection } from "./NativeApiInspection.js";
|
||||
|
||||
describe("native API inspection", () => {
|
||||
it("projects structured boundary evidence through inspectable substeps", () => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
|
||||
expect(projectNativeApiInspection(dossier)).toMatchObject({
|
||||
schema_version: 1,
|
||||
procedure: { address: "0x401000", name: "fixture_main" },
|
||||
boundary: {
|
||||
available: true,
|
||||
return_type: { data_type: "int", confidence: "medium" },
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [{ address: "0x403000" }],
|
||||
mappings: [
|
||||
{
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
substeps: [
|
||||
{ operation: "analyze_function", status: "completed" },
|
||||
{ operation: "project_native_api_boundary", status: "completed" },
|
||||
{ operation: "preserve_residual_unknowns", status: "completed" },
|
||||
],
|
||||
unsupported_branches: [],
|
||||
residual_unknowns: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves unsupported provider branches as residual unknowns", () => {
|
||||
const value = ghidraFunctionDossier();
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
throw new TypeError("Ghidra dossier fixture is invalid");
|
||||
const dossier = functionDossierSchema.parse(
|
||||
Object.fromEntries(
|
||||
Object.entries(value).filter(([key]) => key !== "native_api"),
|
||||
),
|
||||
);
|
||||
|
||||
expect(projectNativeApiInspection(dossier)).toMatchObject({
|
||||
boundary: { available: false },
|
||||
unsupported_branches: [
|
||||
"structured-boundary-types",
|
||||
"jump-table-data-mapping",
|
||||
],
|
||||
residual_unknowns: [
|
||||
expect.stringContaining("boundary types"),
|
||||
expect.stringContaining("jump table"),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects boundary types placed in the wrong ABI role", () => {
|
||||
const boundary = functionDossierSchema.parse(
|
||||
ghidraFunctionDossier(),
|
||||
).native_api;
|
||||
if (boundary === null || boundary.available !== true)
|
||||
throw new TypeError("Ghidra native API fixture is unavailable");
|
||||
|
||||
expect(
|
||||
nativeApiBoundarySchema.safeParse({
|
||||
...boundary,
|
||||
return_type: { ...boundary.return_type, role: "parameter" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
nativeApiBoundarySchema.safeParse({
|
||||
...boundary,
|
||||
parameters: [
|
||||
{
|
||||
...boundary.return_type,
|
||||
role: "return",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectAnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
describe("process capture error projection", () => {
|
||||
it("reports incomplete cleanup resources without exposing its cause", () => {
|
||||
const projected = projectAnalysisError(
|
||||
new ProcessCaptureError("terminal cleanup failed", {
|
||||
cause: new Error("secret-token"),
|
||||
reason: "cleanup_incomplete",
|
||||
cleanupResources: ["process_group"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { cleanup: "incomplete", resources: ["process_group"] },
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("secret-token");
|
||||
});
|
||||
|
||||
it("projects caller cancellation as completed cleanup", () => {
|
||||
expect(projectAnalysisError(processCaptureCancelled())).toMatchObject({
|
||||
code: "cancelled",
|
||||
category: "cancelled",
|
||||
details: { operation: "process_capture", cleanup: "complete" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import type { ProcessCaptureEventJournalEntry } from "../domain/processCapture.js";
|
||||
import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
|
||||
it("publishes journal entries in capture order and supports nested recording", () => {
|
||||
const journal = createProcessCaptureJournal();
|
||||
const observed: ProcessCaptureEventJournalEntry[] = [];
|
||||
const unsubscribe = journal.subscribe((entry) => observed.push(entry));
|
||||
journal.recordEvent("lifecycle", 0);
|
||||
const settlementEntry = journal.record("lifecycle", 1);
|
||||
unsubscribe();
|
||||
journal.recordEvent("frames", 0);
|
||||
|
||||
expect(journal.entries).toEqual([
|
||||
{ capture_order: 0, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 2, collection: "frames", index: 0 },
|
||||
]);
|
||||
expect(observed).toEqual(journal.entries.slice(0, 2));
|
||||
expect(settlementEntry).toEqual(journal.entries[1]);
|
||||
|
||||
const nestedJournal = createProcessCaptureJournal();
|
||||
const notifications: string[] = [];
|
||||
nestedJournal.subscribe((entry) => {
|
||||
notifications.push(`a:${String(entry.capture_order)}`);
|
||||
if (entry.capture_order === 0) nestedJournal.record("frames", 1);
|
||||
});
|
||||
nestedJournal.subscribe((entry) =>
|
||||
notifications.push(`b:${String(entry.capture_order)}`),
|
||||
);
|
||||
nestedJournal.record("frames", 0);
|
||||
|
||||
expect(notifications).toEqual(["a:0", "b:0", "a:1", "b:1"]);
|
||||
});
|
||||
@@ -0,0 +1,334 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import {
|
||||
buildCaptureResult,
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "./ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "./ProcessNormalization.js";
|
||||
import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import { emptyProcessCapture as emptyCapture } from "../domain/processCapture.fixture.js";
|
||||
|
||||
const base = {
|
||||
approved: true as const,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
it("returns detached terminal and filesystem checkpoint observations", async () => {
|
||||
const observed: string[] = [];
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxFrames: 10,
|
||||
maxBytes: 10_000,
|
||||
normalize: (value) => value,
|
||||
recordEvent: (collection, index) =>
|
||||
observed.push(`${collection}:${String(index)}`),
|
||||
});
|
||||
renderer.write("A", 20);
|
||||
renderer.resize(40, 12, 10);
|
||||
const frames = await renderer.frames();
|
||||
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
|
||||
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
|
||||
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
|
||||
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
|
||||
await renderer.dispose();
|
||||
|
||||
const scenario = parseProcessScenario(base);
|
||||
const checkpoints = new ProcessCheckpoints(
|
||||
scenario,
|
||||
Date.now(),
|
||||
{ files: [], truncated: false },
|
||||
{ signal: undefined },
|
||||
);
|
||||
const first = await checkpoints.finish({ files: [], truncated: false });
|
||||
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
|
||||
const second = await checkpoints.finish({ files: [], truncated: false });
|
||||
expect(second[0]?.name).toBe("before");
|
||||
await checkpoints.dispose();
|
||||
});
|
||||
|
||||
it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
const capture = emptyCapture();
|
||||
const renderedFrames: ProcessCapture["rendered_frames"] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 20,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["first"],
|
||||
serialized_state: "first",
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["second"],
|
||||
serialized_state: "second",
|
||||
},
|
||||
];
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
replay: {
|
||||
httpUrl: "http://127.0.0.1",
|
||||
websocketUrl: "ws://127.0.0.1/ws",
|
||||
events: [],
|
||||
transitions: [],
|
||||
truncated: false,
|
||||
close: () => Promise.resolve(),
|
||||
},
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario(base),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames,
|
||||
interactions: [],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
shimEvents: [],
|
||||
settlement: {
|
||||
state: capture.settlement.state,
|
||||
elapsed_ms: capture.settlement.elapsed_ms,
|
||||
},
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
{
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("admits PTY samples only after stable session and token setup", () => {
|
||||
const initialized = {
|
||||
pid: 100,
|
||||
parent_pid: 10,
|
||||
process_group_id: 100,
|
||||
session_id: 100,
|
||||
startTime: "200",
|
||||
};
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, process_group_id: 10, session_id: 10 },
|
||||
observedRunId: undefined,
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, startTime: "201" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, session_id: null },
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, session_id: null },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const shim = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
shim: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
shim: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_roots: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
|
||||
it("parses bounded scenarios and rejects unordered events", () => {
|
||||
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [
|
||||
{ type: "input", at_ms: 2, data: "a" },
|
||||
{ type: "input", at_ms: 1, data: "b" },
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/unsafe" },
|
||||
}),
|
||||
).toThrow(/reserved/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 31_000, data: "late" }],
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
|
||||
it("requires explicit operator approval for host network access", () => {
|
||||
expect(
|
||||
authorizeProcessScenario(parseProcessScenario(base), {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "none",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "host network access is not approved by operator policy",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses paths and environment outside operator policy", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
...base,
|
||||
environment: { TOKEN: "secret" },
|
||||
});
|
||||
expect(
|
||||
authorizeProcessScenario(scenario, {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "scenario requests an environment variable not allowed by policy",
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
runPairedProcessExperiment,
|
||||
type ProcessCapturePort,
|
||||
} from "./ProcessPairedExperiment.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import {
|
||||
parseProcessCapture,
|
||||
type EnabledProcessExecutionPolicy,
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
import { runSetup } from "./Setup.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("omits an aligned managed skill from an otherwise empty plan", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
const result = await runSetup(options(false), host);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("installs missing Linux demo dependencies for existing Hopper", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.hopper = "/opt/hopper/bin/Hopper";
|
||||
host.linuxDemoRuntimeMissing = true;
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toContain(
|
||||
"install_hopper",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not reinstall Hopper for an unsupported configured path", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.hopper = "/custom/Hopper";
|
||||
host.unsupportedHopperVersion = true;
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).not.toContain(
|
||||
"install_hopper",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a failed Hopper installation without configuring clients", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopperInstallSucceeds = false;
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.code).toBe("download_failed");
|
||||
expect(result.remediation).toBe("Download failed.");
|
||||
expect(host.configurations).toBe(0);
|
||||
});
|
||||
|
||||
it("blocks malformed client configuration before Hopper or file mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
];
|
||||
host.clientInspections.set("codex", {
|
||||
status: "invalid",
|
||||
remediation: "Repair the existing TOML.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe("Codex: Repair the existing TOML.");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("blocks malformed configuration before unrelated writes with an existing provider", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{
|
||||
name: "claude_desktop",
|
||||
displayName: "Claude Desktop",
|
||||
configPath: "/claude.json",
|
||||
},
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
host.clientInspections.set("claude_desktop", {
|
||||
status: "invalid",
|
||||
remediation: "Repair the existing JSON.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
"Claude Desktop: Repair the existing JSON.",
|
||||
);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("plans a client update when Hopper installation changes its desired environment", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
];
|
||||
host.clientInspections.set("codex", { status: "already_current" });
|
||||
|
||||
const result = await runSetup(options(false), host);
|
||||
|
||||
expect(
|
||||
result.plannedActions.map(({ id, operation }) => ({
|
||||
id,
|
||||
operation,
|
||||
})),
|
||||
).toContainEqual({
|
||||
id: "configure_client:codex",
|
||||
operation: "update",
|
||||
});
|
||||
expect(host.configurations).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setup workflow action selection", () => {
|
||||
it("executes only actions selected by the interactive adapter", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() =>
|
||||
Promise.resolve({
|
||||
approved: true,
|
||||
selectedActionIds: ["configure_client:codex"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.plannedActions.map(({ id }) => id)).toEqual([
|
||||
"configure_client:codex",
|
||||
]);
|
||||
expect(result.clients).toEqual({ codex: { status: "configured" } });
|
||||
expect(host.configurations).toBe(1);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"path",
|
||||
"Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"backup",
|
||||
"Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"write",
|
||||
"Agent configuration could not be updated. Check file permissions, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"readback",
|
||||
"Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.",
|
||||
],
|
||||
] as const)("explains %s configuration recovery", async (reason, message) => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
|
||||
host.clientResults.set("internal_client_key", { status: "failed", reason });
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(message);
|
||||
expect(result.remediation).not.toContain("internal_client_key");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import {
|
||||
type ClientConfigurationInspection,
|
||||
type ClientConfigurationResult,
|
||||
type SetupClient,
|
||||
type SetupHost,
|
||||
type SetupOptions,
|
||||
type SetupHopperInstallResult,
|
||||
type SetupProviderEnvironment,
|
||||
} from "./Setup.js";
|
||||
import type { DoctorCheck, DoctorReport, DoctorScope } from "./Doctor.js";
|
||||
import type { LinuxDistribution } from "./LinuxHopper.js";
|
||||
|
||||
/** Recording setup host for service-level planning and recovery tests. */
|
||||
export class FakeSetupHost implements SetupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
nodeVersion = "25.1.0";
|
||||
version: string | undefined = "14.5";
|
||||
distribution: LinuxDistribution | undefined;
|
||||
hopper: string | undefined;
|
||||
ghidra: string | undefined;
|
||||
javaHome: string | undefined;
|
||||
hopperInstallSucceeds = true;
|
||||
skill: "installed" | "unchanged" | "failed" = "installed";
|
||||
clients: readonly SetupClient[] = [];
|
||||
clientResults = new Map<string, ClientConfigurationResult>();
|
||||
clientInspections = new Map<string, ClientConfigurationInspection>();
|
||||
hopperInstalls = 0;
|
||||
hopperReplaceRequests: boolean[] = [];
|
||||
configurations = 0;
|
||||
skillInstalls = 0;
|
||||
doctorCalls = 0;
|
||||
doctorScopes: Array<DoctorScope | undefined> = [];
|
||||
checkedHopperPaths: Array<string | undefined> = [];
|
||||
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
|
||||
doctorHealthy: boolean | undefined;
|
||||
scopedDoctorHealthy: boolean | undefined;
|
||||
linuxDemoRuntimeMissing = false;
|
||||
unsupportedHopperVersion = false;
|
||||
|
||||
constructor(platform: NodeJS.Platform = "darwin") {
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
macosVersion = (): Promise<string | undefined> =>
|
||||
Promise.resolve(this.version);
|
||||
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
|
||||
Promise.resolve(this.distribution);
|
||||
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
|
||||
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
|
||||
Promise.resolve({
|
||||
...(this.hopper === undefined
|
||||
? {}
|
||||
: { HOPPER_LAUNCHER_PATH: this.hopper }),
|
||||
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
|
||||
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
|
||||
});
|
||||
installHopper = (
|
||||
replaceExisting: boolean,
|
||||
): Promise<SetupHopperInstallResult> => {
|
||||
this.hopperInstalls += 1;
|
||||
this.hopperReplaceRequests.push(replaceExisting);
|
||||
this.linuxDemoRuntimeMissing = false;
|
||||
if (this.hopperInstallSucceeds) {
|
||||
this.hopper = "/manual/Hopper";
|
||||
return Promise.resolve({
|
||||
status: "installed",
|
||||
launcherPath: this.hopper,
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
status: "failed",
|
||||
code: "download_failed",
|
||||
remediation: "Download failed.",
|
||||
});
|
||||
};
|
||||
detectedClients = (): Promise<readonly SetupClient[]> =>
|
||||
Promise.resolve(this.clients);
|
||||
configureClient = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
this.configurations += 1;
|
||||
this.configuredProviderEnvironments.push(providerEnvironment);
|
||||
return Promise.resolve(
|
||||
this.clientResults.get(client.name) ?? { status: "configured" },
|
||||
);
|
||||
};
|
||||
clientNeedsConfigure = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
): Promise<boolean> => {
|
||||
this.checkedHopperPaths.push(providerEnvironment.HOPPER_LAUNCHER_PATH);
|
||||
return Promise.resolve(
|
||||
this.clientResults.get(client.name)?.status !== "unchanged",
|
||||
);
|
||||
};
|
||||
inspectClientConfiguration = (
|
||||
client: SetupClient,
|
||||
): Promise<ClientConfigurationInspection> =>
|
||||
Promise.resolve(
|
||||
this.clientInspections.get(client.name) ?? { status: "update" },
|
||||
);
|
||||
skillNeedsInstall = (): Promise<boolean> =>
|
||||
Promise.resolve(this.skill !== "unchanged");
|
||||
installSkill = (): Promise<"installed" | "unchanged" | "failed"> => {
|
||||
this.skillInstalls += 1;
|
||||
return Promise.resolve(this.skill);
|
||||
};
|
||||
doctor = (scope?: DoctorScope): Promise<DoctorReport> => {
|
||||
this.doctorCalls += 1;
|
||||
this.doctorScopes.push(scope);
|
||||
const checks: DoctorCheck[] = [
|
||||
...(this.linuxDemoRuntimeMissing
|
||||
? ([
|
||||
{
|
||||
name: "hopper-demo-runtime",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
},
|
||||
] as const)
|
||||
: []),
|
||||
...(this.unsupportedHopperVersion
|
||||
? ([
|
||||
{
|
||||
name: "hopper-version",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: this.hopper ?? "",
|
||||
},
|
||||
] as const)
|
||||
: []),
|
||||
];
|
||||
const environmentHealthy =
|
||||
this.doctorHealthy ??
|
||||
(this.hopper !== undefined &&
|
||||
!this.linuxDemoRuntimeMissing &&
|
||||
!this.unsupportedHopperVersion);
|
||||
const healthy =
|
||||
scope === undefined
|
||||
? environmentHealthy
|
||||
: (this.scopedDoctorHealthy ?? environmentHealthy);
|
||||
return Promise.resolve({
|
||||
healthy,
|
||||
environment_healthy: environmentHealthy,
|
||||
scope: {
|
||||
mode: scope === undefined ? "audit-wide" : "explicit",
|
||||
clients: scope?.clients ?? [],
|
||||
providers: scope?.providers ?? [],
|
||||
skill: scope?.skill === true,
|
||||
target: null,
|
||||
},
|
||||
scope_checks: checks,
|
||||
informational_checks: [],
|
||||
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
|
||||
checks,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/** Build setup options for approved or planning-only service tests. */
|
||||
export const options = (
|
||||
approved: boolean,
|
||||
installHopper = false,
|
||||
): SetupOptions => ({
|
||||
approved,
|
||||
installHopper,
|
||||
structured: true,
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
registrationPermissionEnvironment,
|
||||
runSetup,
|
||||
type SetupProgressEvent,
|
||||
} from "./Setup.js";
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("propagates only the explicit non-secret investigation root policy", () => {
|
||||
expect(
|
||||
registrationPermissionEnvironment({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
|
||||
AUTHORIZATION: "secret",
|
||||
}),
|
||||
).toEqual({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
|
||||
});
|
||||
expect(registrationPermissionEnvironment({})).toEqual({});
|
||||
});
|
||||
|
||||
it("returns a complete plan without mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(false), host);
|
||||
expect(result.status).toBe("needs_confirmation");
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
"configure_client",
|
||||
"install_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(result.remediation).toBe(
|
||||
"Review the setup plan, then rerun interactively or with --yes.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports ready after an accepted Linux plan installs healthy Hopper", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.appliedActions).toEqual([
|
||||
"installed_hopper",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.remediation).toBeUndefined();
|
||||
});
|
||||
|
||||
it("requires first-run activation after installing Hopper on macOS", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toContain("choose its demo mode");
|
||||
});
|
||||
|
||||
it("declines an interactive plan without mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(false),
|
||||
);
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("treats an empty interactive selection as cancellation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve({ approved: false, selectedActionIds: [] }),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("requires the Hopper flag for unattended setup", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.appliedActions).toEqual(["installed_skill"]);
|
||||
expect(result.remediation).toContain("--install-hopper");
|
||||
expect(result.remediation).toBe(
|
||||
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
|
||||
);
|
||||
});
|
||||
|
||||
it("installs Hopper when unattended authorization is explicit", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.appliedActions).toEqual([
|
||||
"installed_hopper",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.remediation).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reuses existing Hopper and configures detected clients", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "claude", configPath: "/claude.json" },
|
||||
{ name: "cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.appliedActions).toEqual([
|
||||
"configured_claude",
|
||||
"configured_cursor",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setup workflow lifecycle and provider planning", () => {
|
||||
it("reports append-only lifecycle progress for each selected action", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{
|
||||
name: "codex",
|
||||
displayName: "Codex",
|
||||
configPath: "/codex.toml",
|
||||
},
|
||||
];
|
||||
const progress: SetupProgressEvent[] = [];
|
||||
await runSetup(
|
||||
{ ...options(true), onProgress: (event) => progress.push(event) },
|
||||
host,
|
||||
);
|
||||
expect(progress).toEqual([
|
||||
{ actionId: "configure_client:codex", label: "Codex", state: "started" },
|
||||
{
|
||||
actionId: "configure_client:codex",
|
||||
label: "Codex",
|
||||
state: "completed",
|
||||
},
|
||||
{
|
||||
actionId: "install_skill",
|
||||
label: "REA reverse-engineering skill",
|
||||
state: "started",
|
||||
},
|
||||
{
|
||||
actionId: "install_skill",
|
||||
label: "REA reverse-engineering skill",
|
||||
state: "completed",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("plans and propagates BYO Ghidra without installing software", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
host.doctorHealthy = true;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
|
||||
const plan = await runSetup(options(false), host);
|
||||
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"configure_client",
|
||||
]);
|
||||
expect(plan.plannedActions[0]?.detail).toContain(
|
||||
"GHIDRA_INSTALL_DIR=/opt/ghidra_12.1.2_PUBLIC",
|
||||
);
|
||||
expect(plan.plannedActions[0]?.detail).toContain(
|
||||
"JAVA_HOME=/usr/lib/jvm/jdk-21",
|
||||
);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
|
||||
const applied = await runSetup(options(true), host);
|
||||
expect(applied.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configuredProviderEnvironments).toContainEqual({
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
});
|
||||
});
|
||||
|
||||
it("reinstalls existing Hopper when explicitly requested", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
host.clientResults.set("codex", { status: "unchanged" });
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
"configure_client",
|
||||
]);
|
||||
expect(result.appliedActions).toEqual(["installed_hopper"]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(host.hopperReplaceRequests).toEqual([true]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.checkedHopperPaths).toEqual(["/manual/Hopper"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
import { runSetup } from "./Setup.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("records every detected client outcome after an earlier failure", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "first", configPath: "/first.json" },
|
||||
{ name: "second", configPath: "/second.json" },
|
||||
{ name: "third", configPath: "/third.json" },
|
||||
];
|
||||
host.clientResults.set("first", { status: "failed", reason: "write" });
|
||||
host.clientResults.set("second", { status: "configured" });
|
||||
host.clientResults.set("third", { status: "failed", reason: "readback" });
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(host.configurations).toBe(3);
|
||||
expect(result.clients).toEqual({
|
||||
first: { status: "failed", reason: "write" },
|
||||
second: { status: "configured" },
|
||||
third: { status: "failed", reason: "readback" },
|
||||
});
|
||||
expect(result.appliedActions).toEqual(["configured_second"]);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toContain("could not be updated");
|
||||
});
|
||||
|
||||
it("explains skill installation recovery", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "failed";
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
);
|
||||
});
|
||||
|
||||
it("delegates remaining unhealthy checks to doctor remediation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.remediation).toBe(
|
||||
"Run rea doctor and apply each reported remediation.",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses requested readiness scope without hiding environment drift", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
host.scopedDoctorHealthy = true;
|
||||
const readinessScope = {
|
||||
clients: ["codex"],
|
||||
providers: [] as string[],
|
||||
skill: true,
|
||||
};
|
||||
|
||||
const result = await runSetup(
|
||||
{
|
||||
...options(true),
|
||||
proposeHopper: false,
|
||||
installSkill: false,
|
||||
readinessScope,
|
||||
},
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "ready",
|
||||
doctor: { healthy: true, environment_healthy: false },
|
||||
});
|
||||
expect(host.doctorScopes).toEqual(expect.arrayContaining([readinessScope]));
|
||||
});
|
||||
|
||||
it("explains unsupported Node and macOS recovery", async () => {
|
||||
const platformHost = new FakeSetupHost("win32");
|
||||
expect((await runSetup(options(true), platformHost)).remediation).toBe(
|
||||
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
|
||||
);
|
||||
|
||||
const nodeHost = new FakeSetupHost();
|
||||
nodeHost.nodeVersion = "20.0.0";
|
||||
expect((await runSetup(options(true), nodeHost)).remediation).toBe(
|
||||
"Install Node.js 22.19+ or 24.11+ and rerun setup.",
|
||||
);
|
||||
|
||||
const macHost = new FakeSetupHost();
|
||||
macHost.version = "11.7";
|
||||
expect((await runSetup(options(true), macHost)).remediation).toBe(
|
||||
"Upgrade to macOS 12 or newer.",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unsupported hosts before mutation", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.remediation).toBe(
|
||||
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
|
||||
);
|
||||
});
|
||||
|
||||
it("configures BYO Ghidra on Linux outside Hopper's installer matrix", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
host.doctorHealthy = true;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configuredProviderEnvironments).toContainEqual({
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
setupInstallFailure,
|
||||
type HopperInstallFailureReason,
|
||||
} from "./SetupInstallFailure.js";
|
||||
|
||||
describe("setup installer failure projection", () => {
|
||||
it.each([
|
||||
["unsupported_host", "unsupported_host"],
|
||||
["download", "download_failed"],
|
||||
["release_metadata", "download_failed"],
|
||||
["integrity", "integrity_mismatch"],
|
||||
[
|
||||
"authorization_or_package_manager",
|
||||
"authorization_or_package_manager_failed",
|
||||
],
|
||||
["launcher_missing", "launcher_missing"],
|
||||
["runtime_dependencies", "runtime_dependency_unavailable"],
|
||||
["unsupported_hopper_build", "unsupported_hopper_build"],
|
||||
["cancelled", "setup_cancelled"],
|
||||
["destination_exists", "destination_exists"],
|
||||
["mount", "mount_failed"],
|
||||
["bundle", "bundle_invalid"],
|
||||
["copy", "copy_failed"],
|
||||
] as const)("maps %s to %s", (reason, code) => {
|
||||
const result = setupInstallFailure(reason as HopperInstallFailureReason);
|
||||
expect(result).toMatchObject({ status: "failed", code });
|
||||
if (result.status === "failed")
|
||||
expect(result.remediation.length).toBeGreaterThan(20);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runCapabilityStatus, runProviderStatus } from "./DirectAnalysis.js";
|
||||
import { createDoctorHostFixture } from "./Doctor.fixture.js";
|
||||
import { projectDoctorReport } from "./DoctorProjection.js";
|
||||
import { runDoctor, type DoctorHost } from "./Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
|
||||
const doctorHost = (): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("14.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
});
|
||||
import { runDoctor } from "./Doctor.js";
|
||||
|
||||
describe("purpose-specific CLI projections", () => {
|
||||
it("keeps provider and capability summaries concise with explicit full detail", async () => {
|
||||
@@ -59,7 +33,10 @@ describe("purpose-specific CLI projections", () => {
|
||||
});
|
||||
|
||||
it("omits the catalog tool array only from the default doctor projection", async () => {
|
||||
const report = await runDoctor(undefined, doctorHost());
|
||||
const report = await runDoctor(
|
||||
undefined,
|
||||
createDoctorHostFixture({ validTarget: () => Promise.resolve(true) }),
|
||||
);
|
||||
const summary = projectDoctorReport(report, "summary");
|
||||
const full = projectDoctorReport(report, "full");
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectNpmInstallation,
|
||||
runUpgrade,
|
||||
type UpgradeHost,
|
||||
type UpgradeOutput,
|
||||
type NpmInstallationHost,
|
||||
} from "./Upgrade.js";
|
||||
|
||||
class FakeUpgradeHost implements UpgradeHost {
|
||||
latest: string | undefined = "0.6.0";
|
||||
installationResult: { readonly prefix: string } | undefined = {
|
||||
prefix: "/fixture",
|
||||
};
|
||||
installSucceeds = true;
|
||||
installs = 0;
|
||||
output: UpgradeOutput | undefined;
|
||||
syncResult: boolean | undefined = true;
|
||||
syncs = 0;
|
||||
|
||||
latestVersion = (): Promise<string | undefined> =>
|
||||
Promise.resolve(this.latest);
|
||||
installation = (): Promise<{ readonly prefix: string } | undefined> =>
|
||||
Promise.resolve(this.installationResult);
|
||||
installLatest = (
|
||||
_installation: { readonly prefix: string },
|
||||
output: UpgradeOutput,
|
||||
): Promise<boolean> => {
|
||||
this.installs += 1;
|
||||
this.output = output;
|
||||
return Promise.resolve(this.installSucceeds);
|
||||
};
|
||||
syncAgentIntegration = (
|
||||
_output: UpgradeOutput,
|
||||
): Promise<boolean | undefined> => {
|
||||
this.syncs += 1;
|
||||
return Promise.resolve(this.syncResult);
|
||||
};
|
||||
}
|
||||
|
||||
describe("CLI upgrade", () => {
|
||||
it("reports an already-current release without mutation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
|
||||
expect(await runUpgrade("0.6.0", host)).toEqual({
|
||||
status: "current",
|
||||
currentVersion: "0.6.0",
|
||||
latestVersion: "0.6.0",
|
||||
installMethod: "npm",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("upgrades an outdated global npm installation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toEqual({
|
||||
status: "upgraded",
|
||||
previousVersion: "0.5.0",
|
||||
latestVersion: "0.6.0",
|
||||
versionCheck: "available",
|
||||
installMethod: "npm",
|
||||
command: "npm install --global rea-agents@latest",
|
||||
integrationSync: "setup_invoked",
|
||||
clientRestartRequired: true,
|
||||
remediation:
|
||||
"The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed.",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
expect(host.syncs).toBe(1);
|
||||
});
|
||||
|
||||
it("does not mutate when the registry check is unavailable", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
latestVersion: null,
|
||||
reason: "version-check",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["1.10.0", "1.9.0"],
|
||||
["1.0.0", "1.0.0-rc.1"],
|
||||
])(
|
||||
"does not downgrade installed version %s to registry version %s",
|
||||
async (currentVersion, latestVersion) => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = latestVersion;
|
||||
|
||||
expect(await runUpgrade(currentVersion, host)).toEqual({
|
||||
status: "current",
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
installMethod: "npm",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("upgrades a prerelease when the final release is available", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = "1.0.0";
|
||||
|
||||
expect(await runUpgrade("1.0.0-rc.1", host)).toMatchObject({
|
||||
status: "upgraded",
|
||||
previousVersion: "1.0.0-rc.1",
|
||||
latestVersion: "1.0.0",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects invalid registry version metadata without mutation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = "latest";
|
||||
|
||||
expect(await runUpgrade("1.0.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: "latest",
|
||||
reason: "version-check",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves stdout for an explicitly structured CLI response", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.syncResult = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host, "structured")).toMatchObject({
|
||||
status: "upgraded",
|
||||
integrationSync: "deferred",
|
||||
remediation:
|
||||
"Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
|
||||
});
|
||||
|
||||
expect(host.output).toBe("structured");
|
||||
});
|
||||
|
||||
it("refuses to mutate an unrelated installation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.installationResult = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "unknown-install-method",
|
||||
remediation:
|
||||
"Update manually with: npm install --global rea-agents@latest",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("reports npm installation failure", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.installSucceeds = false;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "install",
|
||||
remediation:
|
||||
"REA could not update through npm. Check npm registry access and global install permissions, then run: npm install --global rea-agents@latest",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("npm installation detection", () => {
|
||||
const host = (root: string, prefix = "/usr/local"): NpmInstallationHost => ({
|
||||
canonicalPath: (path) => Promise.resolve(path),
|
||||
globalRoot: () => Promise.resolve(root),
|
||||
globalPrefix: () => Promise.resolve(prefix),
|
||||
});
|
||||
|
||||
it("returns the prefix for the global package that owns the running CLI", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation(
|
||||
"/usr/local/lib/node_modules/rea-agents",
|
||||
host("/usr/local/lib/node_modules"),
|
||||
),
|
||||
).resolves.toEqual({ prefix: "/usr/local" });
|
||||
});
|
||||
|
||||
it("infers the prefix used by the curl installer's custom npm layout", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation(
|
||||
"/home/user/.local/lib/node_modules/rea-agents",
|
||||
host("/usr/local/lib/node_modules"),
|
||||
),
|
||||
).resolves.toEqual({ prefix: "/home/user/.local" });
|
||||
});
|
||||
|
||||
it("rejects a source checkout when a different global copy exists", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation("/work/rea", host("/usr/local/lib/node_modules")),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
|
||||
describe("CdpCaptureCompleteness", () => {
|
||||
it("reports attach-window limitations without claiming a complete history", () => {
|
||||
const capture = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
]);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
conditions: ["attach_limited"],
|
||||
attach_limited_sections: ["console_events", "network_requests"],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("aggregates sparse exclusions and applies explicit status precedence", () => {
|
||||
const capture = new CdpCaptureCompleteness(["network_requests"]);
|
||||
capture.exclude("scripts", "disallowed_origin");
|
||||
capture.exclude("scripts", "disallowed_origin", 2);
|
||||
capture.exclude("storage_keys", "not_approved", null);
|
||||
capture.drop("console_events", 4);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "truncated",
|
||||
conditions: ["attach_limited", "policy_filtered", "truncated"],
|
||||
policy_filtered_sections: ["scripts", "storage_keys"],
|
||||
truncated_sections: ["console_events"],
|
||||
excluded: [
|
||||
{ section: "scripts", reason: "disallowed_origin", count: 3 },
|
||||
{ section: "storage_keys", reason: "not_approved", count: null },
|
||||
],
|
||||
dropped_events: { console_events: 4, total: 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("restores initial attach limitations when reused for a new capture", () => {
|
||||
const capture = new CdpCaptureCompleteness(["websocket_frames"]);
|
||||
capture.drop("scripts");
|
||||
capture.exclude("resources", "provider_unavailable", null);
|
||||
|
||||
capture.reset();
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
attach_limited_sections: ["websocket_frames"],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
captureAccessibility,
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("CDP document capture", () => {
|
||||
it("walks deeply nested frame trees iteratively and retains a bounded prefix", () => {
|
||||
let frameTree: Record<string, unknown> = {
|
||||
frame: { id: "frame-0", url: `${origin}/0` },
|
||||
resources: [{ url: `${origin}/0.js`, type: "Script" }],
|
||||
};
|
||||
for (let index = 1; index < 2_000; index += 1) {
|
||||
frameTree = {
|
||||
frame: {
|
||||
id: `frame-${String(index)}`,
|
||||
url: `${origin}/${String(index)}`,
|
||||
},
|
||||
resources: [{ url: `${origin}/${String(index)}.js`, type: "Script" }],
|
||||
childFrames: [frameTree],
|
||||
};
|
||||
}
|
||||
const result = { frameTree };
|
||||
const frames = captureFrames(result, new Set([origin]), 3);
|
||||
const resources = captureResources(result, new Set([origin]), 2);
|
||||
expect(frames).toMatchObject({ total: 2_000 });
|
||||
expect(frames.items).toHaveLength(3);
|
||||
expect(resources).toMatchObject({ total: 2_000 });
|
||||
expect(resources.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rebases parent indexes when allowed DOM documents are combined", () => {
|
||||
const input = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: [origin],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const snapshot = {
|
||||
strings: [`${origin}/main`, `${origin}/frame`, "#document", "DIV", ""],
|
||||
documents: [
|
||||
{
|
||||
documentURL: 0,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
{
|
||||
documentURL: 1,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const capture = captureDom(snapshot, new Set([origin]), input);
|
||||
expect(capture.nodes.map((node) => node.parent_index)).toEqual([
|
||||
-1, 0, -1, 2,
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds approved accessibility text by UTF-8 bytes without splitting characters", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
role: { value: "button" },
|
||||
name: { value: "😀a" },
|
||||
description: { value: "éé" },
|
||||
childIds: ["missing-child"],
|
||||
properties: [
|
||||
{ name: "disabled", value: { value: true } },
|
||||
{ name: "valuetext", value: { value: "private value" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: true,
|
||||
maximumFieldBytes: 4,
|
||||
maximumTotalBytes: 7,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({
|
||||
name: "😀",
|
||||
description: "é",
|
||||
states: [{ name: "disabled", value: true }],
|
||||
});
|
||||
expect(capture.treeIncomplete).toBe(true);
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
excluded_fields: 0,
|
||||
truncated_fields: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("counts accessibility fields omitted without text approval", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
name: { value: "private name" },
|
||||
description: { value: "private description" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: false,
|
||||
maximumFieldBytes: 1_024,
|
||||
maximumTotalBytes: 64 * 1_024,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({ name: null, description: null });
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
excluded_fields: 2,
|
||||
truncated_fields: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
|
||||
import { PlaywrightBrowserScenarioProvider } from "./PlaywrightBrowserScenarioProvider.js";
|
||||
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioSchema,
|
||||
type BrowserScenario,
|
||||
type BrowserScenarioAction,
|
||||
} from "../domain/browserScenario.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../domain/browserScenarioCapture.js";
|
||||
|
||||
const scenario = (
|
||||
options: {
|
||||
readonly mode?: "launch" | "connect";
|
||||
readonly captures?: readonly (
|
||||
| "screenshot"
|
||||
| "dom"
|
||||
| "accessibility"
|
||||
| "url"
|
||||
| "history"
|
||||
| "storage"
|
||||
)[];
|
||||
readonly events?: readonly (
|
||||
| "console"
|
||||
| "page-errors"
|
||||
| "network"
|
||||
| "websockets"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "downloads"
|
||||
)[];
|
||||
readonly actions?: number;
|
||||
} = {},
|
||||
): BrowserScenario =>
|
||||
browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser:
|
||||
options.mode === "connect"
|
||||
? {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
}
|
||||
: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: Array.from({ length: options.actions ?? 1 }, (_, index) => ({
|
||||
step_id: `wait_${index}`,
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
})),
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
at_end: [],
|
||||
events: options.events ?? [],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 16_384,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
|
||||
const artifactState = (
|
||||
kind: SnapshotKind,
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
incomplete: boolean,
|
||||
) => {
|
||||
if (!requested.has(kind)) return { state: "not_requested" as const };
|
||||
if (kind === "url")
|
||||
return {
|
||||
state: "captured" as const,
|
||||
value: sanitizeBrowserUrl("https://app.example.test/current"),
|
||||
};
|
||||
if (incomplete && kind === "screenshot")
|
||||
return {
|
||||
state: "truncated" as const,
|
||||
observed: 2_048,
|
||||
retained: 0,
|
||||
reason: "fixture limit",
|
||||
};
|
||||
return { state: "missing" as const, reason: "fixture unavailable" };
|
||||
};
|
||||
|
||||
class FakeSession implements BrowserScenarioSessionPort {
|
||||
readonly product = "Fake Chromium";
|
||||
readonly version = "1";
|
||||
readonly initialUrl = "about:blank";
|
||||
readonly processOwnership: "provider-owned" | "external";
|
||||
closeCalls = 0;
|
||||
performCalls = 0;
|
||||
captureCalls = 0;
|
||||
eventTruncations: (
|
||||
| "events"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "websockets"
|
||||
)[] = [];
|
||||
onPerform: (() => void) | undefined;
|
||||
private step = 0;
|
||||
|
||||
constructor(
|
||||
readonly mode: "launch" | "connect",
|
||||
private readonly incomplete = false,
|
||||
private readonly failAction = false,
|
||||
private readonly failCapture = false,
|
||||
) {
|
||||
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
|
||||
}
|
||||
|
||||
currentUrl() {
|
||||
return "https://app.example.test/current";
|
||||
}
|
||||
|
||||
setStep(index: number) {
|
||||
this.step = index;
|
||||
}
|
||||
|
||||
nextEventSequence() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
lastEventSequence() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
events(): {
|
||||
readonly retained: number;
|
||||
readonly dropped: number;
|
||||
readonly items: readonly BrowserScenarioEvent[];
|
||||
} {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
|
||||
eventTruncationSections() {
|
||||
return this.eventTruncations;
|
||||
}
|
||||
|
||||
async perform(
|
||||
_action: BrowserScenarioAction,
|
||||
_timeout: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
this.performCalls += 1;
|
||||
this.onPerform?.();
|
||||
if (signal?.aborted === true) throw new Error("request cancelled");
|
||||
if (this.failAction) throw new Error("fixture secret action failure");
|
||||
}
|
||||
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
_budget: BrowserScenarioCaptureBudget,
|
||||
): Promise<BrowserStepArtifacts> {
|
||||
this.captureCalls += 1;
|
||||
if (this.failCapture) return Promise.reject(new Error("capture failed"));
|
||||
return Promise.resolve(
|
||||
browserStepArtifactsSchema.parse({
|
||||
screenshot: artifactState("screenshot", requested, this.incomplete),
|
||||
dom: artifactState("dom", requested, this.incomplete),
|
||||
accessibility: artifactState(
|
||||
"accessibility",
|
||||
requested,
|
||||
this.incomplete,
|
||||
),
|
||||
url: artifactState("url", requested, this.incomplete),
|
||||
history: artifactState("history", requested, this.incomplete),
|
||||
storage: artifactState("storage", requested, this.incomplete),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closeCalls += 1;
|
||||
return Promise.resolve(
|
||||
this.mode === "launch"
|
||||
? ("terminated-owned-process" as const)
|
||||
: ("disconnected-external" as const),
|
||||
);
|
||||
}
|
||||
|
||||
redactError(error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message.replaceAll("secret", "[REDACTED]")
|
||||
: "fixture failure";
|
||||
}
|
||||
}
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
it("captures initial and action steps and closes its launched session", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
|
||||
0, 1,
|
||||
]);
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("makes missing and truncated captures ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch", true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ captures: ["screenshot", "dom"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
it("makes event limit truncation ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
session.eventTruncations = ["events", "websockets"];
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ events: ["websockets"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
truncated_sections: ["events", "websockets"],
|
||||
});
|
||||
});
|
||||
|
||||
it("records one failed step, cancels later actions, and still cleans up", async () => {
|
||||
const session = new FakeSession("launch", false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario({ actions: 2 }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ status }) => status)).toEqual([
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]);
|
||||
expect(result.value.steps[1]?.error).toBe(
|
||||
"fixture [REDACTED] action failure",
|
||||
);
|
||||
expect(session.performCalls).toBe(1);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
expect(result.value.completeness.equality_eligible).toBe(false);
|
||||
});
|
||||
|
||||
it("disconnects external CDP sessions and marks pre-attach events missing", async () => {
|
||||
const session = new FakeSession("connect");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ mode: "connect" }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["events"],
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("closes the session when initial capture fails", async () => {
|
||||
const session = new FakeSession("launch", false, false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(false);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not open a session for an already-cancelled request", async () => {
|
||||
let opens = 0;
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => {
|
||||
opens += 1;
|
||||
return Promise.resolve(new FakeSession("launch"));
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(opens).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels an active action and still closes the session", async () => {
|
||||
const controller = new AbortController();
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => controller.abort();
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps[1]?.status).toBe("cancelled");
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BrowserScenarioCaptureBudget", () => {
|
||||
it("enforces cumulative screenshot and metadata limits", () => {
|
||||
const budget = new BrowserScenarioCaptureBudget(1, 10);
|
||||
expect(budget.claimScreenshot()).toBe(true);
|
||||
expect(budget.claimScreenshot()).toBe(false);
|
||||
expect(budget.claimMetadata(6)).toBe(true);
|
||||
expect(budget.claimMetadata(5)).toBe(false);
|
||||
expect(budget.claimMetadata(4)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
electronActiveObservationInputSchema,
|
||||
electronActiveObservationResultSchema,
|
||||
} from "../domain/electronActiveObservation.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../domain/electronActiveObservation.fixture.js";
|
||||
import { runElectronActions } from "./PlaywrightElectronActiveActions.js";
|
||||
|
||||
it("parses bounded window, renderer, and deep-link actions for agents", () => {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{ step_id: "first-window", kind: "click", selector: "#run" },
|
||||
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
|
||||
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
|
||||
{
|
||||
step_id: "deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
|
||||
expect(input.actions).toEqual([
|
||||
{
|
||||
step_id: "first-window",
|
||||
kind: "click",
|
||||
selector: "#run",
|
||||
window_index: 0,
|
||||
},
|
||||
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
|
||||
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
|
||||
{
|
||||
step_id: "deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects non-absolute deep-link values", () => {
|
||||
const result = electronActiveObservationInputSchema.safeParse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{
|
||||
step_id: "bad-link",
|
||||
kind: "deep-link",
|
||||
delivery: "open-url",
|
||||
url: "not a URL",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts action inputs from Playwright failures", async () => {
|
||||
const selector = "#secret-selector";
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [{ step_id: "click-step", kind: "click", selector }],
|
||||
approved: true,
|
||||
});
|
||||
const page = {
|
||||
locator: () => ({
|
||||
click: async () => {
|
||||
throw new Error(`locator ${selector} failed with token=raw-secret`);
|
||||
},
|
||||
}),
|
||||
};
|
||||
const application = {
|
||||
windows: () => [page],
|
||||
};
|
||||
|
||||
const result = await runElectronActions(
|
||||
application as never,
|
||||
input,
|
||||
{},
|
||||
Date.now() + 1_000,
|
||||
);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
status: "failed",
|
||||
error: "locator <redacted-input> failed with token=[REDACTED]",
|
||||
});
|
||||
expect(result[0]?.error).not.toContain(selector);
|
||||
expect(result[0]?.error).not.toContain("raw-secret");
|
||||
});
|
||||
|
||||
it("runs an untargeted deep-link without requiring a BrowserWindow", async () => {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{
|
||||
step_id: "open-deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
const application = {
|
||||
windows: () => [],
|
||||
evaluate: async () => true,
|
||||
};
|
||||
|
||||
const result = await runElectronActions(
|
||||
application as never,
|
||||
input,
|
||||
{},
|
||||
Date.now() + 1_000,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject([
|
||||
{
|
||||
step_id: "open-deep-link",
|
||||
status: "completed",
|
||||
error: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects action outcomes that disagree with their error state", () => {
|
||||
const result = createElectronActiveObservationFixtureResult("/opt/app");
|
||||
const action = result.actions[0];
|
||||
expect(action).toBeDefined();
|
||||
if (action === undefined) return;
|
||||
|
||||
expect(
|
||||
electronActiveObservationResultSchema.safeParse({
|
||||
...result,
|
||||
actions: [{ ...action, error: "unexpected failure" }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
electronActiveObservationResultSchema.safeParse({
|
||||
...result,
|
||||
actions: [{ ...action, status: "failed", error: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
25,
|
||||
);
|
||||
const rejection =
|
||||
expect(result).rejects.toBeInstanceOf(AnalysisTimeoutError);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
});
|
||||
|
||||
it("rejects when the caller cancels active work", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
1_000,
|
||||
controller.signal,
|
||||
);
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Page } from "playwright-core";
|
||||
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
|
||||
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
|
||||
|
||||
describe("PlaywrightScenarioEvents", () => {
|
||||
it("bounds oversized page errors before validating captured events", () => {
|
||||
const listeners = new Map<string, (value: Error) => void>();
|
||||
const page = {
|
||||
url: () => "https://app.example.test/",
|
||||
on: (name: string, listener: (value: Error) => void) => {
|
||||
listeners.set(name, listener);
|
||||
},
|
||||
} as unknown as Page;
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "wait",
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: [],
|
||||
at_end: [],
|
||||
events: ["page-errors"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 10,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 1,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 1_000_000,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
if (secrets === undefined) throw new Error("Expected resolved secrets");
|
||||
const events = new PlaywrightScenarioEvents({
|
||||
page,
|
||||
enabled: new Set(["page-errors"]),
|
||||
limits: scenario.limits,
|
||||
secrets,
|
||||
budget: new BrowserScenarioCaptureBudget(1, 1_000_000),
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
const error = new Error("m".repeat(70_000));
|
||||
error.stack = "s".repeat(300_000);
|
||||
|
||||
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
|
||||
expect(events.result().items[0]).toMatchObject({
|
||||
kind: "page-error",
|
||||
message: "m".repeat(65_536),
|
||||
stack: "s".repeat(262_144),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isCliOperationFailure } from "./cliLogging.js";
|
||||
|
||||
describe("CLI operation status classification", () => {
|
||||
it.each([
|
||||
["typed error", { error: "Analysis failed", category: "timeout" }],
|
||||
["unhealthy diagnostic", { healthy: false, checks: [] }],
|
||||
["failed status", { status: "failed" }],
|
||||
["confirmation requirement", { status: "needs_confirmation" }],
|
||||
["human remediation", { status: "needs_human" }],
|
||||
["unapplied plan", { status: "planned" }],
|
||||
])("classifies %s as failure", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["ready setup", { status: "ready" }],
|
||||
["complete uninstall", { status: "complete" }],
|
||||
["current version", { status: "current" }],
|
||||
["completed upgrade", { status: "upgraded" }],
|
||||
["healthy diagnostics", { healthy: true, checks: [] }],
|
||||
["bounded evidence", { evidence: [{ truncated: true }] }],
|
||||
])("keeps %s successful", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("configuration parsing integration", () => {
|
||||
it("returns defaults when no environment variables are set", () => {
|
||||
const result = parseConfig({});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe(
|
||||
process.platform === "linux"
|
||||
? "/opt/hopper/bin/Hopper"
|
||||
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
);
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([]);
|
||||
expect(result.value.analysisProvider).toBe("auto");
|
||||
});
|
||||
|
||||
it("parses a complete target-bound configuration", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/usr/bin/true",
|
||||
HOPPER_TARGET_KIND: "executable",
|
||||
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/tmp/releases"]',
|
||||
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.analysisProvider).toBe("hopper");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([
|
||||
"-l",
|
||||
"Mach-O",
|
||||
"--aarch64",
|
||||
]);
|
||||
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
|
||||
expect(result.value.investigationInputRoots).toEqual(["/tmp/releases"]);
|
||||
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
|
||||
"/tmp/analysis",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects target kind values outside the enum", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_KIND: "archive",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("Invalid REA environment");
|
||||
});
|
||||
|
||||
it("rejects invalid JSON in loader arguments", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: "not json",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("valid JSON");
|
||||
});
|
||||
|
||||
it("rejects non-array types in loader arguments JSON", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: '"just a string"',
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("array of strings");
|
||||
});
|
||||
|
||||
it("allows overriding the launcher path while keeping other defaults", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LAUNCHER_PATH: "/custom/hopper",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses database target kind correctly", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/path/to/file.hop",
|
||||
HOPPER_TARGET_KIND: "database",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetKind).toBe("database");
|
||||
});
|
||||
});
|
||||
@@ -1,72 +1,2 @@
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { digestProcessCommitment } from "../domain/processCapture.js";
|
||||
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: JsonValue[] = [];
|
||||
const replayPlan = {};
|
||||
|
||||
/** Minimal valid process capture used only in public contract examples. */
|
||||
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "1.1.0",
|
||||
provider_version: "3",
|
||||
platform: "fixture",
|
||||
architecture: "fixture",
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
} satisfies JsonValue;
|
||||
/** Minimal valid process capture retained as a public contract example. */
|
||||
export { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCaptureExample.js";
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
ArtifactOperationError,
|
||||
BinaryTargetError,
|
||||
HopperProcessError,
|
||||
PermissionRequiredError,
|
||||
ProviderAdapterError,
|
||||
ReplayPlanStaleError,
|
||||
UnknownRegistryError,
|
||||
projectAnalysisError,
|
||||
} from "./errors.js";
|
||||
|
||||
describe("analysis error projection: provider failures", () => {
|
||||
it("preserves detached, actionable provider diagnostics", () => {
|
||||
const diagnostics = {
|
||||
runtime_root: "/tmp/rea-ghidra-fixture",
|
||||
profile_digest: "a".repeat(64),
|
||||
exit_code: 1,
|
||||
};
|
||||
const error = new ProviderAdapterError("ghidra", "health", {
|
||||
diagnostics,
|
||||
});
|
||||
|
||||
expect(error.diagnostics).not.toBe(diagnostics);
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
details: {
|
||||
provider_id: "ghidra",
|
||||
operation: "health",
|
||||
diagnostics,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps the Linux startup compatibility exit codes without host internals", () => {
|
||||
const expected = [
|
||||
[70, "private_display_unavailable"],
|
||||
[71, "x11_authorization_failed"],
|
||||
[72, "unsupported_hopper_build"],
|
||||
[73, "invalid_launch_command"],
|
||||
[74, "process_ownership_mismatch"],
|
||||
[75, "hopper_exited_during_startup"],
|
||||
[76, "unsupported_demo_dialog"],
|
||||
[77, "unexpected_display_geometry"],
|
||||
[78, "x11_input_failed"],
|
||||
[79, "runtime_dependency_unavailable"],
|
||||
[80, "x11_socket_directory_unusable"],
|
||||
] as const;
|
||||
|
||||
for (const [exitCode, code] of expected) {
|
||||
const projected = projectAnalysisError(new HopperProcessError(exitCode));
|
||||
expect(projected).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: { failure_code: code, exit_code: exitCode },
|
||||
});
|
||||
expect(projected.message.length).toBeGreaterThan(20);
|
||||
expect(JSON.stringify(projected)).not.toContain("/proc/");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: caller contract", () => {
|
||||
it("maps representative failures without exposing causes", () => {
|
||||
const secretCause = new Error("secret-token");
|
||||
const projected = [
|
||||
projectAnalysisError(
|
||||
new AnalysisInputError("overview", { cause: secretCause }),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new AnalysisCapabilityUnavailableError("fixture", "overview", "absent"),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new BinaryTargetError("/local/targets/app", "invalid", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new ReplayPlanStaleError("a".repeat(64), "b".repeat(64)),
|
||||
),
|
||||
];
|
||||
|
||||
expect(projected.map(({ code }) => code)).toEqual([
|
||||
"invalid_request",
|
||||
"capability_unavailable",
|
||||
"target_unavailable",
|
||||
"plan_stale",
|
||||
]);
|
||||
expect(projected[1]).toMatchObject({ category: "unsupported_provider" });
|
||||
expect(projected[2]).toMatchObject({
|
||||
details: { path: "/local/targets/app" },
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("secret-token");
|
||||
});
|
||||
|
||||
it("preserves exact artifact-integrity coordinates", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "integrity", {
|
||||
logicalPath: "main.js",
|
||||
declaredSha256: "a".repeat(64),
|
||||
calculatedSha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
category: "integrity_mismatch",
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: "a".repeat(64),
|
||||
calculated_sha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"configure",
|
||||
false,
|
||||
false,
|
||||
"Add the exact missing scope beneath the administrator ceiling, then retry.",
|
||||
],
|
||||
[
|
||||
"elicit",
|
||||
false,
|
||||
true,
|
||||
"Approve the exact missing scope, then retry the operation.",
|
||||
],
|
||||
[
|
||||
"restart",
|
||||
true,
|
||||
false,
|
||||
"Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.",
|
||||
],
|
||||
] as const)(
|
||||
"projects %s permission remediation into stable protocol fields",
|
||||
(remediation, restartRequired, elicitationSupported, action) => {
|
||||
const projected = projectAnalysisError(
|
||||
new PermissionRequiredError({
|
||||
requested: {
|
||||
capability: "evidence_read",
|
||||
roots: ["/workspace/evidence.json"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:evidence",
|
||||
},
|
||||
missing: { roots: ["/workspace/evidence.json"] },
|
||||
ceiling: null,
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projected.remediation).toEqual({
|
||||
action,
|
||||
restart_required: restartRequired,
|
||||
elicitation_supported: elicitationSupported,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("gives missing residual unknowns lookup-specific remediation", () => {
|
||||
expect(
|
||||
projectAnalysisError(new UnknownRegistryError("not-found")),
|
||||
).toMatchObject({
|
||||
code: "execution_failure",
|
||||
message:
|
||||
"The requested residual unknown does not exist in this session. Check the unknown_id and try again.",
|
||||
remediation: {
|
||||
action:
|
||||
"Check that the unknown_id belongs to this session, then retry.",
|
||||
},
|
||||
details: { reason: "not-found" },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains schema-authored input guidance", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new AnalysisInputError("find_changed_behavior", undefined, [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes disabled integrity continuation from format support", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "policy"),
|
||||
),
|
||||
).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
category: "unavailable",
|
||||
message: expect.stringContaining(
|
||||
"REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true",
|
||||
),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analyzeBytecodeArtifacts,
|
||||
bytecodeAnalysisSchema,
|
||||
classifyProvenance,
|
||||
detectArtifactFormat,
|
||||
detectBytecodeFamily,
|
||||
type BytecodeArtifact,
|
||||
} from "./bytecodeProvider.js";
|
||||
|
||||
describe("bytecode provider", () => {
|
||||
it("detects JVM family from extensions", () => {
|
||||
expect(detectBytecodeFamily("App.class")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
|
||||
});
|
||||
|
||||
it("detects Python family from extensions", () => {
|
||||
expect(detectBytecodeFamily("module.pyc")).toBe("python");
|
||||
expect(detectBytecodeFamily("module.pyo")).toBe("python");
|
||||
expect(detectBytecodeFamily("package.whl")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.pyz")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
|
||||
});
|
||||
|
||||
it("returns null for unknown extensions", () => {
|
||||
expect(detectBytecodeFamily("readme.txt")).toBeNull();
|
||||
expect(detectBytecodeFamily("script.js")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects artifact format from path", () => {
|
||||
expect(detectArtifactFormat("App.class")).toBe("class");
|
||||
expect(detectArtifactFormat("lib.jar")).toBe("jar");
|
||||
expect(detectArtifactFormat("web.war")).toBe("war");
|
||||
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
|
||||
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
|
||||
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
|
||||
});
|
||||
|
||||
it("classifies standard library provenance", () => {
|
||||
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
|
||||
"standard_library",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
|
||||
).toBe("standard_library");
|
||||
});
|
||||
|
||||
it("classifies generated provenance", () => {
|
||||
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
|
||||
"generated",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
|
||||
).toBe("generated");
|
||||
});
|
||||
|
||||
it("classifies vendored provenance", () => {
|
||||
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies application provenance", () => {
|
||||
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
|
||||
"application",
|
||||
);
|
||||
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
|
||||
});
|
||||
|
||||
it("analyzes bytecode artifacts and computes summary", () => {
|
||||
const artifacts: BytecodeArtifact[] = [
|
||||
{
|
||||
path: "src/App.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 1000,
|
||||
digest: "a".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "com.example.App",
|
||||
raw_location: "0x1000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "application",
|
||||
is_public: true,
|
||||
},
|
||||
{
|
||||
name: "java.lang.String",
|
||||
raw_location: "0x2000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "standard_library",
|
||||
is_public: true,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: false,
|
||||
is_vendored: false,
|
||||
},
|
||||
{
|
||||
path: "lib/generated/Generated.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 500,
|
||||
digest: "b".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "GeneratedClass",
|
||||
raw_location: "0x3000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "generated",
|
||||
is_public: false,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: true,
|
||||
is_vendored: false,
|
||||
},
|
||||
];
|
||||
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
|
||||
expect(result.family).toBe("jvm");
|
||||
expect(result.total_symbols).toBe(3);
|
||||
expect(result.application_symbols).toBe(1);
|
||||
expect(result.standard_library_symbols).toBe(1);
|
||||
expect(result.generated_symbols).toBe(1);
|
||||
expect(result.vendored_symbols).toBe(0);
|
||||
|
||||
// Validate schema
|
||||
const parsed = bytecodeAnalysisSchema.safeParse(result);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,6 @@ export const bytecodeSymbolSchema = z.strictObject({
|
||||
/** Whether the symbol is accessible (public). */
|
||||
is_public: z.boolean().default(false),
|
||||
});
|
||||
export type BytecodeSymbol = z.infer<typeof bytecodeSymbolSchema>;
|
||||
|
||||
/** A discovered bytecode artifact (class file, wheel, etc). */
|
||||
export const bytecodeArtifactSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
authEventsByProtocol,
|
||||
authFlowDuration,
|
||||
customProtocolCaptureSchema,
|
||||
correlateProcessIdentity,
|
||||
failedAuthEvents,
|
||||
framesByTransport,
|
||||
looksLikeCredentialFrame,
|
||||
successfulAuthEvents,
|
||||
type AuthFlowEvent,
|
||||
type ProtocolFrame,
|
||||
} from "./customProtocolCapture.js";
|
||||
|
||||
const sampleFrames: ProtocolFrame[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
transport: "tcp",
|
||||
direction: "sent",
|
||||
source_pid: 100,
|
||||
dest_pid: 200,
|
||||
source_endpoint: "127.0.0.1:8080",
|
||||
dest_endpoint: "127.0.0.1:9090",
|
||||
raw_data: "hello",
|
||||
decoded_content: "hello",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 200,
|
||||
transport: "udp",
|
||||
direction: "received",
|
||||
source_pid: 200,
|
||||
dest_pid: 100,
|
||||
source_endpoint: "127.0.0.1:9090",
|
||||
dest_endpoint: "127.0.0.1:8080",
|
||||
raw_data: "world",
|
||||
decoded_content: "world",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
];
|
||||
|
||||
const sampleAuthEvents: AuthFlowEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
stage: "init",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: false,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 500,
|
||||
stage: "success",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: true,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("custom protocol capture", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
transport: "tcp" as const,
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = customProtocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("correlates process identity", () => {
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters frames by transport", () => {
|
||||
const tcpFrames = framesByTransport(sampleFrames, "tcp");
|
||||
expect(tcpFrames).toHaveLength(1);
|
||||
const udpFrames = framesByTransport(sampleFrames, "udp");
|
||||
expect(udpFrames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("detects credential-like frames", () => {
|
||||
const credFrame: ProtocolFrame = {
|
||||
...sampleFrames[0]!,
|
||||
decoded_content: { password: "secret" },
|
||||
};
|
||||
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
|
||||
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters auth events by protocol", () => {
|
||||
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
|
||||
expect(oauthEvents).toHaveLength(2);
|
||||
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
|
||||
expect(otherEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("gets successful auth events", () => {
|
||||
const success = successfulAuthEvents(sampleAuthEvents);
|
||||
expect(success).toHaveLength(1);
|
||||
expect(success[0]!.succeeded).toBe(true);
|
||||
});
|
||||
|
||||
it("gets failed auth events", () => {
|
||||
const failed = failedAuthEvents(sampleAuthEvents);
|
||||
expect(failed).toHaveLength(1);
|
||||
expect(failed[0]!.succeeded).toBe(false);
|
||||
});
|
||||
|
||||
it("computes auth flow duration", () => {
|
||||
const duration = authFlowDuration(sampleAuthEvents);
|
||||
expect(duration).toBe(400);
|
||||
});
|
||||
|
||||
it("returns null for empty auth events", () => {
|
||||
expect(authFlowDuration([])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,6 @@ export type TransportType = z.infer<typeof transportTypeSchema>;
|
||||
|
||||
/** Direction of a protocol frame. */
|
||||
export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
|
||||
export type FrameDirection = z.infer<typeof frameDirectionSchema>;
|
||||
|
||||
/** A captured protocol frame. */
|
||||
export const protocolFrameSchema = z.strictObject({
|
||||
@@ -57,7 +56,6 @@ export const authStageSchema = z.enum([
|
||||
"failure",
|
||||
"success",
|
||||
]);
|
||||
export type AuthStage = z.infer<typeof authStageSchema>;
|
||||
|
||||
/** Token lifecycle event. */
|
||||
export const tokenLifecycleEventSchema = z.enum([
|
||||
@@ -67,7 +65,6 @@ export const tokenLifecycleEventSchema = z.enum([
|
||||
"revoked",
|
||||
"renewed",
|
||||
]);
|
||||
export type TokenLifecycleEvent = z.infer<typeof tokenLifecycleEventSchema>;
|
||||
|
||||
/** A captured authentication flow event. */
|
||||
export const authFlowEventSchema = z.strictObject({
|
||||
@@ -107,7 +104,6 @@ export const customProtocolCaptureSchema = z.strictObject({
|
||||
/** Whether credentials were detected. */
|
||||
credentials_detected: z.boolean().default(false),
|
||||
});
|
||||
export type CustomProtocolCapture = z.infer<typeof customProtocolCaptureSchema>;
|
||||
|
||||
/** Correlate a frame with process identity. */
|
||||
export function correlateProcessIdentity(
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { electronActiveObservationResultSchema } from "./electronActiveObservation.js";
|
||||
|
||||
/** Create a bounded active-capture result for MCP contract tests. */
|
||||
export const createElectronActiveObservationFixtureResult = (
|
||||
applicationPath: string,
|
||||
) =>
|
||||
electronActiveObservationResultSchema.parse({
|
||||
schema_version: 1,
|
||||
application: {
|
||||
executable_path: process.execPath,
|
||||
application_path: applicationPath,
|
||||
electron_version: "test-electron",
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "submit",
|
||||
kind: "click",
|
||||
window_index: 0,
|
||||
target: "window:1",
|
||||
status: "completed",
|
||||
elapsed_ms: 3,
|
||||
error: null,
|
||||
},
|
||||
],
|
||||
windows: [
|
||||
{
|
||||
window_id: "window:1",
|
||||
web_contents_id: "webContents:1",
|
||||
url: "file:///tmp/app.html",
|
||||
title: "Fixture",
|
||||
visible: true,
|
||||
destroyed: false,
|
||||
},
|
||||
],
|
||||
windows_truncated: false,
|
||||
processes: {
|
||||
items: [{ pid: 1234, type: "Browser", name: null, service_name: null }],
|
||||
truncated: false,
|
||||
},
|
||||
ipc: {
|
||||
events: [
|
||||
{
|
||||
sequence: 1,
|
||||
kind: "main-handler-invocation",
|
||||
channel: "readiness:echo",
|
||||
argument_shapes: ["string"],
|
||||
result_shape: "object",
|
||||
process_type: "main",
|
||||
error: false,
|
||||
},
|
||||
],
|
||||
observed: 1,
|
||||
retained: 1,
|
||||
truncated: false,
|
||||
},
|
||||
limitations: [
|
||||
"IPC payloads are represented only by bounded value shapes; values are never retained.",
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
containsProcess,
|
||||
getDescendants,
|
||||
maxTreeDepth,
|
||||
reconstructProcessTree,
|
||||
type ProcessTreeEvent,
|
||||
} from "./eventProcessTree.js";
|
||||
|
||||
describe("event-backed process tree reconstruction", () => {
|
||||
it("reconstructs a simple process tree", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 3,
|
||||
at_ms: 30,
|
||||
type: "exit",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.processes).toHaveLength(2);
|
||||
expect(result.events_consumed).toBe(4);
|
||||
expect(result.events_unmatched).toBe(0);
|
||||
expect(result.short_lived_descendants).toBe(2);
|
||||
});
|
||||
|
||||
it("detects short-lived descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: "/short",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 11,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.short_lived_descendants).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree transitions", () => {
|
||||
it("detects re-exec", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "re_exec",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/newroot",
|
||||
arguments: ["--new"],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_re_exec).toBe(true);
|
||||
const root = result.processes.find((p) => p.pid === 1)!;
|
||||
expect(root.is_re_exec).toBe(true);
|
||||
expect(root.executable).toBe("/newroot");
|
||||
});
|
||||
|
||||
it("detects reparenting", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "reparent",
|
||||
pid: 2,
|
||||
ppid: 0,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: 1,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_reparenting).toBe(true);
|
||||
const child = result.processes.find((p) => p.pid === 2)!;
|
||||
expect(child.is_reparented).toBe(true);
|
||||
expect(child.previous_ppid).toBe(1);
|
||||
expect(child.ppid).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unmatched events for unknown exits", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "exit",
|
||||
pid: 999,
|
||||
ppid: null,
|
||||
process_name: null,
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 1,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.events_unmatched).toBe(1);
|
||||
expect(result.processes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree queries", () => {
|
||||
it("gets descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child1",
|
||||
executable: "/c1",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "grandchild",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
const descendants = getDescendants(result.processes, 1);
|
||||
expect(descendants).toHaveLength(2);
|
||||
expect(descendants).toContain(2);
|
||||
expect(descendants).toContain(3);
|
||||
});
|
||||
|
||||
it("checks process containment", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(containsProcess(result.processes, 1)).toBe(true);
|
||||
expect(containsProcess(result.processes, 999)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree depth and types", () => {
|
||||
it("computes max tree depth", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/c",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "gc",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(maxTreeDepth(result.processes, 1)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,6 @@ export const processEventTypeSchema = z.enum([
|
||||
"thread_create",
|
||||
"thread_exit",
|
||||
]);
|
||||
export type ProcessEventType = z.infer<typeof processEventTypeSchema>;
|
||||
|
||||
/** A single event-backed process-tree event. */
|
||||
export const processTreeEventSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
export const ghidraFunctionClassification = () => ({
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager" as const,
|
||||
});
|
||||
|
||||
export const ghidraFunctionIdentity = () => ({
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: ghidraFunctionClassification(),
|
||||
});
|
||||
|
||||
const ghidraReferenceKind = () => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-reference-manager" as const,
|
||||
type: "DATA",
|
||||
flow: false,
|
||||
call: false,
|
||||
jump: false,
|
||||
data: true,
|
||||
read: true,
|
||||
write: false,
|
||||
indirect: false,
|
||||
computed: false,
|
||||
conditional: false,
|
||||
terminal: false,
|
||||
primary: true,
|
||||
operand_index: 0,
|
||||
external: false,
|
||||
});
|
||||
|
||||
export const ghidraReferenceEdge = () => ({
|
||||
source_address: "0x401001",
|
||||
target_address: "0x402000",
|
||||
source_procedure: ghidraFunctionIdentity(),
|
||||
target_procedure: null,
|
||||
kind: ghidraReferenceKind(),
|
||||
});
|
||||
|
||||
export const ghidraBounded = (items: readonly JsonValue[]) => ({
|
||||
items: [...items],
|
||||
total: items.length,
|
||||
returned: items.length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
export const ghidraNativeApiBoundary = (mappingsTruncated = false) => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-high-function",
|
||||
signature_source: "analysis",
|
||||
calling_convention: "__cdecl",
|
||||
return_type: {
|
||||
role: "return" as const,
|
||||
ordinal: null,
|
||||
name: null,
|
||||
data_type: "int",
|
||||
size_bytes: 4,
|
||||
storage: "EAX:4",
|
||||
confidence: "medium" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "signature-source" as const,
|
||||
source: "ghidra-function-manager",
|
||||
detail: "Function signature source is analysis.",
|
||||
},
|
||||
{
|
||||
kind: "decompiler-type" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "HighFunction recovered data type int.",
|
||||
},
|
||||
],
|
||||
decompiler_artifacts: [
|
||||
"recovered-signature" as const,
|
||||
"register-or-stack-storage" as const,
|
||||
],
|
||||
},
|
||||
parameters: [],
|
||||
parameters_truncated: false,
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [
|
||||
{
|
||||
address: "0x403000",
|
||||
provenance: "ghidra-decompiler-load-table" as const,
|
||||
entry_size_bytes: 4,
|
||||
entry_count: 2,
|
||||
confidence: "high" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "jump-table" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "Decompiler load table starts at 0x403000.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
data_sources_truncated: false,
|
||||
mappings: [
|
||||
{
|
||||
case_value: 0,
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
confidence: "medium" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "jump-table" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "Recovered target 0x401020 from dispatch 0x401010.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
mappings_truncated: mappingsTruncated,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
jump_tables_truncated: false,
|
||||
pseudocode: {
|
||||
classification: "decompiler-generated-non-source" as const,
|
||||
compilable: false as const,
|
||||
},
|
||||
decompiler_artifacts: [
|
||||
"recovered-signature" as const,
|
||||
"register-and-stack-variables" as const,
|
||||
"compiler-generated-control-flow" as const,
|
||||
"pointer-arithmetic" as const,
|
||||
"pseudocode" as const,
|
||||
],
|
||||
limitations: [
|
||||
"Pseudocode is neither original source nor guaranteed to compile.",
|
||||
],
|
||||
});
|
||||
|
||||
export const ghidraFunctionDossier = (
|
||||
includeAssembly = true,
|
||||
mappingsTruncated = false,
|
||||
): JsonValue => {
|
||||
const pseudocode = "int fixture_main(void) { return 42; }";
|
||||
return {
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: pseudocode,
|
||||
total_chars: [...pseudocode].length,
|
||||
returned_chars: [...pseudocode].length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: ghidraBounded(
|
||||
includeAssembly ? ["0x401000: CALL 0x401020", "0x401005: RET"] : [],
|
||||
),
|
||||
comments: ghidraBounded([]),
|
||||
callers: ghidraBounded([]),
|
||||
callees: ghidraBounded([]),
|
||||
incoming_references: ghidraBounded([]),
|
||||
outgoing_references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
referenced_strings: ghidraBounded([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "inventory fixture",
|
||||
source_address: "0x401001",
|
||||
},
|
||||
]),
|
||||
referenced_names: ghidraBounded([]),
|
||||
basic_blocks: ghidraBounded([
|
||||
{ start: "0x401000", end: "0x401006", successors: [] },
|
||||
]),
|
||||
instruction_scan: { scanned: 2, truncated: false },
|
||||
native_api: ghidraNativeApiBoundary(mappingsTruncated),
|
||||
limitations: [
|
||||
"Unresolved computed or indirect flows without target addresses are not represented as reference edges.",
|
||||
"Thunk and external classifications are Ghidra FunctionManager observations; they do not resolve targetless calls.",
|
||||
"Pseudocode and assembly are Ghidra-specific representations, not original source or Hopper-equivalent text.",
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseDocuments,
|
||||
parseAddressedPage,
|
||||
parseListCount,
|
||||
parseNames,
|
||||
parseProcedures,
|
||||
parseRelatedAddresses,
|
||||
parseSegments,
|
||||
} from "./hopperValues.js";
|
||||
|
||||
describe("Hopper boundary values", () => {
|
||||
it("parses Hopper's address-keyed name and string maps", () => {
|
||||
expect(parseNames({ "0x1000": "_main" })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1000", name: "_main" }],
|
||||
});
|
||||
expect(
|
||||
parseListCount({ "0x1000": "hello", "0x2000": "world" }, "strings"),
|
||||
).toEqual({ ok: true, value: 2 });
|
||||
});
|
||||
|
||||
it("parses direct and wrapped protocol shapes", () => {
|
||||
expect(parseProcedures({ procedures: { "0x1": "main" } })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1", name: "main" }],
|
||||
});
|
||||
expect(parseNames({ names: [{ address: "0x2", name: "label" }] }).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseRelatedAddresses({ callers: ["0x3"] }, "callers")).toEqual({
|
||||
ok: true,
|
||||
value: ["0x3"],
|
||||
});
|
||||
expect(
|
||||
parseSegments([
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
]),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: [
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(parseDocuments(["fixture"])).toEqual({
|
||||
ok: true,
|
||||
value: ["fixture"],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: true,
|
||||
},
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: 100,
|
||||
has_more: false,
|
||||
},
|
||||
])("rejects contradictory page continuation metadata", (page) => {
|
||||
const result = parseAddressedPage(page);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["procedures", () => parseProcedures(["not-a-map"])],
|
||||
["names", () => parseNames([{ address: 1, name: "bad" }])],
|
||||
["relations", () => parseRelatedAddresses([1], "callees")],
|
||||
["segments", () => parseSegments([{ name: 1 }])],
|
||||
["documents", () => parseDocuments([1])],
|
||||
])(
|
||||
"rejects malformed %s instead of manufacturing empty output",
|
||||
(_label, parse) => {
|
||||
const result = parse();
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareManagedMembers,
|
||||
managedMemberComparisonResultSchema,
|
||||
} from "./managedMemberComparison.js";
|
||||
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "../dotnet/ManagedPe.fixture.js";
|
||||
|
||||
const comparisonLimits = {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
};
|
||||
|
||||
describe("managed member comparison", () => {
|
||||
it("remaps renamed methods by exact CIL/signature without using names", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
mvid: Buffer.from("00112233445566778899aabbccddeefe", "hex"),
|
||||
typeName: "A",
|
||||
typeNamespace: "X",
|
||||
methodName: "b",
|
||||
fieldName: "c",
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.algorithm.name_matching).toBe("not-used");
|
||||
expect(result.left.mvid).toBe("00112233-4455-6677-8899-aabbccddeeff");
|
||||
expect(result.right.mvid).toBe("33221100-5544-7766-8899-aabbccddeefe");
|
||||
expect(result.matching.exact_il_signature).toBe(1);
|
||||
expect(result.methods).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unchanged",
|
||||
left: expect.objectContaining({ token: "0x06000001", name: "Main" }),
|
||||
right: expect.objectContaining({ token: "0x06000001", name: "b" }),
|
||||
match: expect.objectContaining({
|
||||
status: "matched",
|
||||
basis: "exact-il-signature",
|
||||
confidence: "exact",
|
||||
}),
|
||||
dimensions: [],
|
||||
}),
|
||||
]);
|
||||
expect(result.limitations).toContain(
|
||||
"Names are reported as observations but are not used as a matching basis.",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses structural method shape when build-local token operands drift", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, 0x0a,
|
||||
0x2a,
|
||||
]),
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(1);
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "changed",
|
||||
match: { status: "matched", basis: "structural-method-shape" },
|
||||
dimensions: ["cil"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects member states that disagree with their observed sides or match", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
const method = result.methods[0];
|
||||
expect(method).toBeDefined();
|
||||
if (method === undefined) return;
|
||||
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [{ ...method, status: "unchanged", right: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [
|
||||
{
|
||||
...method,
|
||||
match: {
|
||||
...method.match,
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
},
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not match identical instruction-limited method prefixes", () => {
|
||||
const limited = {
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
maxMethodInstructions: 1,
|
||||
};
|
||||
const left = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/left-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const right = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/right-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(0);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed member comparison uncertainty", () => {
|
||||
it("keeps unmatched members unknown when the opposite page is incomplete", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left-paged.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right-paged.dll");
|
||||
const leftPartial = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const rightPartial = {
|
||||
...right.result,
|
||||
methods: {
|
||||
...right.result.methods,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: leftPartial },
|
||||
{ evidenceId: right.evidenceId, result: rightPartial },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.summary).toMatchObject({
|
||||
added: 0,
|
||||
removed: 0,
|
||||
unknown: 2,
|
||||
});
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: { token: "0x06000001" },
|
||||
right: null,
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.fields[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: { token: "0x04000001" },
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
status: "truncated",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 1,
|
||||
omitted_candidates: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not guess ambiguous field signature matches", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const leftField = left.result.fields.items[0];
|
||||
expect(leftField).toBeDefined();
|
||||
if (leftField === undefined) return;
|
||||
const duplicatedLeft = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [
|
||||
leftField,
|
||||
{
|
||||
...leftField,
|
||||
token: "0x04000002",
|
||||
name: "other",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const rightField = right.result.fields.items[0];
|
||||
expect(rightField).toBeDefined();
|
||||
if (rightField === undefined) return;
|
||||
const duplicatedRight = {
|
||||
...right.result,
|
||||
fields: {
|
||||
...right.result.fields,
|
||||
items: [
|
||||
rightField,
|
||||
{
|
||||
...rightField,
|
||||
token: "0x04000002",
|
||||
name: "renamed",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: duplicatedLeft },
|
||||
{ evidenceId: right.evidenceId, result: duplicatedRight },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.ambiguous).toBe(1);
|
||||
expect(result.fields).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
match: expect.objectContaining({
|
||||
status: "ambiguous",
|
||||
basis: "field-signature",
|
||||
candidate_left_tokens: ["0x04000001", "0x04000002"],
|
||||
candidate_right_tokens: ["0x04000001", "0x04000002"],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const inspect = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
limits: typeof MANAGED_MEMBER_FIXTURE_LIMITS = MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
) => {
|
||||
const target = managedPeFixtureTarget(bytes, path);
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
return {
|
||||
result,
|
||||
evidenceId: `ev_${hash(Buffer.from(path))}`,
|
||||
};
|
||||
};
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyMobileResource,
|
||||
detectMobileFormat,
|
||||
detectPlatform,
|
||||
getAllArchitectures,
|
||||
hasInternetPermission,
|
||||
mobileArtifactManifestSchema,
|
||||
nativeLibsByArchitecture,
|
||||
type MobileArtifactManifest,
|
||||
type AndroidManifest,
|
||||
type SigningInfo,
|
||||
type NativeLibrary,
|
||||
type MobileResource,
|
||||
} from "./mobileApplicationInvestigation.js";
|
||||
|
||||
describe("mobile application investigation", () => {
|
||||
it("detects mobile format from extension", () => {
|
||||
expect(detectMobileFormat("app.apk")).toBe("apk");
|
||||
expect(detectMobileFormat("app.aab")).toBe("aab");
|
||||
expect(detectMobileFormat("app.ipa")).toBe("ipa");
|
||||
expect(detectMobileFormat("classes.dex")).toBe("dex");
|
||||
expect(detectMobileFormat("lib.so")).toBe("native_lib");
|
||||
expect(detectMobileFormat("readme.txt")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects platform from format", () => {
|
||||
expect(detectPlatform("apk")).toBe("android");
|
||||
expect(detectPlatform("aab")).toBe("android");
|
||||
expect(detectPlatform("dex")).toBe("android");
|
||||
expect(detectPlatform("ipa")).toBe("ios");
|
||||
expect(detectPlatform("native_lib")).toBe("cross_platform");
|
||||
});
|
||||
|
||||
it("classifies resources by path", () => {
|
||||
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
|
||||
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
|
||||
expect(classifyMobileResource("assets/data.json")).toBe("asset");
|
||||
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
|
||||
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
|
||||
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
|
||||
"native_lib",
|
||||
);
|
||||
expect(classifyMobileResource("unknown.xyz")).toBe("other");
|
||||
});
|
||||
|
||||
const androidManifest: AndroidManifest = {
|
||||
package_name: "com.example.app",
|
||||
version_name: "1.0.0",
|
||||
version_code: 1,
|
||||
min_sdk: 21,
|
||||
target_sdk: 34,
|
||||
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
|
||||
activities: ["MainActivity"],
|
||||
services: ["BackgroundService"],
|
||||
receivers: [],
|
||||
providers: [],
|
||||
};
|
||||
|
||||
const signing: SigningInfo = {
|
||||
is_signed: true,
|
||||
signer_identity: "CN=TestSigner",
|
||||
certificate_fingerprint: "abc123",
|
||||
signature_scheme: "v2",
|
||||
is_debuggable: false,
|
||||
};
|
||||
|
||||
const nativeLibs: NativeLibrary[] = [
|
||||
{
|
||||
path: "lib/arm64-v8a/libnative.so",
|
||||
architecture: "arm64-v8a",
|
||||
size: 100000,
|
||||
digest: "a".repeat(64),
|
||||
},
|
||||
{
|
||||
path: "lib/armeabi-v7a/libnative.so",
|
||||
architecture: "armeabi-v7a",
|
||||
size: 90000,
|
||||
digest: "b".repeat(64),
|
||||
},
|
||||
];
|
||||
|
||||
const resources: MobileResource[] = [
|
||||
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
|
||||
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
|
||||
];
|
||||
|
||||
const validManifest: MobileArtifactManifest = {
|
||||
format: "apk",
|
||||
platform: "android",
|
||||
app_name: "TestApp",
|
||||
android_manifest: androidManifest,
|
||||
ios_manifest: null,
|
||||
signing,
|
||||
resources,
|
||||
native_libraries: nativeLibs,
|
||||
total_size: 5000000,
|
||||
architectures: ["arm64-v8a", "armeabi-v7a"],
|
||||
};
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = mobileArtifactManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("filters native libs by architecture", () => {
|
||||
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
|
||||
expect(arm64).toHaveLength(1);
|
||||
expect(arm64[0]!.architecture).toBe("arm64-v8a");
|
||||
});
|
||||
|
||||
it("checks internet permission", () => {
|
||||
expect(hasInternetPermission(validManifest)).toBe(true);
|
||||
const noInternet: MobileArtifactManifest = {
|
||||
...validManifest,
|
||||
android_manifest: { ...androidManifest, permissions: [] },
|
||||
};
|
||||
expect(hasInternetPermission(noInternet)).toBe(false);
|
||||
});
|
||||
|
||||
it("gets all architectures", () => {
|
||||
const archs = getAllArchitectures(validManifest);
|
||||
expect(archs).toHaveLength(2);
|
||||
expect(archs).toContain("arm64-v8a");
|
||||
expect(archs).toContain("armeabi-v7a");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countMethodsByType,
|
||||
isDbSaveComplete,
|
||||
isGetterSelector,
|
||||
isSetterSelector,
|
||||
objcSwiftMetadataSchema,
|
||||
propertyNameFromSelector,
|
||||
swiftDeclsByKind,
|
||||
type ObjcClass,
|
||||
type ObjcMethod,
|
||||
type ObjcProtocol,
|
||||
type SwiftDecl,
|
||||
type DbSaveResult,
|
||||
} from "./objcSwiftMetadata.js";
|
||||
|
||||
describe("ObjC/Swift metadata", () => {
|
||||
it("identifies getter selectors", () => {
|
||||
expect(isGetterSelector("name")).toBe(true);
|
||||
expect(isGetterSelector("setName:")).toBe(false);
|
||||
expect(isGetterSelector("set")).toBe(true);
|
||||
});
|
||||
|
||||
it("identifies setter selectors", () => {
|
||||
expect(isSetterSelector("setName:")).toBe(true);
|
||||
expect(isSetterSelector("name")).toBe(false);
|
||||
});
|
||||
|
||||
it("extracts property name from selector", () => {
|
||||
expect(propertyNameFromSelector("name")).toBe("name");
|
||||
expect(propertyNameFromSelector("setName:")).toBe("name");
|
||||
expect(propertyNameFromSelector("set")).toBe("set");
|
||||
});
|
||||
|
||||
it("counts methods by type", () => {
|
||||
const methods: ObjcMethod[] = [
|
||||
{
|
||||
selector: "init",
|
||||
method_type: "instance",
|
||||
address: 0x1000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
{
|
||||
selector: "alloc",
|
||||
method_type: "class",
|
||||
address: 0x2000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
];
|
||||
const counts = countMethodsByType(methods);
|
||||
expect(counts.instance).toBe(1);
|
||||
expect(counts.class).toBe(1);
|
||||
expect(counts.ivar_getter).toBe(0);
|
||||
expect(counts.ivar_setter).toBe(0);
|
||||
});
|
||||
|
||||
it("filters Swift declarations by kind", () => {
|
||||
const decls: SwiftDecl[] = [
|
||||
{
|
||||
kind: "class",
|
||||
name: "Foo",
|
||||
module: null,
|
||||
access_level: "public",
|
||||
super_class: null,
|
||||
protocols: [],
|
||||
is_final: false,
|
||||
is_required: false,
|
||||
is_convenience_init: false,
|
||||
is_override: false,
|
||||
},
|
||||
];
|
||||
const classes = swiftDeclsByKind(decls, "class");
|
||||
expect(classes).toHaveLength(1);
|
||||
expect(classes[0]!.name).toBe("Foo");
|
||||
});
|
||||
|
||||
it("checks database save completeness", () => {
|
||||
const result: DbSaveResult = {
|
||||
operation: "save",
|
||||
succeeded: true,
|
||||
preserved_names: 10,
|
||||
preserved_comments: 5,
|
||||
preserved_bookmarks: 3,
|
||||
database_path: "/tmp/db.hop",
|
||||
error: null,
|
||||
};
|
||||
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
|
||||
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
|
||||
});
|
||||
|
||||
it("validates a well-formed metadata result", () => {
|
||||
const meta = {
|
||||
objc_classes: [] as ObjcClass[],
|
||||
objc_protocols: [] as ObjcProtocol[],
|
||||
swift_decls: [] as SwiftDecl[],
|
||||
db_save_result: null,
|
||||
};
|
||||
const result = objcSwiftMetadataSchema.safeParse(meta);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyResource,
|
||||
detectPackageFormat,
|
||||
hasValidSignature,
|
||||
isConfigurationResource,
|
||||
isManifestResource,
|
||||
packageManifestSchema,
|
||||
resourcesByType,
|
||||
totalResourceSize,
|
||||
type PackageManifest,
|
||||
} from "./packageAnalysis.js";
|
||||
|
||||
describe("package analysis", () => {
|
||||
it("detects package format from extension", () => {
|
||||
expect(detectPackageFormat("app.msix")).toBe("msix");
|
||||
expect(detectPackageFormat("installer.msi")).toBe("msi");
|
||||
expect(detectPackageFormat("app.appx")).toBe("appx");
|
||||
expect(detectPackageFormat("app.zip")).toBeNull();
|
||||
});
|
||||
|
||||
it("identifies manifest resources", () => {
|
||||
expect(isManifestResource("AppXManifest.xml")).toBe(true);
|
||||
expect(isManifestResource("resources.pri")).toBe(false);
|
||||
});
|
||||
|
||||
it("identifies configuration resources", () => {
|
||||
expect(isConfigurationResource("settings.xml")).toBe(true);
|
||||
expect(isConfigurationResource("config.json")).toBe(true);
|
||||
expect(isConfigurationResource("app.exe")).toBe(false);
|
||||
});
|
||||
|
||||
it("classifies resources by path", () => {
|
||||
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
|
||||
expect(classifyResource("icon.png")).toBe("icon");
|
||||
expect(classifyResource("settings.xml")).toBe("configuration");
|
||||
expect(classifyResource("cert.cer")).toBe("certificate");
|
||||
expect(classifyResource("app.exe")).toBe("executable");
|
||||
expect(classifyResource("lib.dll")).toBe("library");
|
||||
expect(classifyResource("data.bin")).toBe("other");
|
||||
});
|
||||
|
||||
const validManifest: PackageManifest = {
|
||||
format: "msix",
|
||||
name: "TestApp",
|
||||
publisher: "CN=TestPublisher",
|
||||
version: "1.0.0.0",
|
||||
architecture: "x64",
|
||||
resources: [
|
||||
{
|
||||
path: "AppXManifest.xml",
|
||||
type: "manifest",
|
||||
size: 1000,
|
||||
digest: "a".repeat(64),
|
||||
},
|
||||
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
|
||||
{
|
||||
path: "app.exe",
|
||||
type: "executable",
|
||||
size: 50000,
|
||||
digest: "c".repeat(64),
|
||||
},
|
||||
],
|
||||
signature: {
|
||||
is_signed: true,
|
||||
signer_subject: "CN=TestPublisher",
|
||||
certificate_thumbprint: "abc123",
|
||||
is_valid: true,
|
||||
is_timestamped: true,
|
||||
timestamp_signer: "CN=Timestamp",
|
||||
},
|
||||
is_framework: false,
|
||||
dependencies: ["Microsoft.VCLibs.14.00"],
|
||||
capabilities: ["internetClient", "localNetwork"],
|
||||
};
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = packageManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("filters resources by type", () => {
|
||||
const icons = resourcesByType(validManifest, "icon");
|
||||
expect(icons).toHaveLength(1);
|
||||
expect(icons[0]!.path).toBe("icon.png");
|
||||
});
|
||||
|
||||
it("computes total resource size", () => {
|
||||
expect(totalResourceSize(validManifest)).toBe(56000);
|
||||
});
|
||||
|
||||
it("checks valid signature", () => {
|
||||
expect(hasValidSignature(validManifest)).toBe(true);
|
||||
const unsigned: PackageManifest = {
|
||||
...validManifest,
|
||||
signature: { ...validManifest.signature, is_valid: false },
|
||||
};
|
||||
expect(hasValidSignature(unsigned)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -44,7 +44,6 @@ export const digitalSignatureSchema = z.strictObject({
|
||||
/** Timestamp signer if present. */
|
||||
timestamp_signer: z.string().nullable(),
|
||||
});
|
||||
export type DigitalSignature = z.infer<typeof digitalSignatureSchema>;
|
||||
|
||||
/** A Windows package manifest for static analysis. */
|
||||
export const packageManifestSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countExecutableSections,
|
||||
getExportedFunctions,
|
||||
getImportedDlls,
|
||||
hasPdbInfo,
|
||||
parseDebugType,
|
||||
parseImageCharacteristics,
|
||||
parseMachineType,
|
||||
parseSectionCharacteristics,
|
||||
peManifestSchema,
|
||||
type PeManifest,
|
||||
} from "./peInspection.js";
|
||||
|
||||
const validManifest: PeManifest = {
|
||||
dos_magic: 0x5a4d,
|
||||
pe_signature: 0x00004550,
|
||||
machine: "x64",
|
||||
number_of_sections: 3,
|
||||
timestamp: 0x12345678,
|
||||
is_dll: false,
|
||||
is_executable: true,
|
||||
is_console: true,
|
||||
entry_point: 0x1000,
|
||||
image_base: 0x400000,
|
||||
section_alignment: 0x1000,
|
||||
subsystem_version: "10.0",
|
||||
sections: [
|
||||
{
|
||||
name: ".text",
|
||||
virtual_size: 0x1000,
|
||||
virtual_address: 0x1000,
|
||||
raw_size: 0x1000,
|
||||
raw_offset: 0x400,
|
||||
characteristics: {
|
||||
has_code: true,
|
||||
has_initialized_data: false,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".data",
|
||||
virtual_size: 0x500,
|
||||
virtual_address: 0x2000,
|
||||
raw_size: 0x500,
|
||||
raw_offset: 0x1400,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".rdata",
|
||||
virtual_size: 0x200,
|
||||
virtual_address: 0x3000,
|
||||
raw_size: 0x200,
|
||||
raw_offset: 0x1900,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
imports: [
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "CreateFileW",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "WriteFile",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "USER32.DLL",
|
||||
function_name: "MessageBoxW",
|
||||
ordinal: 100,
|
||||
is_delay_import: false,
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
|
||||
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
|
||||
],
|
||||
resources: [
|
||||
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
|
||||
],
|
||||
debug_entries: [
|
||||
{
|
||||
type: "CODEVIEW",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
|
||||
pdb_age: 1,
|
||||
pdb_path: "C:\\src\\app.pdb",
|
||||
},
|
||||
],
|
||||
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
|
||||
relocations_count: 50,
|
||||
image_characteristics: ["Executable", "Console"],
|
||||
};
|
||||
|
||||
describe("PE/COFF static inspection", () => {
|
||||
it("parses machine types", () => {
|
||||
expect(parseMachineType(0x014c)).toBe("x86");
|
||||
expect(parseMachineType(0x8664)).toBe("x64");
|
||||
expect(parseMachineType(0x01c0)).toBe("arm");
|
||||
expect(parseMachineType(0xaa64)).toBe("arm64");
|
||||
expect(parseMachineType(0x0200)).toBe("ia64");
|
||||
expect(parseMachineType(0xffff)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("parses section characteristics", () => {
|
||||
const CODE = 0x00000020;
|
||||
const READ = 0x40000000;
|
||||
const EXECUTE = 0x20000000;
|
||||
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
|
||||
expect(result.has_code).toBe(true);
|
||||
expect(result.readable).toBe(true);
|
||||
expect(result.executable).toBe(true);
|
||||
expect(result.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("parses image characteristics", () => {
|
||||
const DLL = 0x2000;
|
||||
const EXEC = 0x0002;
|
||||
const flags = parseImageCharacteristics(DLL | EXEC);
|
||||
expect(flags).toContain("DLL");
|
||||
expect(flags).toContain("Executable");
|
||||
});
|
||||
|
||||
it("parses debug types", () => {
|
||||
expect(parseDebugType(2)).toBe("CODEVIEW");
|
||||
expect(parseDebugType(1)).toBe("COFF");
|
||||
expect(parseDebugType(99)).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = peManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects PDB info", () => {
|
||||
expect(hasPdbInfo(validManifest)).toBe(true);
|
||||
const withoutPdb: PeManifest = {
|
||||
...validManifest,
|
||||
debug_entries: [
|
||||
{
|
||||
type: "COFF",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: null,
|
||||
pdb_age: null,
|
||||
pdb_path: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(hasPdbInfo(withoutPdb)).toBe(false);
|
||||
});
|
||||
|
||||
it("gets imported DLLs", () => {
|
||||
const dlls = getImportedDlls(validManifest);
|
||||
expect(dlls).toHaveLength(2);
|
||||
expect(dlls).toContain("KERNEL32.DLL");
|
||||
expect(dlls).toContain("USER32.DLL");
|
||||
});
|
||||
|
||||
it("gets exported functions", () => {
|
||||
const exports = getExportedFunctions(validManifest);
|
||||
expect(exports).toHaveLength(2);
|
||||
expect(exports).toContain("DllMain");
|
||||
expect(exports).toContain("MyFunction");
|
||||
});
|
||||
|
||||
it("counts executable sections", () => {
|
||||
expect(countExecutableSections(validManifest)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,6 @@ export const peSectionSchema = z.strictObject({
|
||||
raw_offset: z.number().int().nonnegative(),
|
||||
characteristics: sectionCharacteristicsSchema,
|
||||
});
|
||||
export type PeSection = z.infer<typeof peSectionSchema>;
|
||||
|
||||
/** PE import entry. */
|
||||
export const peImportSchema = z.strictObject({
|
||||
@@ -34,7 +33,6 @@ export const peImportSchema = z.strictObject({
|
||||
ordinal: z.number().int().nullable(),
|
||||
is_delay_import: z.boolean().default(false),
|
||||
});
|
||||
export type PeImport = z.infer<typeof peImportSchema>;
|
||||
|
||||
/** PE export entry. */
|
||||
export const peExportSchema = z.strictObject({
|
||||
@@ -43,7 +41,6 @@ export const peExportSchema = z.strictObject({
|
||||
rva: z.number().int().nonnegative(),
|
||||
forwarder: z.string().nullable(),
|
||||
});
|
||||
export type PeExport = z.infer<typeof peExportSchema>;
|
||||
|
||||
/** PE/COFF resource entry. */
|
||||
export const peResourceSchema = z.strictObject({
|
||||
@@ -53,7 +50,6 @@ export const peResourceSchema = z.strictObject({
|
||||
rva: z.number().int().nonnegative(),
|
||||
size: z.number().int().nonnegative(),
|
||||
});
|
||||
export type PeResource = z.infer<typeof peResourceSchema>;
|
||||
|
||||
/** PE debug directory entry. */
|
||||
export const peDebugEntrySchema = z.strictObject({
|
||||
@@ -67,14 +63,12 @@ export const peDebugEntrySchema = z.strictObject({
|
||||
/** PDB path if this is a CodeView entry. */
|
||||
pdb_path: z.string().nullable(),
|
||||
});
|
||||
export type PeDebugEntry = z.infer<typeof peDebugEntrySchema>;
|
||||
|
||||
/** TLS callback entry. */
|
||||
export const peTlsCallbackSchema = z.strictObject({
|
||||
callback_rva: z.number().int().nonnegative(),
|
||||
index: z.number().int().nonnegative(),
|
||||
});
|
||||
export type PeTlsCallback = z.infer<typeof peTlsCallbackSchema>;
|
||||
|
||||
/** Architecture/machine type. */
|
||||
export const peMachineTypeSchema = z.enum([
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("classifies missing observations as unknown and one-sided evidence as added", () => {
|
||||
const base = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const added = compareProcessCaptures(base, {
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
columns: 3,
|
||||
rows: 1,
|
||||
cursor_x: 3,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["new"],
|
||||
serialized_state: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(added.terminal).toBe("added");
|
||||
expect(added.status).toBe("changed");
|
||||
const unknown = compareProcessCaptures(
|
||||
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
|
||||
base,
|
||||
);
|
||||
expect(unknown.process).toBe("unknown");
|
||||
expect(unknown.shim).toBe("unchanged");
|
||||
expect(unknown.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("treats equivalent normalization records as equal regardless of member order", () => {
|
||||
const capture = emptyCapture();
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
normalization: {
|
||||
patterns: [],
|
||||
time_bucket_ms: 10,
|
||||
ports: true,
|
||||
pids: true,
|
||||
paths: true,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
first_divergence: { status: "none" },
|
||||
});
|
||||
});
|
||||
|
||||
it("compares raw terminal chunks even when rendered states agree", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
|
||||
});
|
||||
expect(comparison.terminal).toBe("changed");
|
||||
expect(comparison.first_divergence).toMatchObject({
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps filesystem evidence unknown when stable snapshots match", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [
|
||||
{ scope: "filesystem" as const, reason: "watcher unavailable" },
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, capture);
|
||||
expect(comparison.filesystem).toBe("unknown");
|
||||
expect(comparison.status).toBe("unknown");
|
||||
|
||||
const complete = { ...capture, residual_unknowns: [] };
|
||||
const transient = compareProcessCaptures(complete, {
|
||||
...complete,
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "during_run",
|
||||
at_ms: 10,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(transient.filesystem).toBe("changed");
|
||||
expect(transient.status).toBe("changed");
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
|
||||
|
||||
export { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
|
||||
|
||||
/** Parse a detached valid empty capture for tests that need trusted evidence. */
|
||||
export const emptyProcessCapture = () =>
|
||||
parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
/** Parse a mutable unverified capture for boundary-validation tests. */
|
||||
export const emptyUnverifiedProcessCapture = (): UnverifiedProcessCapture =>
|
||||
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
/** Project validation failures without coupling tests to Zod internals. */
|
||||
export const processCaptureIssues = (
|
||||
capture: UnverifiedProcessCapture,
|
||||
): readonly { readonly path: string; readonly message: string }[] => {
|
||||
const parsed = processCaptureSchema.safeParse(capture);
|
||||
return parsed.success
|
||||
? []
|
||||
: parsed.error.issues.map((issue) => ({
|
||||
path: issue.path.join("."),
|
||||
message: issue.message,
|
||||
}));
|
||||
};
|
||||
|
||||
/** Compare unverified fixture values through the production parser. */
|
||||
export const compareUnverifiedProcessCaptures = (
|
||||
left: UnverifiedProcessCapture,
|
||||
right: UnverifiedProcessCapture,
|
||||
options?: Parameters<typeof compareProcessCaptures>[2],
|
||||
): ReturnType<typeof compareProcessCaptures> =>
|
||||
compareProcessCaptures(
|
||||
parseProcessCapture(left),
|
||||
parseProcessCapture(right),
|
||||
options,
|
||||
);
|
||||
@@ -0,0 +1,125 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { digestProcessCommitment } from "./processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("detects changes in normalized process sample metadata", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const changed = {
|
||||
...capture,
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 20,
|
||||
pid: 1,
|
||||
parent_pid: 2,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, changed);
|
||||
expect(comparison.process).toBe("changed");
|
||||
expect(comparison.status).toBe("changed");
|
||||
});
|
||||
|
||||
it("compares replay state transitions as protocol evidence", () => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "anonymous",
|
||||
states: [
|
||||
{ name: "anonymous" },
|
||||
{ name: "authenticated", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "login",
|
||||
from: "anonymous",
|
||||
to: "authenticated",
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
};
|
||||
const empty = emptyCapture();
|
||||
const baseline = {
|
||||
...empty,
|
||||
manifest: {
|
||||
...empty.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
};
|
||||
const transitioned = {
|
||||
...baseline,
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
transition_id: "login",
|
||||
state_before: "anonymous",
|
||||
state_after: "authenticated",
|
||||
sensitive_aliases: ["token"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
|
||||
status: "changed",
|
||||
protocol: "added",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyUnverifiedProcessCapture as emptyCapture,
|
||||
processCaptureIssues,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("never considers truncated captures equivalent", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: true,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
|
||||
});
|
||||
|
||||
it("rejects altered v4 commitments and accepts canonical key reordering", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(parseProcessCapture(capture)).toEqual(capture);
|
||||
expect(digestProcessCommitment({ second: 2, first: 1 })).toBe(
|
||||
digestProcessCommitment({ first: 1, second: 2 }),
|
||||
);
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
normalization_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("normalization_sha256");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
executable_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("executable_sha256");
|
||||
});
|
||||
|
||||
it("rejects settlement and cleanup combinations that cannot occur", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 0,
|
||||
cleanup_outcome: "cleaned",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "alive_at_deadline",
|
||||
elapsed_ms: 1,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
});
|
||||
|
||||
it("accepts old captures without a journal and validates complete journals", () => {
|
||||
const capture = emptyCapture();
|
||||
const { event_journal: _eventJournal, ...oldCapture } = capture;
|
||||
expect(parseProcessCapture(oldCapture).event_journal).toEqual([]);
|
||||
|
||||
const eventJournal = [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
] as const;
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: eventJournal }),
|
||||
).toEqual([]);
|
||||
|
||||
for (const [candidate, message] of [
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 1 ? { ...entry, capture_order: 2 } : entry,
|
||||
),
|
||||
"contiguous",
|
||||
],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3
|
||||
? { ...entry, collection: "lifecycle" as const, index: 1 }
|
||||
: entry,
|
||||
),
|
||||
"unique",
|
||||
],
|
||||
[eventJournal.slice(0, 3), "every captured observation"],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3 ? { ...entry, index: 2 } : entry,
|
||||
),
|
||||
"outside",
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: candidate }),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["machine limit", 1, 5, 10],
|
||||
["transition use limit", 5, 1, 10],
|
||||
["state visit limit", 5, 5, 1],
|
||||
])(
|
||||
"rejects replay journals that exceed the declared %s",
|
||||
(_name, maxTransitions, maxUses, maxVisits) => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: maxVisits },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "again",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "again",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "again" }],
|
||||
max_uses: maxUses,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "complete",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "finish",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: maxTransitions,
|
||||
},
|
||||
};
|
||||
const capture = emptyCapture();
|
||||
const candidate: UnverifiedProcessCapture = {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
replay_transitions: [0, 1].map((sequence) => ({
|
||||
sequence,
|
||||
at_ms: sequence,
|
||||
transition_id: "again",
|
||||
state_before: "active",
|
||||
state_after: "active",
|
||||
sensitive_aliases: [],
|
||||
})),
|
||||
};
|
||||
|
||||
expect(processCaptureIssues(candidate)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining("limit"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("tells agents and users to recapture unsupported v3 evidence", () => {
|
||||
const legacy = { ...emptyCapture(), schema_version: 3 };
|
||||
expect(() => parseProcessCapture(legacy)).toThrow(
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
const parsed = processCaptureSchema.safeParse(legacy);
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected legacy capture rejection");
|
||||
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
});
|
||||
|
||||
it("requires compatible contracts and enforces capture age through a clock seam", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
comparison_contract: { changed: true },
|
||||
comparison_contract_sha256: digestProcessCommitment({
|
||||
changed: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrow("incompatible comparison contracts");
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, capture, {
|
||||
maxCaptureAgeMs: 1,
|
||||
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
|
||||
}),
|
||||
).toThrow("max_capture_age_ms");
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { digestProcessCommitment } from "./processCapture.js";
|
||||
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: JsonValue[] = [];
|
||||
const replayPlan = {};
|
||||
|
||||
/** Minimal valid process capture retained as a public contract example. */
|
||||
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "1.1.0",
|
||||
provider_version: "3",
|
||||
platform: "fixture",
|
||||
architecture: "fixture",
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
} satisfies JsonValue;
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import {
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
createProcessObservation,
|
||||
projectProcessObservation,
|
||||
} from "./processObservation.js";
|
||||
|
||||
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
const capture: UnverifiedProcessCapture = {
|
||||
...emptyCapture,
|
||||
frames: [{ sequence: 0, at_ms: 1, data: "Ready" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
columns: 80,
|
||||
rows: 24,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["Ready"],
|
||||
serialized_state: "Ready",
|
||||
},
|
||||
],
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 2,
|
||||
dispatched_at_ms: 3,
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 4,
|
||||
pid: 2,
|
||||
parent_pid: 1,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 5,
|
||||
command: "helper",
|
||||
route_index: 0,
|
||||
arguments: [],
|
||||
working_directory: "/fixture",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
protocol_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 6,
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: "/done",
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 7,
|
||||
transition_id: "done",
|
||||
state_before: "open",
|
||||
state_after: "closed",
|
||||
sensitive_aliases: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("process observation vocabulary", () => {
|
||||
it("projects every capture collection without timestamp sorting", () => {
|
||||
const locations = [
|
||||
{ collection: "frames", index: 0, capture_order: 4 },
|
||||
{ collection: "rendered_frames", index: 0, capture_order: 3 },
|
||||
{ collection: "interaction_events", index: 0, capture_order: 2 },
|
||||
{ collection: "lifecycle", index: 0, capture_order: 8 },
|
||||
{ collection: "lifecycle", index: 1, capture_order: 9 },
|
||||
{ collection: "process_samples", index: 0, capture_order: 1 },
|
||||
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
|
||||
{ collection: "shim_events", index: 0, capture_order: 5 },
|
||||
{ collection: "protocol_events", index: 0, capture_order: 6 },
|
||||
{ collection: "replay_transitions", index: 0, capture_order: 7 },
|
||||
] as const;
|
||||
const observations = locations.map((location) =>
|
||||
projectProcessObservation(capture, location),
|
||||
);
|
||||
|
||||
expect(observations.map((value) => value?.source)).toEqual([
|
||||
"terminal_raw",
|
||||
"terminal_rendered",
|
||||
"interaction",
|
||||
"lifecycle",
|
||||
"lifecycle",
|
||||
"process",
|
||||
"filesystem",
|
||||
"shim",
|
||||
"http",
|
||||
"replay_transition",
|
||||
]);
|
||||
expect(observations.map((value) => value?.capture_order)).toEqual(
|
||||
locations.map(({ capture_order }) => capture_order),
|
||||
);
|
||||
expect(observations[5]).toMatchObject({
|
||||
event_id: "obs.process_samples.0",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 4,
|
||||
subject_id: "process:2",
|
||||
});
|
||||
expect(observations[7]).toMatchObject({
|
||||
event_id: "obs.shim_events.0",
|
||||
subject_id: "shim:helper:route:0",
|
||||
});
|
||||
expect(observations[3]?.captured_at_ms).toBeNull();
|
||||
expect(observations[4]?.captured_at_ms).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the same constructor for live and post-hoc observations", () => {
|
||||
const location = {
|
||||
collection: "frames" as const,
|
||||
index: 0,
|
||||
capture_order: 4,
|
||||
};
|
||||
const projected = projectProcessObservation(capture, location);
|
||||
const live = createProcessObservation({
|
||||
source: "terminal_raw",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 1,
|
||||
subject_id: null,
|
||||
location,
|
||||
payload: capture.frames[0],
|
||||
});
|
||||
expect(live).toEqual(projected);
|
||||
});
|
||||
|
||||
it("returns no observation for a missing raw record", () => {
|
||||
expect(
|
||||
projectProcessObservation(capture, {
|
||||
collection: "frames",
|
||||
index: 1,
|
||||
capture_order: 10,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyProtocolFamily,
|
||||
decodeGrpcFrame,
|
||||
decodeJsonRpc,
|
||||
decodeMessagePack,
|
||||
inferMessageSchema,
|
||||
looksLikeCredential,
|
||||
protocolCaptureSchema,
|
||||
type ProtocolMessage,
|
||||
} from "./protocolCapture.js";
|
||||
|
||||
describe("protocol capture", () => {
|
||||
it("classifies gRPC from content type", () => {
|
||||
expect(classifyProtocolFamily("application/grpc+proto", null)).toBe("grpc");
|
||||
});
|
||||
|
||||
it("classifies protobuf from content type", () => {
|
||||
expect(classifyProtocolFamily("application/x-protobuf", null)).toBe(
|
||||
"protobuf",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies json-rpc from content type", () => {
|
||||
expect(classifyProtocolFamily("application/json-rpc", null)).toBe(
|
||||
"json-rpc",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies msgpack from content type", () => {
|
||||
expect(classifyProtocolFamily("application/msgpack", null)).toBe(
|
||||
"messagepack",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies from path when content type is null", () => {
|
||||
expect(classifyProtocolFamily(null, "/some/grpc/method")).toBe("grpc");
|
||||
expect(classifyProtocolFamily(null, "/api/json-rpc/2.0")).toBe("json-rpc");
|
||||
});
|
||||
|
||||
it("returns null for unknown protocols", () => {
|
||||
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
|
||||
expect(classifyProtocolFamily(null, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects credential-like field names", () => {
|
||||
expect(looksLikeCredential("password")).toBe(true);
|
||||
expect(looksLikeCredential("api_key")).toBe(true);
|
||||
expect(looksLikeCredential("authorization")).toBe(true);
|
||||
expect(looksLikeCredential("username")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON-RPC decoding", () => {
|
||||
it("decodes a simple JSON-RPC request", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
method: "add",
|
||||
params: [1, 2],
|
||||
id: 1,
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
expect(result.decoded_fields.length).toBe(4);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts credential-like fields", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
password: "secret123",
|
||||
username: "admin",
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
const passwordField = result.decoded_fields.find(
|
||||
(f) => f.path === "password",
|
||||
);
|
||||
expect(passwordField?.value).toBe("[REDACTED]");
|
||||
const usernameField = result.decoded_fields.find(
|
||||
(f) => f.path === "username",
|
||||
);
|
||||
expect(usernameField?.value).toBe("admin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagePack decoding", () => {
|
||||
it("detects map type", () => {
|
||||
const payload = new Uint8Array([0x82]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("map");
|
||||
});
|
||||
|
||||
it("detects array type", () => {
|
||||
const payload = new Uint8Array([0x92]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("array");
|
||||
});
|
||||
|
||||
it("reports unknown type for other tags", () => {
|
||||
const payload = new Uint8Array([0xff]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("unknown");
|
||||
expect(result.decoded_fields[0]?.inferred).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gRPC frame decoding", () => {
|
||||
it("decodes a valid gRPC frame header", () => {
|
||||
const payload = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x00, 0x05, 1, 2, 3, 4, 5,
|
||||
]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields).toHaveLength(2);
|
||||
expect(result.decoded_fields[0]?.path).toBe("compressed");
|
||||
expect(result.decoded_fields[0]?.value).toBe(false);
|
||||
expect(result.decoded_fields[1]?.path).toBe("message_length");
|
||||
expect(result.decoded_fields[1]?.value).toBe(5);
|
||||
});
|
||||
|
||||
it("detects compressed flag", () => {
|
||||
const payload = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x0a]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe(true);
|
||||
});
|
||||
|
||||
it("handles too-short frames", () => {
|
||||
const payload = new Uint8Array([0x00, 0x01]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.path).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("schema inference", () => {
|
||||
it("infers schema from repeated messages", () => {
|
||||
const messages: ProtocolMessage[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
family: "json-rpc",
|
||||
direction: "request",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "method", wire_type: "json", value: "add", inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
family: "json-rpc",
|
||||
direction: "response",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "result", wire_type: "json", value: 3, inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
];
|
||||
const hypotheses = inferMessageSchema(messages);
|
||||
expect(hypotheses).toHaveLength(3);
|
||||
const idHypothesis = hypotheses.find((h) => h.field_name === "id");
|
||||
expect(idHypothesis).toBeDefined();
|
||||
expect(idHypothesis!.evidence_count).toBe(2);
|
||||
expect(idHypothesis!.confidence).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("protocol capture schema validation", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
family: "grpc" as const,
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = protocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -77,7 +77,6 @@ export const protocolCaptureSchema = z.strictObject({
|
||||
/** Whether credentials were detected and redacted. */
|
||||
credentials_detected: z.boolean().default(false),
|
||||
});
|
||||
export type ProtocolCapture = z.infer<typeof protocolCaptureSchema>;
|
||||
|
||||
/** Classification of a byte sequence as a known protocol family. */
|
||||
export function classifyProtocolFamily(
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
verifyReconstruction,
|
||||
} from "./reconstructionVerification.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../contracts/artifactComparisonExample.js";
|
||||
import { createResidualUnknown } from "./residualUnknown.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
replayMachineRunInputSchema,
|
||||
runReplayMachine,
|
||||
} from "./replayMachineRun.js";
|
||||
|
||||
const loginRun = () =>
|
||||
replayMachineRunInputSchema.parse({
|
||||
machine: {
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "target-secret" },
|
||||
body: "target-secret",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
limits: {
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
},
|
||||
events: [
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 1,
|
||||
method: "post",
|
||||
path: "/login",
|
||||
headers: {},
|
||||
body: '{"token":"target-secret"}',
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 2,
|
||||
method: "GET",
|
||||
path: "/api",
|
||||
headers: { Authorization: "target-secret" },
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const parseMachineRun = (machine: unknown, events: unknown[]) =>
|
||||
replayMachineRunInputSchema.parse({ machine, events });
|
||||
|
||||
const httpEvent = (path: string, atMs = 0) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: atMs,
|
||||
method: "GET",
|
||||
path,
|
||||
headers: {},
|
||||
body: "",
|
||||
});
|
||||
|
||||
describe("direct replay machine execution", () => {
|
||||
it("returns actions, aliases, terminal state, and exact limit use", () => {
|
||||
const result = runReplayMachine(loginRun());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
schema_version: 1,
|
||||
initial_state: "login",
|
||||
final_state: "complete",
|
||||
terminal: true,
|
||||
decisions: [
|
||||
{ event_sequence: 0, outcome: "matched", transition_sequence: 0 },
|
||||
{ event_sequence: 1, outcome: "matched", transition_sequence: 1 },
|
||||
],
|
||||
transition_journal: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
captured_aliases: [{ name: "token", sensitive: true }],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
captured_aliases: [],
|
||||
},
|
||||
],
|
||||
transition_actions: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "<secret:token>" },
|
||||
body: "<secret:token>",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
limits: {
|
||||
configured: {
|
||||
transitions: 2,
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
usage: {
|
||||
offered_events: 2,
|
||||
admitted_events: 2,
|
||||
transitions: 2,
|
||||
connections: 0,
|
||||
messages: 0,
|
||||
bytes: 25,
|
||||
last_at_ms: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("target-secret");
|
||||
});
|
||||
|
||||
it("classifies unmatched and guard-failed events without aborting", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
events: [httpEvent("/missing"), input.events[0]!, httpEvent("/api", 2)],
|
||||
});
|
||||
|
||||
expect(result.decisions.map(({ outcome }) => outcome)).toEqual([
|
||||
"unmatched",
|
||||
"matched",
|
||||
"guard_failed",
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies exhausted transitions", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "retry_once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/retry" },
|
||||
actions: [{ type: "http_response", status: 200, body: "retry" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 200, body: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
},
|
||||
[httpEvent("/retry"), httpEvent("/retry", 1)],
|
||||
);
|
||||
|
||||
expect(
|
||||
runReplayMachine(input).decisions.map(({ outcome }) => outcome),
|
||||
).toEqual(["matched", "transition_exhausted"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine protocol and limits", () => {
|
||||
it("classifies reconnects that arrive in the wrong state", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "connected",
|
||||
states: [
|
||||
{ name: "connected" },
|
||||
{ name: "reconnecting" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "disconnect",
|
||||
from: "connected",
|
||||
to: "reconnecting",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/socket",
|
||||
body: "disconnect",
|
||||
},
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "reconnect",
|
||||
from: "reconnecting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: [{ type: "websocket_send", data: "ready" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
},
|
||||
[
|
||||
{
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/socket",
|
||||
headers: {},
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
expect(runReplayMachine(input).decisions[0]?.outcome).toBe(
|
||||
"unexpected_reconnect",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects protocol-inconsistent events at the boundary", () => {
|
||||
const input = loginRun();
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [{ ...httpEvent("/login"), method: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
headers: { Authorization: "first", authorization: "second" },
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reports limit refusals without committing rejected usage", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
machine: {
|
||||
...input.machine,
|
||||
limits: { ...input.machine.limits, bytes: 1 },
|
||||
},
|
||||
events: [input.events[0]!],
|
||||
});
|
||||
|
||||
expect(result.decisions).toEqual([
|
||||
{
|
||||
event_sequence: 0,
|
||||
outcome: "limit_exhausted",
|
||||
transition_sequence: null,
|
||||
},
|
||||
]);
|
||||
expect(result.limits.usage).toMatchObject({
|
||||
offered_events: 1,
|
||||
admitted_events: 0,
|
||||
transitions: 0,
|
||||
bytes: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine output bounds", () => {
|
||||
it("records large repeated actions once instead of amplifying each match", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 11 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "repeat",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/repeat" },
|
||||
actions: [{ type: "http_response", status: 200, body: largeBody }],
|
||||
max_uses: 10,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 11,
|
||||
},
|
||||
Array.from({ length: 10 }, (_, index) => httpEvent("/repeat", index)),
|
||||
);
|
||||
|
||||
const result = runReplayMachine(input);
|
||||
expect(result.transition_journal).toHaveLength(10);
|
||||
expect(result.transition_actions).toHaveLength(1);
|
||||
expect(JSON.stringify(result).length).toBeLessThan(1_100_000);
|
||||
});
|
||||
|
||||
it("rejects aggregate action output above four MiB", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const parsed = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "send",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: Array.from({ length: 5 }, () => ({
|
||||
type: "websocket_send",
|
||||
data: largeBody,
|
||||
})),
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (!parsed.success)
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds action-field and sensitive-redaction work structurally", () => {
|
||||
const input = loginRun();
|
||||
const excessiveCaptures = replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: Array.from({ length: 1_025 }, () => input.events[0]),
|
||||
});
|
||||
expect(excessiveCaptures.success).toBe(false);
|
||||
if (!excessiveCaptures.success)
|
||||
expect(excessiveCaptures.error.issues).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: ["events"] })]),
|
||||
);
|
||||
|
||||
const excessiveFields = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "respond",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: Object.fromEntries(
|
||||
Array.from({ length: 1_024 }, (_, index) => [
|
||||
`x-field-${String(index)}`,
|
||||
"",
|
||||
]),
|
||||
),
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
expect(excessiveFields.success).toBe(false);
|
||||
if (!excessiveFields.success)
|
||||
expect(excessiveFields.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "./replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("compares captured JSON values canonically", () => {
|
||||
const objectMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_profile",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_profile",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(objectMachine);
|
||||
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/capture", '{"profile":{"name":"A","id":1}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/guard", '{"profile":{"id":1,"name":"A"}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
});
|
||||
|
||||
it("does not traverse inherited properties in JSON capture paths", () => {
|
||||
const inheritedPathMachine = replayMachineSchema.parse({
|
||||
...machine,
|
||||
transitions: machine.transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...transition,
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: {
|
||||
source: "request_json" as const,
|
||||
path: ["__proto__", "toString"],
|
||||
},
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
: transition,
|
||||
),
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(inheritedPathMachine).dispatch(
|
||||
event("POST", "/login", "{}"),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
});
|
||||
|
||||
it("rejects non-string sensitive captures and retains rotated values", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(
|
||||
event("POST", "/login", '{"session_value":1234}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const rotatingMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "rotate",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "POST", path: "/rotate" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
});
|
||||
const rotating = new ReplayMachineRuntime(rotatingMachine);
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"alpha"}'));
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"beta"}'));
|
||||
const alias = ["<", "secret", ":session_value>"].join("");
|
||||
|
||||
expect(rotating.redact("alpha beta")).toBe(`${alias} ${alias}`);
|
||||
});
|
||||
|
||||
it("falls back to a lower-priority transition after a preferred one is exhausted", () => {
|
||||
const fallbackMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 2 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "preferred",
|
||||
from: "active",
|
||||
to: "active",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "again" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "fallback",
|
||||
from: "active",
|
||||
to: "done",
|
||||
priority: 20,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(fallbackMachine);
|
||||
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "preferred" },
|
||||
});
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "fallback" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-finite parsed JSON captures and guard values", () => {
|
||||
const jsonMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_value",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_value",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(jsonMachine).dispatch(
|
||||
event("POST", "/capture", '{"value":1e400}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const guarded = new ReplayMachineRuntime(jsonMachine);
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/capture", '{"value":null}')),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/guard", '{"value":1e400}')),
|
||||
).toMatchObject({ outcome: "guard_failed" });
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "./replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("captures secret values in memory and journals aliases only", () => {
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: {
|
||||
transition_id: "capture_token",
|
||||
sensitive_aliases: ["session_value"],
|
||||
},
|
||||
});
|
||||
const expectedRedaction = ["Bearer <", "secret", ":session_value>"].join("");
|
||||
expect(runtime.redact("Bearer test-auth-token")).toBe(expectedRedaction);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", { Authorization: "test-auth-token" }),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(JSON.stringify(runtime.timeline)).not.toContain("test-auth-token");
|
||||
expect(runtime.state).toBe("complete");
|
||||
});
|
||||
|
||||
it("classifies wrong-state, guard, capture, and exhaustion failures", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("GET", "/api")),
|
||||
).toMatchObject({ outcome: "invalid_state" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("POST", "/login", "{}")),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", {
|
||||
authorization: "test-token-placeholder",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "guard_failed",
|
||||
});
|
||||
const bounded = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [{ name: "active" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/once" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "transition_exhausted",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches bounded headers and bodies and distinguishes wrong-state reconnects", () => {
|
||||
const runtime = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "connected",
|
||||
states: [{ name: "connected" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "finish",
|
||||
from: "connected",
|
||||
to: "done",
|
||||
trigger: {
|
||||
protocol: "http",
|
||||
method: "POST",
|
||||
path: "/finish",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: '{"done":true}',
|
||||
},
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "initial_socket",
|
||||
from: "connected",
|
||||
to: "connected",
|
||||
trigger: { protocol: "websocket_connect", path: "/ws" },
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(runtime.dispatch(event("POST", "/finish", "wrong"))).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "initial",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "transition_exhausted" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/finish", '{"done":true}', {
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "unexpected_reconnect" });
|
||||
});
|
||||
|
||||
it("enforces state, connection, message, byte, and duration limits", () => {
|
||||
const limitedMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 1 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "loop",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "websocket_message", path: "/ws" },
|
||||
actions: [{ type: "websocket_send", data: "ack" }],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
limits: { connections: 1, messages: 1, bytes: 100, duration_ms: 10 },
|
||||
});
|
||||
const stateLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
stateLimited.dispatch({
|
||||
protocol: "websocket_message",
|
||||
connection: "not_applicable",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const messageLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
states: limitedMachine.states.map((state) =>
|
||||
state.name === "active" ? { ...state, max_visits: 3 } : state,
|
||||
),
|
||||
}),
|
||||
);
|
||||
const message = {
|
||||
protocol: "websocket_message" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
};
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "limit_exhausted",
|
||||
});
|
||||
const durationLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
durationLimited.dispatch({ ...event("GET", "/done"), at_ms: 11 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(limitedMachine).dispatch({
|
||||
...event("GET", "/done"),
|
||||
at_ms: Number.NaN,
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const monotonic = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 5 }),
|
||||
).toMatchObject({ outcome: "unmatched" });
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 4 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const byteLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
limits: { ...limitedMachine.limits, bytes: 4 },
|
||||
}),
|
||||
);
|
||||
expect(byteLimited.dispatch(event("GET", "/missing", "12345"))).toMatchObject(
|
||||
{ outcome: "limit_exhausted" },
|
||||
);
|
||||
const connectionLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
const connect = {
|
||||
protocol: "websocket_connect" as const,
|
||||
connection: "initial" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/unknown",
|
||||
headers: {},
|
||||
body: "",
|
||||
};
|
||||
expect(connectionLimited.dispatch(connect)).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
connectionLimited.dispatch({ ...connect, connection: "reconnect" }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
buildNativePeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed artifact failure classification", () => {
|
||||
it("distinguishes native, malformed, unsupported, and bounded metadata", () => {
|
||||
const nativeBytes = buildNativePeFixture();
|
||||
const native = inspectManagedArtifactBytes(
|
||||
nativeBytes,
|
||||
managedPeFixtureTarget(nativeBytes),
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
expect(native).toMatchObject({
|
||||
classification: { status: "not-managed" },
|
||||
metadata: { status: "absent" },
|
||||
coverage: { state: "unavailable" },
|
||||
});
|
||||
|
||||
const malformedBytes = buildManagedPeFixture({
|
||||
corruptMetadataSignature: true,
|
||||
});
|
||||
const malformed = inspectManagedArtifactBytes(
|
||||
malformedBytes,
|
||||
managedPeFixtureTarget(malformedBytes),
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
expect(malformed.classification.status).toBe("malformed");
|
||||
expect(malformed.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-metadata-root" }),
|
||||
]);
|
||||
|
||||
const unsupportedTableBytes = buildManagedPeFixture({
|
||||
metadataValidMaskExtra: 1n << 50n,
|
||||
});
|
||||
const unsupportedTable = inspectManagedArtifactBytes(
|
||||
unsupportedTableBytes,
|
||||
managedPeFixtureTarget(unsupportedTableBytes),
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
expect(unsupportedTable.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-tables" }),
|
||||
]);
|
||||
|
||||
const limitedBytes = buildManagedPeFixture();
|
||||
const limited = inspectManagedArtifactBytes(
|
||||
limitedBytes,
|
||||
managedPeFixtureTarget(limitedBytes),
|
||||
{ ...MANAGED_ARTIFACT_FIXTURE_LIMITS, maxMetadataBytes: 256 },
|
||||
);
|
||||
expect(limited.metadata.status).toBe("partial");
|
||||
expect(limited.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "limit-exceeded" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed artifact inventory", () => {
|
||||
it("inventories module, assembly, framework, references, and resources without loading CLR code", () => {
|
||||
const resource = Buffer.from("source-owned resource");
|
||||
const bytes = buildManagedPeFixture({ resourceData: resource });
|
||||
const result = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.classification).toMatchObject({
|
||||
status: "managed",
|
||||
runtime_family: "modern-dotnet",
|
||||
implementation: "cil",
|
||||
managed_architecture: "anycpu",
|
||||
});
|
||||
expect(result.pe.cli).toMatchObject({
|
||||
flag_names: ["il-only"],
|
||||
entry_point: { kind: "metadata-token", value: "0x06000001" },
|
||||
});
|
||||
expect(result.module).toMatchObject({
|
||||
name: "Fixture.dll",
|
||||
mvid: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
token: "0x00000001",
|
||||
});
|
||||
expect(result.assembly).toMatchObject({
|
||||
name: "Fixture.Managed",
|
||||
version: "1.2.3.4",
|
||||
token: "0x20000001",
|
||||
});
|
||||
expect(result.target_frameworks).toEqual([".NETCoreApp,Version=v8.0"]);
|
||||
expect(result.references).toMatchObject({
|
||||
total: 1,
|
||||
returned: 1,
|
||||
complete: true,
|
||||
items: [expect.objectContaining({ name: "System.Runtime" })],
|
||||
});
|
||||
expect(result.resources.items).toEqual([
|
||||
expect.objectContaining({
|
||||
name: "Fixture.resources",
|
||||
embedded: true,
|
||||
visibility: "private",
|
||||
data_length: resource.length,
|
||||
data_sha256: createHash("sha256").update(resource).digest("hex"),
|
||||
}),
|
||||
]);
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
});
|
||||
|
||||
it("keeps classification evidence complete when caller pages visible references", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
references: ["System.Runtime", "UnityEngine.CoreModule"],
|
||||
});
|
||||
const result = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
{
|
||||
...MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
referenceLimit: 1,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.classification.runtime_family).toBe("unity-mono");
|
||||
expect(result.references).toMatchObject({
|
||||
total: 2,
|
||||
returned: 1,
|
||||
complete: false,
|
||||
});
|
||||
expect(result.coverage.state).toBe("partial");
|
||||
expect(result.coverage.issues).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts CLI metadata GUIDs without RFC UUID version or variant bits", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
mvid: Buffer.from("3aebc60edc4a544b1f458b4ed40b33b1", "hex"),
|
||||
});
|
||||
const result = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
const members = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
const boundaries = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.module?.mvid).toBe("0ec6eb3a-4adc-4b54-1f45-8b4ed40b33b1");
|
||||
expect(result.classification.status).toBe("managed");
|
||||
expect(members.identity_scope.requires_mvid).toBe(result.module?.mvid);
|
||||
expect(boundaries.identity_scope.requires_mvid).toBe(result.module?.mvid);
|
||||
});
|
||||
|
||||
it("decodes ECMA-335 pointer and byref element types without swapping them", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
fieldSignature: Buffer.from([0x06, 0x1d, 0x0f, 0x0f, 0x08]),
|
||||
methodSignature: Buffer.from([
|
||||
0x00, 0x02, 0x10, 0x08, 0x0f, 0x08, 0x10, 0x0e,
|
||||
]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.fields.items[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: "i4**[]",
|
||||
});
|
||||
expect(result.methods.items[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
return_type: "i4&",
|
||||
parameter_types: ["i4*", "string&"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed CIL decoding", () => {
|
||||
it("reads fat method header size from the full flags-and-size word", () => {
|
||||
const il = Buffer.from([
|
||||
0x21, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x22, 0x00,
|
||||
0x00, 0x80, 0x3f, 0x26, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
|
||||
0x3f, 0x26, 0xfe, 0x06, 0x01, 0x00, 0x00, 0x06, 0x26, 0x2a,
|
||||
]);
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt16LE(0x3013, 0);
|
||||
header.writeUInt16LE(8, 2);
|
||||
header.writeUInt32LE(il.length, 4);
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([header, il]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "present",
|
||||
header_format: "fat",
|
||||
il_size: il.length,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
opcode_counts: {
|
||||
"ldc.i8": 1,
|
||||
pop: 4,
|
||||
"ldc.r4": 1,
|
||||
"ldc.r8": 1,
|
||||
ldftn: 1,
|
||||
ret: 1,
|
||||
},
|
||||
issue: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not normalize reserved CIL opcodes as operand-free instructions", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([0x0a, 0x24, 0x2a]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "malformed",
|
||||
il_size: 2,
|
||||
normalized_il_sha256: null,
|
||||
decoded_instruction_count: 0,
|
||||
issue: "Unsupported CIL opcode 0x24 at IL offset 0",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the documented decoded-CIL v1 golden vector stable", () => {
|
||||
const il = Buffer.from([0x00, 0x2a]);
|
||||
const tinyBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([0x0a, ...il]),
|
||||
});
|
||||
const fatHeader = Buffer.alloc(12);
|
||||
fatHeader.writeUInt16LE(0x3013, 0);
|
||||
fatHeader.writeUInt16LE(32, 2);
|
||||
fatHeader.writeUInt32LE(il.length, 4);
|
||||
fatHeader.writeUInt32LE(0x1100_0001, 8);
|
||||
const fatBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([fatHeader, il]),
|
||||
});
|
||||
const tiny = inspectManagedMembersBytes(
|
||||
tinyBytes,
|
||||
managedPeFixtureTarget(tinyBytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
const fat = inspectManagedMembersBytes(
|
||||
fatBytes,
|
||||
managedPeFixtureTarget(fatBytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(tiny.methods.items[0]?.body).toMatchObject({
|
||||
status: "present",
|
||||
header_format: "tiny",
|
||||
max_stack: 8,
|
||||
init_locals: false,
|
||||
local_var_sig_token: null,
|
||||
il_size: 2,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
normalized_il_sha256:
|
||||
"5e5fad7741cb44bca3a4f045546b7449990da343f612f5f34c0ca30e9eee0636",
|
||||
opcode_counts: { nop: 1, ret: 1 },
|
||||
exception_regions: [],
|
||||
});
|
||||
expect(fat.methods.items[0]?.body).toMatchObject({
|
||||
header_format: "fat",
|
||||
max_stack: 32,
|
||||
init_locals: true,
|
||||
local_var_sig_token: "0x11000001",
|
||||
il_sha256: tiny.methods.items[0]?.body.il_sha256,
|
||||
normalized_il_sha256: tiny.methods.items[0]?.body.normalized_il_sha256,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed CIL limits", () => {
|
||||
it("marks instruction-limited CIL as partial without assigning normalized identity", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
{
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
maxMethodInstructions: 1,
|
||||
},
|
||||
);
|
||||
const il = bytes.subarray(0x0a01, 0x0a0d);
|
||||
|
||||
expect(result.metadata.status).toBe("complete");
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "partial",
|
||||
il_size: 12,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
normalized_il_sha256: null,
|
||||
instruction_count: 1,
|
||||
decoded_instruction_count: 1,
|
||||
truncated_instructions: 1,
|
||||
issue:
|
||||
"Instruction decode reached max_method_instructions 1 before the end of the method body",
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
state: "partial",
|
||||
issues: [
|
||||
{
|
||||
code: "limit-exceeded",
|
||||
scope: "method.0x06000001.body.instructions",
|
||||
offset: 0x0a00,
|
||||
detail:
|
||||
"Instruction decode reached max_method_instructions 1 before the end of the method body",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.limitations.join(" ")).toContain(
|
||||
"has no normalized CIL identity",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed member inspection", () => {
|
||||
it("inspects metadata members, signatures, CIL hashes, call edges, and field anchors", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.identity_scope).toEqual({
|
||||
token_identity: "build-local",
|
||||
requires_artifact_sha256: managedPeFixtureTarget(bytes).sha256,
|
||||
requires_mvid: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
});
|
||||
expect(result.types.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x02000001",
|
||||
full_name: "Fixture.Program",
|
||||
field_list: { first_row: 1, last_row: 1, count: 1 },
|
||||
method_list: { first_row: 1, last_row: 1, count: 1 },
|
||||
}),
|
||||
]);
|
||||
expect(result.fields.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x04000001",
|
||||
declaring_type: "Fixture.Program",
|
||||
name: "counter",
|
||||
signature: expect.objectContaining({
|
||||
kind: "field",
|
||||
parse_status: "decoded",
|
||||
field_type: "i4",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.methods.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
declaring_type: "Fixture.Program",
|
||||
name: "Main",
|
||||
rva: 0x2800,
|
||||
signature: expect.objectContaining({
|
||||
kind: "method",
|
||||
parse_status: "decoded",
|
||||
return_type: "void",
|
||||
parameter_types: [],
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
status: "present",
|
||||
header_format: "tiny",
|
||||
file_offset: 0x0a00,
|
||||
il_size: 12,
|
||||
instruction_count: 4,
|
||||
decoded_instruction_count: 4,
|
||||
truncated_instructions: 0,
|
||||
opcode_counts: { "ldarg.0": 1, ldfld: 1, call: 1, ret: 1 },
|
||||
anchors: [
|
||||
{
|
||||
il_offset: 1,
|
||||
opcode: "ldfld",
|
||||
operand_kind: "field",
|
||||
operand: "0x04000001",
|
||||
},
|
||||
{
|
||||
il_offset: 6,
|
||||
opcode: "call",
|
||||
operand_kind: "method",
|
||||
operand: "0x0a000001",
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.member_refs.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x0a000001",
|
||||
name: ".ctor",
|
||||
signature: expect.objectContaining({
|
||||
kind: "method",
|
||||
parse_status: "decoded",
|
||||
parameter_types: ["string"],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.call_edges.items).toEqual([
|
||||
{
|
||||
caller_token: "0x06000001",
|
||||
caller: "Fixture.Program.Main",
|
||||
opcode: "call",
|
||||
target_token: "0x0a000001",
|
||||
target_kind: "member-ref",
|
||||
target_name: ".ctor",
|
||||
},
|
||||
]);
|
||||
expect(result.field_accesses.items).toEqual([
|
||||
{
|
||||
method_token: "0x06000001",
|
||||
method: "Fixture.Program.Main",
|
||||
opcode: "ldfld",
|
||||
field_token: "0x04000001",
|
||||
field_name: "counter",
|
||||
},
|
||||
]);
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
buildNativePeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
} from "./ManagedPe.fixture.js";
|
||||
|
||||
describe("managed native boundaries", () => {
|
||||
it("inspects managed/native PInvoke declarations without verifying native exports", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
pinvoke: {
|
||||
moduleName: "user32.dll",
|
||||
importName: "MessageBoxW",
|
||||
mappingFlags: 0x0345,
|
||||
},
|
||||
readyToRun: true,
|
||||
});
|
||||
const result = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
);
|
||||
|
||||
expect(result.cli_native).toMatchObject({
|
||||
il_only: true,
|
||||
ready_to_run_signature: true,
|
||||
managed_native_header_rva: 0x2700,
|
||||
managed_native_header_size: 4,
|
||||
});
|
||||
expect(result.module_refs.items).toEqual([
|
||||
{
|
||||
token: "0x1a000001",
|
||||
row_offset: expect.any(Number),
|
||||
name: "user32.dll",
|
||||
},
|
||||
]);
|
||||
expect(result.pinvoke_imports.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x1c000001",
|
||||
member_token: "0x06000001",
|
||||
member_kind: "method",
|
||||
member_name: "Main",
|
||||
import_name: "MessageBoxW",
|
||||
import_scope_token: "0x1a000001",
|
||||
import_scope_name: "user32.dll",
|
||||
no_mangle: true,
|
||||
char_set: "unicode",
|
||||
call_convention: "stdcall",
|
||||
supports_last_error: true,
|
||||
verification: "managed-declaration-only",
|
||||
}),
|
||||
]);
|
||||
expect(result.native_implementations.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
name: "Main",
|
||||
pinvoke_declared: true,
|
||||
boundary_kind: "pinvoke",
|
||||
body_interpretation: "native-or-runtime",
|
||||
}),
|
||||
]);
|
||||
expect(result.summary).toMatchObject({
|
||||
module_ref_count: 1,
|
||||
pinvoke_import_count: 1,
|
||||
native_implementation_count: 1,
|
||||
ready_to_run: true,
|
||||
mixed_mode_or_native_header: true,
|
||||
});
|
||||
expect(result.limitations).toContain(
|
||||
"P/Invoke rows prove managed import declarations only; this inspection does not verify that a native library, export, thunk, or provider-qualified function exists.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps member evidence bounded and typed for pagination and unavailable metadata", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const paged = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
{
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
methodLimit: 0 + 1,
|
||||
instructionAnchorLimit: 1,
|
||||
},
|
||||
);
|
||||
expect(paged.methods).toMatchObject({
|
||||
total: 1,
|
||||
returned: 1,
|
||||
complete: true,
|
||||
});
|
||||
expect(paged.methods.items[0]?.body.anchors).toHaveLength(1);
|
||||
|
||||
const nativeBytes = buildNativePeFixture();
|
||||
const native = inspectManagedMembersBytes(
|
||||
nativeBytes,
|
||||
managedPeFixtureTarget(nativeBytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
expect(native.metadata.status).toBe("absent");
|
||||
expect(native.coverage.state).toBe("unavailable");
|
||||
|
||||
const malformedBytes = buildManagedPeFixture({
|
||||
corruptMetadataSignature: true,
|
||||
});
|
||||
const malformed = inspectManagedMembersBytes(
|
||||
malformedBytes,
|
||||
managedPeFixtureTarget(malformedBytes),
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
expect(malformed.metadata.status).toBe("malformed");
|
||||
expect(malformed.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-metadata-root" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,512 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
|
||||
interface ManagedPeFixtureOptions {
|
||||
readonly cliFlags?: number;
|
||||
readonly corruptMetadataSignature?: boolean;
|
||||
readonly fieldName?: string;
|
||||
readonly fieldSignature?: Buffer;
|
||||
readonly ilBody?: Buffer;
|
||||
readonly metadataValidMaskExtra?: bigint;
|
||||
readonly methodName?: string;
|
||||
readonly methodSignature?: Buffer;
|
||||
readonly mvid?: Buffer;
|
||||
readonly pinvoke?: {
|
||||
readonly importName?: string;
|
||||
readonly mappingFlags?: number;
|
||||
readonly moduleName?: string;
|
||||
};
|
||||
readonly readyToRun?: boolean;
|
||||
readonly references?: readonly string[];
|
||||
readonly resourceData?: Buffer;
|
||||
readonly targetFramework?: string;
|
||||
readonly typeName?: string;
|
||||
readonly typeNamespace?: string;
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
const align4 = (value: number): number => (value + 3) & ~3;
|
||||
|
||||
const cString = (value: string): Buffer => Buffer.from(`${value}\0`, "utf8");
|
||||
|
||||
class StringHeap {
|
||||
readonly #chunks: Buffer[] = [Buffer.from([0])];
|
||||
#size = 1;
|
||||
|
||||
add(value: string): number {
|
||||
if (value.length === 0) return 0;
|
||||
const index = this.#size;
|
||||
const chunk = cString(value);
|
||||
this.#chunks.push(chunk);
|
||||
this.#size += chunk.length;
|
||||
return index;
|
||||
}
|
||||
|
||||
toBuffer(): Buffer {
|
||||
return Buffer.concat(this.#chunks);
|
||||
}
|
||||
}
|
||||
|
||||
class BlobHeap {
|
||||
readonly #chunks: Buffer[] = [Buffer.from([0])];
|
||||
#size = 1;
|
||||
|
||||
add(value: Buffer): number {
|
||||
if (value.length === 0) return 0;
|
||||
if (value.length > 0x7f)
|
||||
throw new RangeError("Managed PE fixture blob is too large");
|
||||
const index = this.#size;
|
||||
this.#chunks.push(Buffer.from([value.length]), value);
|
||||
this.#size += value.length + 1;
|
||||
return index;
|
||||
}
|
||||
|
||||
toBuffer(): Buffer {
|
||||
return Buffer.concat(this.#chunks);
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_MVID = Buffer.from([
|
||||
0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
|
||||
0xdd, 0xee, 0xff,
|
||||
]);
|
||||
|
||||
/** Generous bounds for inventory assertions over the source-owned PE fixture. */
|
||||
export const MANAGED_ARTIFACT_FIXTURE_LIMITS = {
|
||||
referenceOffset: 0,
|
||||
referenceLimit: 100,
|
||||
resourceOffset: 0,
|
||||
resourceLimit: 100,
|
||||
attributeOffset: 0,
|
||||
attributeLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
/** Generous bounds for member assertions over the source-owned PE fixture. */
|
||||
export const MANAGED_MEMBER_FIXTURE_LIMITS = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
/** Member bounds for fixture tests that inspect a real local path. */
|
||||
export const MANAGED_MEMBER_PATH_FIXTURE_LIMITS = {
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
maxFileBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
/** Generous native-boundary bounds for the source-owned PE fixture. */
|
||||
export const MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS = {
|
||||
moduleRefOffset: 0,
|
||||
moduleRefLimit: 100,
|
||||
importOffset: 0,
|
||||
importLimit: 100,
|
||||
implementationOffset: 0,
|
||||
implementationLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
/** Describe fixture bytes as the managed PE target consumed by static inspectors. */
|
||||
export const managedPeFixtureTarget = (
|
||||
bytes: Buffer,
|
||||
path = "/fixture.exe",
|
||||
): BinaryTarget => ({
|
||||
path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
|
||||
const guidHeap = (mvid: Buffer = DEFAULT_MVID): Buffer => {
|
||||
if (mvid.length !== 16)
|
||||
throw new RangeError("Managed PE fixture MVID must be 16 bytes");
|
||||
return Buffer.from(mvid);
|
||||
};
|
||||
|
||||
const u16 = (value: number): Buffer => {
|
||||
const bytes = Buffer.alloc(2);
|
||||
bytes.writeUInt16LE(value, 0);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const u32 = (value: number): Buffer => {
|
||||
const bytes = Buffer.alloc(4);
|
||||
bytes.writeUInt32LE(value, 0);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const moduleRow = (name: number): Buffer =>
|
||||
Buffer.concat([u16(0), u16(name), u16(1), u16(0), u16(0)]);
|
||||
|
||||
const typeRefRow = (name: number, namespace: number): Buffer =>
|
||||
Buffer.concat([u16(0), u16(name), u16(namespace)]);
|
||||
|
||||
const typeDefRow = (
|
||||
name: number,
|
||||
namespace: number,
|
||||
fieldList: number,
|
||||
methodList: number,
|
||||
): Buffer =>
|
||||
Buffer.concat([
|
||||
u32(0x0010_0001),
|
||||
u16(name),
|
||||
u16(namespace),
|
||||
u16((1 << 2) | 1),
|
||||
u16(fieldList),
|
||||
u16(methodList),
|
||||
]);
|
||||
|
||||
const fieldRow = (name: number, signature: number): Buffer =>
|
||||
Buffer.concat([u16(0x0001), u16(name), u16(signature)]);
|
||||
|
||||
interface MethodDefRowInput {
|
||||
readonly name: number;
|
||||
readonly signature: number;
|
||||
readonly rva?: number;
|
||||
readonly flags?: number;
|
||||
readonly implFlags?: number;
|
||||
}
|
||||
|
||||
const methodDefRow = ({
|
||||
name,
|
||||
signature,
|
||||
rva = 0,
|
||||
flags = 0x0016,
|
||||
implFlags = 0,
|
||||
}: MethodDefRowInput): Buffer =>
|
||||
Buffer.concat([
|
||||
u32(rva),
|
||||
u16(implFlags),
|
||||
u16(flags),
|
||||
u16(name),
|
||||
u16(signature),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const memberRefRow = (name: number, signature: number): Buffer =>
|
||||
Buffer.concat([u16((1 << 3) | 1), u16(name), u16(signature)]);
|
||||
|
||||
const moduleRefRow = (name: number): Buffer => Buffer.concat([u16(name)]);
|
||||
|
||||
const implMapRow = (
|
||||
importName: number,
|
||||
importScope: number,
|
||||
mappingFlags: number,
|
||||
): Buffer =>
|
||||
Buffer.concat([
|
||||
u16(mappingFlags),
|
||||
u16((1 << 1) | 1),
|
||||
u16(importName),
|
||||
u16(importScope),
|
||||
]);
|
||||
|
||||
const assemblyRow = (name: number): Buffer =>
|
||||
Buffer.concat([
|
||||
u32(0x0000_8004),
|
||||
u16(1),
|
||||
u16(2),
|
||||
u16(3),
|
||||
u16(4),
|
||||
u32(0),
|
||||
u16(0),
|
||||
u16(name),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const assemblyRefRow = (name: number, keyOrToken: number): Buffer =>
|
||||
Buffer.concat([
|
||||
u16(8),
|
||||
u16(0),
|
||||
u16(0),
|
||||
u16(0),
|
||||
u32(0),
|
||||
u16(keyOrToken),
|
||||
u16(name),
|
||||
u16(0),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const customAttributeRow = (value: number): Buffer =>
|
||||
Buffer.concat([u16((1 << 5) | 14), u16((1 << 3) | 3), u16(value)]);
|
||||
|
||||
const manifestResourceRow = (name: number): Buffer =>
|
||||
Buffer.concat([u32(0), u32(2), u16(name), u16(0)]);
|
||||
|
||||
const fixedStringAttributeBlob = (value: string): Buffer => {
|
||||
const bytes = Buffer.from(textEncoder.encode(value));
|
||||
if (bytes.length > 0x7f)
|
||||
throw new RangeError("Managed PE fixture target framework is too long");
|
||||
return Buffer.concat([Buffer.from([1, 0, bytes.length]), bytes, u16(0)]);
|
||||
};
|
||||
|
||||
const metadataStreamHeader = (
|
||||
relativeOffset: number,
|
||||
size: number,
|
||||
name: string,
|
||||
): Buffer => {
|
||||
const named = cString(name);
|
||||
const paddedName = Buffer.alloc(align4(named.length));
|
||||
named.copy(paddedName);
|
||||
return Buffer.concat([u32(relativeOffset), u32(size), paddedName]);
|
||||
};
|
||||
|
||||
const metadataRoot = (
|
||||
tables: Buffer,
|
||||
strings: Buffer,
|
||||
guid: Buffer,
|
||||
blob: Buffer,
|
||||
): Buffer => {
|
||||
const version = Buffer.from("v4.0.30319\0\0", "utf8");
|
||||
const header = Buffer.concat([
|
||||
u32(0x424a_5342),
|
||||
u16(1),
|
||||
u16(1),
|
||||
u32(0),
|
||||
u32(version.length),
|
||||
version,
|
||||
u16(0),
|
||||
u16(4),
|
||||
]);
|
||||
const streamHeaderSize =
|
||||
metadataStreamHeader(0, 0, "#~").length +
|
||||
metadataStreamHeader(0, 0, "#Strings").length +
|
||||
metadataStreamHeader(0, 0, "#GUID").length +
|
||||
metadataStreamHeader(0, 0, "#Blob").length;
|
||||
let offset = align4(header.length + streamHeaderSize);
|
||||
const tablesOffset = offset;
|
||||
offset = align4(offset + tables.length);
|
||||
const stringsOffset = offset;
|
||||
offset = align4(offset + strings.length);
|
||||
const guidOffset = offset;
|
||||
offset = align4(offset + guid.length);
|
||||
const blobOffset = offset;
|
||||
const headers = Buffer.concat([
|
||||
metadataStreamHeader(tablesOffset, tables.length, "#~"),
|
||||
metadataStreamHeader(stringsOffset, strings.length, "#Strings"),
|
||||
metadataStreamHeader(guidOffset, guid.length, "#GUID"),
|
||||
metadataStreamHeader(blobOffset, blob.length, "#Blob"),
|
||||
]);
|
||||
const root = Buffer.alloc(align4(blobOffset + blob.length));
|
||||
header.copy(root, 0);
|
||||
headers.copy(root, header.length);
|
||||
tables.copy(root, tablesOffset);
|
||||
strings.copy(root, stringsOffset);
|
||||
guid.copy(root, guidOffset);
|
||||
blob.copy(root, blobOffset);
|
||||
return root;
|
||||
};
|
||||
|
||||
const tablesStream = (
|
||||
rows: ReadonlyMap<number, readonly Buffer[]>,
|
||||
extraValidMask: bigint,
|
||||
): Buffer => {
|
||||
let valid = extraValidMask;
|
||||
for (const table of rows.keys()) valid |= 1n << BigInt(table);
|
||||
const header = Buffer.alloc(24);
|
||||
header.writeUInt8(2, 4);
|
||||
header.writeUInt8(1, 7);
|
||||
header.writeBigUInt64LE(valid, 8);
|
||||
const counts: Buffer[] = [];
|
||||
for (let index = 0; index <= 44; index += 1) {
|
||||
const tableRows = rows.get(index);
|
||||
if (tableRows === undefined) continue;
|
||||
counts.push(u32(tableRows.length));
|
||||
}
|
||||
const data: Buffer[] = [];
|
||||
for (let index = 0; index <= 44; index += 1) {
|
||||
const tableRows = rows.get(index);
|
||||
if (tableRows === undefined) continue;
|
||||
data.push(...tableRows);
|
||||
}
|
||||
return Buffer.concat([header, ...counts, ...data]);
|
||||
};
|
||||
|
||||
const buildManagedFixtureMetadata = (
|
||||
options: ManagedPeFixtureOptions,
|
||||
): Buffer => {
|
||||
const strings = new StringHeap();
|
||||
const blobs = new BlobHeap();
|
||||
const moduleName = strings.add("Fixture.dll");
|
||||
const assemblyName = strings.add("Fixture.Managed");
|
||||
const attributeName = strings.add("TargetFrameworkAttribute");
|
||||
const attributeNamespace = strings.add("System.Runtime.Versioning");
|
||||
const constructorName = strings.add(".ctor");
|
||||
const typeName = strings.add(options.typeName ?? "Program");
|
||||
const typeNamespace = strings.add(options.typeNamespace ?? "Fixture");
|
||||
const fieldName = strings.add(options.fieldName ?? "counter");
|
||||
const methodName = strings.add(options.methodName ?? "Main");
|
||||
const pinvokeModuleName =
|
||||
options.pinvoke === undefined
|
||||
? null
|
||||
: strings.add(options.pinvoke.moduleName ?? "user32.dll");
|
||||
const pinvokeImportName =
|
||||
options.pinvoke === undefined
|
||||
? null
|
||||
: strings.add(options.pinvoke.importName ?? "MessageBoxW");
|
||||
const resourceName = strings.add("Fixture.resources");
|
||||
const referenceNames = options.references ?? ["System.Runtime"];
|
||||
const referenceStringIndexes = referenceNames.map((name) =>
|
||||
strings.add(name),
|
||||
);
|
||||
const tokenBlob = blobs.add(Buffer.from("b77a5c561934e089", "hex"));
|
||||
const fieldSignature = blobs.add(
|
||||
options.fieldSignature ?? Buffer.from([0x06, 0x08]),
|
||||
);
|
||||
const methodSignature = blobs.add(
|
||||
options.methodSignature ?? Buffer.from([0x00, 0x00, 0x01]),
|
||||
);
|
||||
const constructorSignature = blobs.add(Buffer.from([0x20, 0x01, 0x01, 0x0e]));
|
||||
const attributeBlob = blobs.add(
|
||||
fixedStringAttributeBlob(
|
||||
options.targetFramework ?? ".NETCoreApp,Version=v8.0",
|
||||
),
|
||||
);
|
||||
const rows = new Map<number, readonly Buffer[]>([
|
||||
[0, [moduleRow(moduleName)]],
|
||||
[1, [typeRefRow(attributeName, attributeNamespace)]],
|
||||
[2, [typeDefRow(typeName, typeNamespace, 1, 1)]],
|
||||
[4, [fieldRow(fieldName, fieldSignature)]],
|
||||
[
|
||||
6,
|
||||
[
|
||||
methodDefRow({
|
||||
name: methodName,
|
||||
signature: methodSignature,
|
||||
rva: 0x2800,
|
||||
flags: options.pinvoke === undefined ? 0x0016 : 0x2016,
|
||||
}),
|
||||
],
|
||||
],
|
||||
[10, [memberRefRow(constructorName, constructorSignature)]],
|
||||
[12, [customAttributeRow(attributeBlob)]],
|
||||
...(pinvokeModuleName === null
|
||||
? []
|
||||
: ([[26, [moduleRefRow(pinvokeModuleName)]]] as const)),
|
||||
...(pinvokeImportName === null
|
||||
? []
|
||||
: ([
|
||||
[
|
||||
28,
|
||||
[
|
||||
implMapRow(
|
||||
pinvokeImportName,
|
||||
1,
|
||||
options.pinvoke?.mappingFlags ?? 0x0344,
|
||||
),
|
||||
],
|
||||
],
|
||||
] as const)),
|
||||
[32, [assemblyRow(assemblyName)]],
|
||||
[35, referenceStringIndexes.map((name) => assemblyRefRow(name, tokenBlob))],
|
||||
[40, [manifestResourceRow(resourceName)]],
|
||||
]);
|
||||
const metadata = metadataRoot(
|
||||
tablesStream(rows, options.metadataValidMaskExtra ?? 0n),
|
||||
strings.toBuffer(),
|
||||
guidHeap(options.mvid),
|
||||
blobs.toBuffer(),
|
||||
);
|
||||
if (options.corruptMetadataSignature === true) metadata.writeUInt32LE(0, 0);
|
||||
return metadata;
|
||||
};
|
||||
|
||||
const buildManagedFixtureImage = (
|
||||
options: ManagedPeFixtureOptions,
|
||||
metadata: Buffer,
|
||||
): Buffer => {
|
||||
const resourceData = options.resourceData ?? Buffer.from("resource-data");
|
||||
const resourceDirectory = Buffer.concat([
|
||||
u32(resourceData.length),
|
||||
resourceData,
|
||||
]);
|
||||
const image = Buffer.alloc(0x1000);
|
||||
image.write("MZ", 0, "ascii");
|
||||
image.writeUInt32LE(0x80, 0x3c);
|
||||
image.writeUInt32LE(0x0000_4550, 0x80);
|
||||
const coff = 0x84;
|
||||
image.writeUInt16LE(0x014c, coff);
|
||||
image.writeUInt16LE(1, coff + 2);
|
||||
image.writeUInt16LE(0x00e0, coff + 16);
|
||||
image.writeUInt16LE(0x0102, coff + 18);
|
||||
const optional = coff + 20;
|
||||
image.writeUInt16LE(0x010b, optional);
|
||||
image.writeUInt32LE(0x2000, optional + 20);
|
||||
image.writeUInt32LE(0x0040_0000, optional + 28);
|
||||
image.writeUInt32LE(0x1000, optional + 32);
|
||||
image.writeUInt32LE(0x200, optional + 36);
|
||||
image.writeUInt32LE(0x3000, optional + 56);
|
||||
image.writeUInt32LE(0x200, optional + 60);
|
||||
image.writeUInt32LE(16, optional + 92);
|
||||
image.writeUInt32LE(0x2000, optional + 96 + 14 * 8);
|
||||
image.writeUInt32LE(72, optional + 96 + 14 * 8 + 4);
|
||||
const section = optional + 0x00e0;
|
||||
image.write(".text\0\0\0", section, "ascii");
|
||||
image.writeUInt32LE(0x1000, section + 8);
|
||||
image.writeUInt32LE(0x2000, section + 12);
|
||||
image.writeUInt32LE(0x0e00, section + 16);
|
||||
image.writeUInt32LE(0x0200, section + 20);
|
||||
image.writeUInt32LE(0x6000_0020, section + 36);
|
||||
const cli = 0x0200;
|
||||
image.writeUInt32LE(72, cli);
|
||||
image.writeUInt16LE(2, cli + 4);
|
||||
image.writeUInt16LE(5, cli + 6);
|
||||
image.writeUInt32LE(0x2100, cli + 8);
|
||||
image.writeUInt32LE(metadata.length, cli + 12);
|
||||
image.writeUInt32LE(options.cliFlags ?? 1, cli + 16);
|
||||
image.writeUInt32LE(0x0600_0001, cli + 20);
|
||||
image.writeUInt32LE(0x2600, cli + 24);
|
||||
image.writeUInt32LE(resourceDirectory.length, cli + 28);
|
||||
if (options.readyToRun === true) {
|
||||
image.writeUInt32LE(0x2700, cli + 64);
|
||||
image.writeUInt32LE(4, cli + 68);
|
||||
image.write("RTR\0", 0x0900, "ascii");
|
||||
}
|
||||
(
|
||||
options.ilBody ??
|
||||
Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x01, 0x00, 0x00, 0x04, 0x28, 0x01, 0x00, 0x00, 0x0a,
|
||||
0x2a,
|
||||
])
|
||||
).copy(image, 0x0a00);
|
||||
metadata.copy(image, 0x0300);
|
||||
resourceDirectory.copy(image, 0x0800);
|
||||
return image;
|
||||
};
|
||||
|
||||
/** Build a source-owned PE32/CLI fixture without committing compiled binaries. */
|
||||
export const buildManagedPeFixture = (
|
||||
options: ManagedPeFixtureOptions = {},
|
||||
): Buffer =>
|
||||
buildManagedFixtureImage(options, buildManagedFixtureMetadata(options));
|
||||
|
||||
/** Build a syntactically valid PE32 fixture with no CLI directory. */
|
||||
export const buildNativePeFixture = (): Buffer => {
|
||||
const image = buildManagedPeFixture();
|
||||
const cliDirectory = 0x84 + 20 + 96 + 14 * 8;
|
||||
image.writeUInt32LE(0, cliDirectory);
|
||||
image.writeUInt32LE(0, cliDirectory + 4);
|
||||
return image;
|
||||
};
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDoctor, type DoctorHost } from "../application/Doctor.js";
|
||||
import { createDoctorHostFixture } from "../application/Doctor.fixture.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
type GhidraInstallationHost,
|
||||
type GhidraInstallationInspection,
|
||||
} from "./GhidraInstallation.js";
|
||||
import { projectGhidraDoctorInspection } from "./GhidraDoctor.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
const installationHost = (
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationHost => ({
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const inspection = (
|
||||
options: {
|
||||
readonly installDir?: string;
|
||||
readonly architecture?: NodeJS.Architecture;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
} = { installDir: INSTALL },
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationInspection =>
|
||||
inspectGhidraInstallation(
|
||||
{
|
||||
platform: options.platform ?? "linux",
|
||||
architecture: options.architecture ?? "x64",
|
||||
...(options.installDir === undefined
|
||||
? {}
|
||||
: { installDir: options.installDir }),
|
||||
},
|
||||
installationHost(overrides),
|
||||
);
|
||||
|
||||
const doctorHost = (
|
||||
ghidra: GhidraInstallationInspection,
|
||||
hopperAvailable = false,
|
||||
): DoctorHost =>
|
||||
createDoctorHostFixture({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: (path) =>
|
||||
Promise.resolve(hopperAvailable && path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
providerInspections: () =>
|
||||
Promise.resolve([projectGhidraDoctorInspection(ghidra)]),
|
||||
});
|
||||
|
||||
describe("Ghidra doctor integration", () => {
|
||||
it("accepts a valid BYO Ghidra engine when Hopper is absent", async () => {
|
||||
const result = await runDoctor(undefined, doctorHost(inspection()));
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.providerInspections?.[0]).toMatchObject({
|
||||
id: "ghidra",
|
||||
available: true,
|
||||
providerVersion: "12.1.2",
|
||||
registrationEnvironment: {
|
||||
GHIDRA_INSTALL_DIR: INSTALL,
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "ghidra-java"),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
detail: expect.stringContaining("21.0.11"),
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the experimental Windows x64 Ghidra provider boundary", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.2_PUBLIC",
|
||||
platform: "win32",
|
||||
});
|
||||
const result = await runDoctor(undefined, {
|
||||
...doctorHost(ghidra),
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
});
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"bad installation",
|
||||
inspection({ installDir: INSTALL }, { readText: () => undefined }),
|
||||
"ghidra-installation",
|
||||
],
|
||||
[
|
||||
"wrong version",
|
||||
inspection(
|
||||
{ installDir: INSTALL },
|
||||
{ readText: () => "application.version=11.4\n" },
|
||||
),
|
||||
"ghidra-version",
|
||||
],
|
||||
[
|
||||
"missing analyzeHeadless",
|
||||
inspection({ installDir: INSTALL }, { executable: () => false }),
|
||||
"ghidra-headless",
|
||||
],
|
||||
[
|
||||
"wrong Java",
|
||||
inspection(
|
||||
{ installDir: INSTALL },
|
||||
{
|
||||
probeJava: () => ({
|
||||
version: "17.0.12",
|
||||
major: 17,
|
||||
home: "/usr/lib/jvm/jdk-17",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
},
|
||||
),
|
||||
"ghidra-java",
|
||||
],
|
||||
[
|
||||
"unsupported architecture",
|
||||
inspection({ installDir: INSTALL, architecture: "arm64" }),
|
||||
"ghidra-architecture",
|
||||
],
|
||||
] as const)("distinguishes %s", async (_label, ghidra, checkName) => {
|
||||
const result = await runDoctor(undefined, doctorHost(ghidra, true));
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks.find(({ name }) => name === checkName)).toMatchObject({
|
||||
ok: false,
|
||||
remediation: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("treats unconfigured Ghidra as optional when Hopper is healthy", async () => {
|
||||
const result = await runDoctor(undefined, doctorHost(inspection({}), true));
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_analysis_engine",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
GHIDRA_FUNCTION_OPERATIONS,
|
||||
isGhidraFunctionOperation,
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
type GhidraFunctionOperation,
|
||||
} from "./GhidraFunctionValues.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraNativeApiBoundary,
|
||||
ghidraReferenceEdge,
|
||||
} from "../domain/hopperValues.fixture.js";
|
||||
|
||||
describe("Ghidra function-analysis boundary values", () => {
|
||||
it("defaults bounded inputs and rejects undeclared or implicit addresses", () => {
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, procedure: "main" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_references", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
direction: "outgoing",
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
max_instructions: 500,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("analyze_function", { procedure: "main" }),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
procedure: "main",
|
||||
include_assembly: false,
|
||||
limit: 100,
|
||||
max_pseudocode_chars: 20_000,
|
||||
max_instructions: 500,
|
||||
pseudocode_offset: 0,
|
||||
assembly_offset: 0,
|
||||
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("read_function_instructions", {
|
||||
procedure: "main",
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
},
|
||||
});
|
||||
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", {
|
||||
procedure: "main",
|
||||
extra: true,
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(9);
|
||||
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("read_function_instructions")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
|
||||
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra function-analysis result values", () => {
|
||||
it("parses provider-classified function facts and reference kinds", () => {
|
||||
expect(
|
||||
parseGhidraFunctionResult("read_function_instructions", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraFunctionResult("read_function_instructions", {
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
address: "0X401000",
|
||||
},
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_info", {
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [
|
||||
{
|
||||
description: "int local @ Stack[-0x4]:4",
|
||||
provenance: "ghidra-function-database",
|
||||
},
|
||||
],
|
||||
classification: ghidraFunctionClassification(),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_references", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
data: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionResult("analyze_function", ghidraFunctionDossier()),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
native_api: {
|
||||
available: true,
|
||||
provenance: "ghidra-high-function",
|
||||
return_type: {
|
||||
data_type: "int",
|
||||
confidence: "medium",
|
||||
},
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [{ address: "0x403000" }],
|
||||
mappings: [
|
||||
{
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
pseudocode: {
|
||||
classification: "decompiler-generated-non-source",
|
||||
compilable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraFunctionResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const malformedOutputs = (): Array<
|
||||
[string, GhidraFunctionOperation, JsonValue]
|
||||
> => {
|
||||
const dossier = ghidraFunctionDossier();
|
||||
if (typeof dossier !== "object" || dossier === null || Array.isArray(dossier))
|
||||
throw new TypeError("Ghidra dossier fixture is invalid");
|
||||
const edge = ghidraReferenceEdge();
|
||||
const nativeApi = ghidraNativeApiBoundary();
|
||||
const jumpTable = nativeApi.jump_tables[0];
|
||||
const mapping = jumpTable?.mappings[0];
|
||||
if (jumpTable === undefined || mapping === undefined)
|
||||
throw new TypeError("Ghidra native API fixture is invalid");
|
||||
return [
|
||||
["non-canonical address", "procedure_callers", ["401000"]],
|
||||
[
|
||||
"missing classification",
|
||||
"procedure_info",
|
||||
{
|
||||
name: "main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 1,
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"unavailable Ghidra reference kind",
|
||||
"procedure_references",
|
||||
{
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([
|
||||
{ ...edge, kind: { available: false, reason: "unknown" } },
|
||||
]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing native API boundary",
|
||||
"analyze_function",
|
||||
Object.fromEntries(
|
||||
Object.entries(dossier).filter(([key]) => key !== "native_api"),
|
||||
),
|
||||
],
|
||||
[
|
||||
"non-canonical native API target",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
native_api: {
|
||||
...nativeApi,
|
||||
jump_tables: [
|
||||
{
|
||||
...jumpTable,
|
||||
mappings: [
|
||||
{
|
||||
...mapping,
|
||||
target_address: "401020",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"Hopper local provenance",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: null,
|
||||
locals: [
|
||||
{
|
||||
description: "opaque",
|
||||
provenance: "hopper-public-python-api",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"inconsistent dossier bound",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
instruction_scan: { scanned: -1, truncated: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing uncertainty limitations",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
];
|
||||
};
|
||||
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ghidraJavaEnvironment,
|
||||
inspectGhidraInstallation,
|
||||
SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
SUPPORTED_GHIDRA_VERSION,
|
||||
type GhidraInstallationHost,
|
||||
type GhidraJavaObservation,
|
||||
} from "./GhidraInstallation.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra";
|
||||
const PROPERTIES = `${INSTALL}/Ghidra/application.properties`;
|
||||
const HEADLESS = `${INSTALL}/support/analyzeHeadless`;
|
||||
const WINDOWS_INSTALL = "C:\\tools\\ghidra_12.1.2_PUBLIC";
|
||||
const WINDOWS_PROPERTIES = `${WINDOWS_INSTALL}\\Ghidra\\application.properties`;
|
||||
const WINDOWS_HEADLESS = `${WINDOWS_INSTALL}\\support\\analyzeHeadless.bat`;
|
||||
const JAVA: GhidraJavaObservation = {
|
||||
version: "21.0.11",
|
||||
major: SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
};
|
||||
|
||||
const host = (
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationHost => ({
|
||||
readText: (path) =>
|
||||
path === PROPERTIES
|
||||
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
|
||||
: undefined,
|
||||
executable: (path) => path === HEADLESS,
|
||||
probeJava: () => JAVA,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("Ghidra installation inspection", () => {
|
||||
it("clears inherited JVM option injection before probing Java", () => {
|
||||
expect(
|
||||
ghidraJavaEnvironment(
|
||||
"/opt/jdk-21",
|
||||
{
|
||||
PATH: "/usr/bin",
|
||||
_JAVA_OPTIONS: "-Xmx99G",
|
||||
JAVA_TOOL_OPTIONS: "-javaagent:/tmp/agent.jar",
|
||||
JDK_JAVA_OPTIONS: "-XX:MaxRAMPercentage=99",
|
||||
GHIDRA_JAVA_OPTIONS: "-Duser.home=/tmp/unapproved",
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toMatchObject({
|
||||
PATH: "/opt/jdk-21/bin:/usr/bin",
|
||||
JAVA_HOME: "/opt/jdk-21",
|
||||
_JAVA_OPTIONS: "",
|
||||
JAVA_TOOL_OPTIONS: "",
|
||||
JDK_JAVA_OPTIONS: "",
|
||||
GHIDRA_JAVA_OPTIONS: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts only the exact Linux x64 Ghidra and JDK commitment", () => {
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
host(),
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "available",
|
||||
providerVersion: SUPPORTED_GHIDRA_VERSION,
|
||||
analyzeHeadlessPath: HEADLESS,
|
||||
javaVersion: "21.0.11",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the exact Windows x64 batch launcher and JDK commitment", () => {
|
||||
const windowsHost: GhidraInstallationHost = {
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
readText: (path) =>
|
||||
path === WINDOWS_PROPERTIES
|
||||
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
|
||||
: undefined,
|
||||
executable: (path) => path === WINDOWS_HEADLESS,
|
||||
probeJava: (command, environment) => {
|
||||
expect(command).toBe("C:\\Java\\jdk-21\\bin\\java.exe");
|
||||
expect(environment.PATH).toMatch(/^C:\\Java\\jdk-21\\bin;/u);
|
||||
return {
|
||||
...JAVA,
|
||||
home: "C:\\Java\\jdk-21",
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{
|
||||
installDir: WINDOWS_INSTALL,
|
||||
javaHome: "C:\\Java\\jdk-21",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
},
|
||||
windowsHost,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "available",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
analyzeHeadlessPath: WINDOWS_HEADLESS,
|
||||
javaCommand: "C:\\Java\\jdk-21\\bin\\java.exe",
|
||||
providerVersion: SUPPORTED_GHIDRA_VERSION,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra installation rejection diagnostics", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "missing configuration",
|
||||
options: { platform: "linux" as const, architecture: "x64" as const },
|
||||
override: {},
|
||||
failed: "configuration",
|
||||
code: "not_configured",
|
||||
},
|
||||
{
|
||||
name: "unsupported platform",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "darwin" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: {},
|
||||
failed: "platform",
|
||||
code: "unsupported_host",
|
||||
},
|
||||
{
|
||||
name: "unsupported architecture",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "arm64" as const,
|
||||
},
|
||||
override: {},
|
||||
failed: "architecture",
|
||||
code: "unsupported_host",
|
||||
},
|
||||
{
|
||||
name: "bad installation root",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { readText: () => undefined },
|
||||
failed: "installation",
|
||||
code: "executable_missing",
|
||||
},
|
||||
{
|
||||
name: "wrong Ghidra version",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { readText: () => "application.version=11.4\n" },
|
||||
failed: "version",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
{
|
||||
name: "missing analyzeHeadless",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { executable: () => false },
|
||||
failed: "headless",
|
||||
code: "executable_missing",
|
||||
},
|
||||
{
|
||||
name: "missing Java",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => undefined },
|
||||
failed: "java",
|
||||
code: "runtime_missing",
|
||||
},
|
||||
{
|
||||
name: "wrong Java",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => ({ ...JAVA, major: 17, version: "17" }) },
|
||||
failed: "java",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
{
|
||||
name: "JRE instead of JDK",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => ({ ...JAVA, runtime: "jre" as const }) },
|
||||
failed: "java",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
])("distinguishes $name", ({ options, override, failed, code }) => {
|
||||
const result = inspectGhidraInstallation(options, host(override));
|
||||
expect(result.status).toBe("unavailable");
|
||||
expect(
|
||||
result.checks.find(({ status }) => status === "failed"),
|
||||
).toMatchObject({
|
||||
name: failed,
|
||||
code,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
GHIDRA_INVENTORY_OPERATIONS,
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
type GhidraInventoryOperation,
|
||||
} from "./GhidraInventoryValues.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
describe("Ghidra inventory boundary values", () => {
|
||||
it("defaults bounded provider inputs without accepting undeclared fields", () => {
|
||||
expect(parseGhidraInventoryInput("list_procedures", {})).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, offset: 0, limit: 100 },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("search_strings", { pattern: "needle" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("list_documents", { extra: true }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(parseGhidraInventoryInput("address_name", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("procedure_address", {
|
||||
procedure: "x".repeat(4097),
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_INVENTORY_OPERATIONS).toHaveLength(10);
|
||||
expect(isGhidraInventoryOperation("list_names")).toBe(true);
|
||||
expect(isGhidraInventoryOperation("goto_address")).toBe(false);
|
||||
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses primary, dynamic, and external symbol facts", () => {
|
||||
const items = [
|
||||
{
|
||||
address: "EXTERNAL:0x1",
|
||||
value: "libc::puts",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: true,
|
||||
type: "function",
|
||||
source: "imported",
|
||||
},
|
||||
},
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "LAB_00401000",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: true,
|
||||
external: false,
|
||||
type: "label",
|
||||
source: "default",
|
||||
},
|
||||
},
|
||||
] satisfies readonly JsonValue[];
|
||||
expect(parseGhidraInventoryResult("list_names", page(items))).toEqual({
|
||||
ok: true,
|
||||
value: page(items),
|
||||
});
|
||||
});
|
||||
|
||||
it("parses thunk, string-layout, and memory-permission observations", () => {
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "0x401020",
|
||||
value: "puts",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: true,
|
||||
thunk_target: "EXTERNAL:0x1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_strings",
|
||||
page([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "fixture",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "missing",
|
||||
byte_length: 7,
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult("list_segments", [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x402000",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraInventoryResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function malformedOutputs(): Array<
|
||||
[string, GhidraInventoryOperation, JsonValue]
|
||||
> {
|
||||
return [
|
||||
[
|
||||
"non-canonical address",
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "00401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
[
|
||||
"missing external metadata",
|
||||
"list_names",
|
||||
page([{ address: "0x401000", value: "main", value_truncated: false }]),
|
||||
],
|
||||
[
|
||||
"contradictory continuation",
|
||||
"search_strings",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: false,
|
||||
next_offset: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
"non-advancing continuation",
|
||||
"list_procedures",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: true,
|
||||
next_offset: 0,
|
||||
},
|
||||
],
|
||||
[
|
||||
"items beyond exact total",
|
||||
"list_procedures",
|
||||
{ ...page([procedureItem()]), total: 0 },
|
||||
],
|
||||
["provider limit", "search_procedures", { ...page([]), limit: 101 }],
|
||||
["multiple programs", "list_documents", ["first", "second"]],
|
||||
];
|
||||
}
|
||||
|
||||
function procedureItem(): JsonValue {
|
||||
return {
|
||||
address: "0x401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function page(items: readonly JsonValue[]) {
|
||||
return {
|
||||
items: [...items],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
} from "./GhidraProvider.js";
|
||||
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
const installationHost = (): GhidraInstallationHost => ({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
});
|
||||
|
||||
const provider = (
|
||||
host = installationHost(),
|
||||
clientFactory?: GhidraProviderClientFactory,
|
||||
): GhidraProvider => {
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
|
||||
if (!config.ok) throw config.error;
|
||||
return new GhidraProvider(config.value, silentLogger, host, clientFactory);
|
||||
};
|
||||
|
||||
describe("Ghidra provider", () => {
|
||||
it("discovers the exact installation once without launching Ghidra", () => {
|
||||
let probeCount = 0;
|
||||
const host: GhidraInstallationHost = {
|
||||
...installationHost(),
|
||||
probeJava: () => {
|
||||
probeCount += 1;
|
||||
return {
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
};
|
||||
},
|
||||
};
|
||||
const ghidra = provider(host);
|
||||
|
||||
expect(ghidra.identity()).toEqual(GHIDRA_PROVIDER_IDENTITY);
|
||||
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(19);
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
pagination: "offset",
|
||||
effects: expect.objectContaining({
|
||||
mutatesArtifact: false,
|
||||
mayShowUi: false,
|
||||
mayWriteFilesystem: true,
|
||||
}),
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
operation: "analyze_function",
|
||||
pagination: "offset",
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 35_000,
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"unresolved targetless flows remain unknown",
|
||||
),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "available",
|
||||
diagnostics: {
|
||||
install_dir: INSTALL,
|
||||
provider_version: "12.1.2",
|
||||
java_version: "21.0.11",
|
||||
},
|
||||
});
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({ status: "available" });
|
||||
expect(probeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("separates target kind, format, and concrete architecture", () => {
|
||||
const ghidra = provider();
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
||||
).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
path: "/tmp/fixture.asar",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
path: "/tmp/fixture.js",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "artifact",
|
||||
format: "javascript",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra platform support", () => {
|
||||
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
|
||||
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
||||
const nativeApplication = peTarget("x86_64");
|
||||
|
||||
expect(ghidra.inspectTargetSupport(nativeApplication)).toMatchObject({
|
||||
status: "supported",
|
||||
diagnostics: {
|
||||
host_platform: "win32",
|
||||
executable_role: "application",
|
||||
managed: false,
|
||||
},
|
||||
});
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "unavailable",
|
||||
code: "unsupported_host",
|
||||
reason: expect.stringContaining("native authority is unavailable"),
|
||||
diagnostics: {
|
||||
windows_security: {
|
||||
job_object_process_ownership: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
private_runtime_dacl: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
reparse_safe_path_admission: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("bounded taskkill cleanup"),
|
||||
expect.stringContaining("private DACL enforcement"),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
...nativeApplication,
|
||||
executableRole: "shared-library",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_role_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({ ...nativeApplication, managed: true }),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "managed_target_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "architecture_unsupported",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra client projection", () => {
|
||||
it("commits exact provider, isolation, and resource semantics", async () => {
|
||||
const toolCalls: Array<{
|
||||
readonly operation: string;
|
||||
readonly input: unknown;
|
||||
readonly options: unknown;
|
||||
}> = [];
|
||||
let startCount = 0;
|
||||
const factoryOptions: unknown[] = [];
|
||||
const callTool: ReturnType<GhidraProviderClientFactory>["callTool"] = (
|
||||
operation,
|
||||
input,
|
||||
options,
|
||||
) => {
|
||||
toolCalls.push({ operation, input, options });
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
);
|
||||
};
|
||||
const clientFactory: GhidraProviderClientFactory = (options) => {
|
||||
factoryOptions.push(options);
|
||||
return {
|
||||
start: () => {
|
||||
startCount += 1;
|
||||
return Promise.resolve(ok(sessionInfo()));
|
||||
},
|
||||
callTool,
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
};
|
||||
const ghidra = provider(installationHost(), clientFactory);
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
|
||||
expect(resolved.ok).toBe(true);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
expect(resolved.value.profile).toMatchObject({
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
|
||||
provider_profile_schema_version: 1,
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
analyzer_preset: "ghidra-default",
|
||||
analysis_timeout_seconds: 300,
|
||||
max_cpu: 2,
|
||||
max_heap: "2G",
|
||||
},
|
||||
});
|
||||
expect(resolved.value.compatibility).toEqual({
|
||||
languageId: "auto",
|
||||
compilerSpecId: "auto",
|
||||
});
|
||||
|
||||
const result = await ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile, {
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
})
|
||||
.execute("list_procedures", {});
|
||||
expect(factoryOptions).toEqual([
|
||||
expect.objectContaining({
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
}),
|
||||
]);
|
||||
expect(toolCalls).toEqual([
|
||||
{
|
||||
operation: "list_procedures",
|
||||
input: { document: null, offset: 0, limit: 100 },
|
||||
options: {},
|
||||
},
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
provider: {
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: "12.1.2",
|
||||
},
|
||||
analysisProfile: resolved.value.profile,
|
||||
result: {
|
||||
items: [{ address: "0x1000", value: "fixture_main" }],
|
||||
total: 1,
|
||||
},
|
||||
rawResult: {
|
||||
items: [{ procedure: { external: false, thunk: false } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(startCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra result projection", () => {
|
||||
it("rejects malformed inventory output before Evidence creation", async () => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () => Promise.resolve(ok({ items: "not-a-page" })),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid_request", "AnalysisInputError"],
|
||||
["not_found", "AnalysisInputError"],
|
||||
["ambiguous", "AnalysisInputError"],
|
||||
["method_unavailable", "AnalysisCapabilityUnavailableError"],
|
||||
] as const)(
|
||||
"projects remote %s without losing its typed meaning",
|
||||
async (code, tag) => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"Fixture remote failure",
|
||||
{ remote_code: code },
|
||||
{ remoteCode: code },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(
|
||||
executableTarget("elf", "x86_64"),
|
||||
resolved.value.profile,
|
||||
)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({ ok: false, error: { _tag: tag } });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["decompile_timeout", "AnalysisTimeoutError", 30_000],
|
||||
["decompile_cancelled", "AnalysisCancelledError", undefined],
|
||||
] as const)(
|
||||
"projects remote %s as a provider-neutral interruption",
|
||||
async (code, tag, timeoutMs) => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"Fixture decompiler interruption",
|
||||
{ remote_code: code },
|
||||
{ remoteCode: code },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
const result = await ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("procedure_pseudo_code", { procedure: "main" });
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: tag,
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("returns cancellation before profile work", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
provider().resolveAnalysisProfile(executableTarget("elf", "x86_64"), {
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const sessionInfo = () => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 6 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: "a".repeat(64),
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
read_only: true as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
sha256: "a".repeat(64),
|
||||
},
|
||||
});
|
||||
|
||||
const executableTarget = (
|
||||
format: "mach-o" | "elf" | "pe",
|
||||
architecture: NonNullable<BinaryTarget["architecture"]>,
|
||||
): BinaryTarget =>
|
||||
format === "pe"
|
||||
? peTarget(architecture)
|
||||
: {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
|
||||
const peTarget = (
|
||||
architecture: NonNullable<BinaryTarget["architecture"]>,
|
||||
): Extract<BinaryTarget, { format: "pe" }> => ({
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
import { HopperProvider } from "./HopperProvider.js";
|
||||
|
||||
describe("Hopper provider discovery", () => {
|
||||
it("reports bounded launcher availability without starting Hopper", () => {
|
||||
const available = provider(process.execPath).inspectAvailability();
|
||||
expect(available).toEqual({
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {
|
||||
launcher_path: process.execPath,
|
||||
platform: process.platform,
|
||||
},
|
||||
});
|
||||
|
||||
const missingPath = "/missing/rea-hopper-launcher";
|
||||
expect(provider(missingPath).inspectAvailability()).toEqual({
|
||||
status: "unavailable",
|
||||
code: "executable_missing",
|
||||
reason: `Hopper launcher is missing or not executable: ${missingPath}`,
|
||||
diagnostics: {
|
||||
launcher_path: missingPath,
|
||||
platform: process.platform,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("separates target kind, format, and architecture support", () => {
|
||||
const hopper = provider(process.execPath);
|
||||
expect(hopper.inspectTargetSupport(databaseTarget())).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
hopper.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({ status: "supported" });
|
||||
expect(hopper.inspectTargetSupport(artifactTarget())).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
diagnostics: { target_kind: "archive", target_format: "asar" },
|
||||
});
|
||||
});
|
||||
|
||||
it("advertises the exact bounded byte-read limit", () => {
|
||||
const capabilities = provider(process.execPath).capabilities();
|
||||
expect(
|
||||
capabilities.find(({ operation }) => operation === "read_bytes"),
|
||||
).toMatchObject({
|
||||
available: true,
|
||||
pagination: "none",
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: 4_096,
|
||||
timeoutMs: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
capabilities.find(
|
||||
({ operation }) => operation === "address_to_file_offset",
|
||||
),
|
||||
).toMatchObject({ available: true, pagination: "none" });
|
||||
});
|
||||
});
|
||||
|
||||
const provider = (launcherPath: string): HopperProvider => {
|
||||
const config = parseConfig({ HOPPER_LAUNCHER_PATH: launcherPath });
|
||||
if (!config.ok) throw config.error;
|
||||
return new HopperProvider(config.value, silentLogger);
|
||||
};
|
||||
|
||||
const databaseTarget = (): BinaryTarget => ({
|
||||
path: "/tmp/fixture.hop",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
|
||||
const executableTarget = (
|
||||
format: "mach-o" | "elf" | "pe",
|
||||
architecture: "x86" | "x86_64" | "arm" | "arm64",
|
||||
): BinaryTarget =>
|
||||
format === "pe"
|
||||
? {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
}
|
||||
: {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
|
||||
const artifactTarget = (): BinaryTarget => ({
|
||||
path: "/tmp/app.asar",
|
||||
sha256: "c".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
verifyNoTokenOwnedProcesses,
|
||||
type ProcessOwnershipHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("signals token-owned groups that were reparented outside the launcher tree", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-helper",
|
||||
},
|
||||
{
|
||||
pid: 901,
|
||||
parentPid: 900,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-worker",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(
|
||||
{ ...ownership, sweepTokenOwnedProcesses: true },
|
||||
adapter,
|
||||
),
|
||||
).resolves.toEqual({ cleaned: true, signaled: true });
|
||||
expect(signalGroup.mock.calls.map(([groupId]) => groupId)).toEqual([
|
||||
100, 900,
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails closed when a token-owned process remains after cleanup", async () => {
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-helper",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
|
||||
await expect(
|
||||
verifyNoTokenOwnedProcesses("run-token", adapter),
|
||||
).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason: "token-owned process remained after cleanup",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("fails before signaling when any descendant-group member is unowned", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
{
|
||||
pid: 104,
|
||||
parentPid: 101,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-helper",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 104 ? "other-run" : "run-token",
|
||||
}),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 104, reason: "run-token-mismatch" }],
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails before signaling when a descendant group leader is not rooted", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 105,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "descendant",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 999,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "unrelated-group-leader",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason:
|
||||
"descendant process-group leader identity could not be verified",
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("records sorted launcher and descendant lineage after token checks", async () => {
|
||||
const { adapter } = host({
|
||||
102: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 102, parentPid: 100, processGroupId: 100 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("walks the PPID tree across process-group boundaries", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 103 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 103,
|
||||
parentPid: 999,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "unrelated-same-group",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
parentPid: 101,
|
||||
processGroupId: 102,
|
||||
state: "S",
|
||||
command: "grandchild-session",
|
||||
},
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-group",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
parseProcessEnvironment,
|
||||
selectCapturedProcessGroupIds,
|
||||
type ProcessOwnershipHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
import { matchesOwnedProcessCommand } from "./ProcessCommandIdentity.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("excludes sampled groups whose leader was outside the captured tree", () => {
|
||||
expect(
|
||||
selectCapturedProcessGroupIds(100, [
|
||||
{ pid: 100, process_group_id: 42 },
|
||||
{ pid: 100, process_group_id: 100 },
|
||||
{ pid: 101, process_group_id: 42 },
|
||||
{ pid: 102, process_group_id: 102 },
|
||||
{ pid: 103, process_group_id: 102 },
|
||||
]),
|
||||
).toEqual([100, 102]);
|
||||
});
|
||||
it("drops nameless Linux environment entries", () => {
|
||||
expect(
|
||||
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
|
||||
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
|
||||
});
|
||||
it("matches macOS executable names after process-table normalization", () => {
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "darwin"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/python/bin/python3",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"linux",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "linux"),
|
||||
).toBe(false);
|
||||
});
|
||||
it("signals only a group whose every member carries the run token", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("validates and signals rooted descendant groups once, root first", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100 },
|
||||
{ pid: 110, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
{ pid: 103, parentPid: 102, processGroupId: 102 },
|
||||
].map((process) => ({
|
||||
...process,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
}));
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
[102, "SIGKILL"],
|
||||
]);
|
||||
});
|
||||
it("leaves an unrelated Hopper process group outside the rooted tree untouched", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "rea-hopper" },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101, command: "owned-child" },
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command:
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/Hopper Disassembler",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
]);
|
||||
expect(environment.mock.calls.some(([pid]) => pid === 900)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("fails closed when a descendant in another process group lacks the token", async () => {
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 100 ? "run-token" : "other-run",
|
||||
}),
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("does not publish lineage when any member fails ownership checks", async () => {
|
||||
const { adapter } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "other-run" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "different-run" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 101, reason: "run-token-mismatch" }],
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("checks every member and aggregates ownership read failures", async () => {
|
||||
const environment = vi.fn((pid: number) => {
|
||||
if (pid === 100)
|
||||
return Promise.reject(new Error("transient procfs read"));
|
||||
return Promise.resolve(
|
||||
pid === 101
|
||||
? { REA_PROCESS_RUN_ID: "different-run" }
|
||||
: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
);
|
||||
});
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
[100, 101, 102].map((pid) => ({
|
||||
pid,
|
||||
parentPid: pid === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [
|
||||
{ pid: 100, reason: "environment-unreadable" },
|
||||
{ pid: 101, reason: "run-token-mismatch" },
|
||||
],
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts a member that exits during ownership revalidation", async () => {
|
||||
const liveLauncher = {
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
};
|
||||
const listProcesses = vi
|
||||
.fn<ProcessOwnershipHost["listProcesses"]>()
|
||||
.mockResolvedValueOnce([liveLauncher])
|
||||
.mockResolvedValue([]);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses,
|
||||
environment: () =>
|
||||
Promise.reject(new Error("process exited before environment read")),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessGroup,
|
||||
type ProcessOwnershipHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("ignores exited zombie members during live ownership checks", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve(pid === 101 ? {} : { REA_PROCESS_RUN_ID: "run-token" }),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "Z",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(environment.mock.calls).toEqual([[100], [100]]);
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("observes a zombie-only group as settled", async () => {
|
||||
const environment = vi.fn(() => Promise.resolve({}));
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "Z+",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
expect(await observeOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
state: "empty",
|
||||
});
|
||||
expect(environment).not.toHaveBeenCalled();
|
||||
});
|
||||
it("is idempotent when the owned group has already exited", async () => {
|
||||
const { adapter } = host({});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("fails closed when the launcher command identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
expectedCommand: "/owned/hopper",
|
||||
expectedParentPid: 1,
|
||||
},
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"owned launcher command identity did not match (observed=fixture; expected=/owned/hopper)",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails closed when the launcher parent identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{ ...ownership, expectedCommand: "fixture", expectedParentPid: 999 },
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason: "owned launcher parent identity did not match",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
cleanupWindowsProcessTree,
|
||||
type WindowsProcessTreeHost,
|
||||
} from "./ProcessOwnership.js";
|
||||
describe("Windows P0 process-tree cleanup", () => {
|
||||
it("reports whether taskkill signaled or found an exited tree", async () => {
|
||||
const terminated: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("terminated"),
|
||||
};
|
||||
const missing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("missing"),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(42, terminated)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, missing)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("keeps invalid identity and termination failures explicit", async () => {
|
||||
const failing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.reject(new Error("taskkill failed")),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(0, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason: "Windows process-tree PID is invalid",
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseReplayWorkerResponse } from "./ReplayWorkerProtocol.js";
|
||||
|
||||
const digest = "1".repeat(64);
|
||||
const cases = [{ case_id: "case-1", sha256: digest }];
|
||||
const outcome = {
|
||||
case_id: "case-1",
|
||||
outcome: "return" as const,
|
||||
value: { parsed: true },
|
||||
input_sha256: digest,
|
||||
output_sha256: null,
|
||||
truncated: false as const,
|
||||
};
|
||||
|
||||
describe("replay worker protocol", () => {
|
||||
it("accepts only the exact committed case sequence", () => {
|
||||
expect(
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [outcome] },
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toMatchObject({ left: [outcome] });
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [{ ...outcome, case_id: "forged" }] },
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow("case identity changed");
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, input_sha256: "2".repeat(64) }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow("case identity changed");
|
||||
});
|
||||
|
||||
it("requires the exact differential shape and strict outcomes", () => {
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [outcome] },
|
||||
cases,
|
||||
"differential",
|
||||
),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, unexpected: true }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, outcome: "exception", value: undefined }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDerivedOperation } from "./runDerivedOperation.js";
|
||||
|
||||
const context = (
|
||||
controller: AbortController,
|
||||
notifications: unknown[] = [],
|
||||
) => ({
|
||||
mcpReq: {
|
||||
signal: controller.signal,
|
||||
_meta: { progressToken: "derived-test" },
|
||||
notify: (notification: unknown) => {
|
||||
notifications.push(notification);
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe("derived MCP operation boundary", () => {
|
||||
it("cancels before computation and never evaluates the operation", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
let computed = false;
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
computed = true;
|
||||
return "impossible";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(computed).toBe(false);
|
||||
});
|
||||
|
||||
it("lets cancellation win immediately before result publication", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
controller.abort();
|
||||
return "must-not-publish";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("emits bounded monotonic progress with one terminal state", async () => {
|
||||
const controller = new AbortController();
|
||||
const notifications: Array<{
|
||||
params?: { progress?: number; total?: number };
|
||||
}> = [];
|
||||
const result = await runDerivedOperation(
|
||||
context(controller, notifications),
|
||||
"compare",
|
||||
() => "complete",
|
||||
);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: "complete" });
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
|
||||
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("projects synchronous computation failures into a typed result", async () => {
|
||||
const result = await runDerivedOperation(
|
||||
context(new AbortController()),
|
||||
"compare_artifacts",
|
||||
() => {
|
||||
throw new TypeError("malformed comparison evidence");
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
operation: "compare_artifacts",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user