feat(javascript): recover readable modules with Wakaru (#848)

* feat(javascript): recover readable modules with Wakaru

Integrate pinned upstream source behind a typed optional recovery port,
preserve source identity and producer provenance, and publish verified
artifacts for existing JavaScript analysis through CLI and MCP.

Add focused real-tool CI with genuine bundler fixtures and bounded
resource, cancellation, cleanup, schema and packaged-artifact checks.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(javascript): align recovery catalog and browser verification

Share canonical Wakaru provider identity, describe CLI mode options, and
format the new workflow test. Disconnect the real page transport after
its observation readiness progress instead of a fixed delay.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* refactor(javascript): consume the investigation evidence writer

Verify that the SDK recovery handler records complete Evidence through the newly shared investigation owner.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)

* chore(test): account for isolated recovery fixture compilers

* fix(javascript): validate recovery paths before acquiring the engine

Return field-specific invalid_format diagnostics for relative paths and verify compiled CLI/MCP parity even when the optional engine is unavailable.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
N0zoM1z0
2026-10-07 12:46:13 +08:00
committed by GitHub
parent 4a6c17ce83
commit 166dcd21d0
60 changed files with 2840 additions and 25 deletions
@@ -5,6 +5,7 @@ import { expect, onTestFinished } from "vitest";
import { createAndroidAnalysisProvider } from "../../src/composition/android.js";
import { createFirmwareAnalysisProvider } from "../../src/composition/firmware.js";
import { createJavaScriptRecoveryProvider } from "../../src/composition/javascriptRecovery.js";
import { createServer } from "../../src/server/createServer.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
import { writeOrderedZip } from "../fixtures/artifactEntryOrder.js";
@@ -18,6 +19,7 @@ const connect = async (environment: NodeJS.ProcessEnv) => {
const server = createServer(session, session, {
androidAnalysis: createAndroidAnalysisProvider(environment),
firmwareAnalysis: createFirmwareAnalysisProvider(environment),
javascriptRecovery: createJavaScriptRecoveryProvider(environment),
});
const client = new Client({ name: "composition-parity", version: "1" });
onTestFinished(async () => {
@@ -86,3 +88,81 @@ cliTest.skipIf(process.platform !== "linux")(
);
},
);
cliTest(
"preserves optional JavaScript recovery configuration through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-recovery-composition-");
const path = join(root, "bundle.js");
await writeFile(path, "globalThis.fixture = 1;");
const environment = {
REA_LOG_LEVEL: "silent",
REA_WAKARU_COMMAND: "relative-unavailable-tool",
};
const cliResult = await cli.run({
arguments: [
"recover-javascript-sources",
path,
join(root, "output"),
"--json",
],
environment,
timeoutMs: 10000,
});
expect(cliResult.exitCode).toBe(1);
expect(cliResult.json).toMatchObject({ code: "capability_unavailable" });
const client = await connect(environment);
const response = await client.callTool({
name: "recover_javascript_sources",
arguments: { path, output_directory: join(root, "output") },
});
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: cliResult.json });
expect(JSON.stringify(response.structuredContent)).toContain(
"REA_WAKARU_COMMAND",
);
},
);
cliTest(
"returns recovery path diagnostics before missing-engine errors in CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-recovery-path-parity-");
const environment = {
REA_LOG_LEVEL: "silent",
REA_WAKARU_COMMAND: "relative-unavailable-tool",
};
const client = await connect(environment);
for (const field of ["path", "output_directory"] as const) {
const input = {
path: join(root, "bundle.js"),
output_directory: join(root, "output"),
[field]: "relative.js",
};
const result = await cli.run({
arguments: [
"recover-javascript-sources",
input.path,
input.output_directory,
"--json",
],
environment,
timeoutMs: 10_000,
});
const response = await client.callTool({
name: "recover_javascript_sources",
arguments: input,
});
expect(result.exitCode).toBe(1);
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: result.json });
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "recover_javascript_sources",
issues: [{ path: [field], reason: "invalid_format" }],
},
});
}
},
);
@@ -27,6 +27,7 @@ import {
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
} from "../../../src/firmware/FirmwareRelease.js";
import { WAKARU_PROVIDER_IDENTITY } from "../../../src/javascript/recovery/WakaruRelease.js";
import { JADX_PROVIDER_IDENTITY } from "../../../src/android/JadxRelease.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
@@ -102,6 +103,7 @@ describe("canonical product catalog", () => {
JADX_PROVIDER_IDENTITY,
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
WAKARU_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
IDA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
@@ -0,0 +1,213 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { javascriptRecoveryResultSchema } from "../../../src/domain/javascriptRecovery.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
assertRecoveryCleanup,
recoveryFixture,
} from "../../fixtures/javascript-recovery/provider.js";
describe.skipIf(process.platform !== "linux" || process.arch !== "x64")(
"Wakaru recovery boundary",
() => {
it("publishes exact bytes and mappings with source identity and no runtime-equivalence claim", async () => {
const fixture = await recoveryFixture();
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
if (!result.ok) throw result.error;
expect(parseEvidence(result.value)).toEqual(result.value);
const value = javascriptRecoveryResultSchema.parse(
result.value.normalized_result,
);
expect(value).toMatchObject({
status: "complete",
total: 1,
failed: 0,
runtime_equivalence: "unknown",
analysis_input: {
input_path: join(fixture.output, "modules"),
format: "directory",
},
});
expect(value.source.path).toBe(fixture.path);
expect(value.source.published_copy.sha256).toBe(value.source.sha256);
expect(value.modules[0]?.provenance.byte_ranges).toEqual([
{ start: 0, end: value.source.bytes },
]);
expect(value.engine.executed_source_revision).toBeNull();
expect(await readFile(value.source.published_copy.path, "utf8")).toBe(
"module.exports = 42;",
);
expect(result.value.confidence).toBe("derived");
await assertRecoveryCleanup(fixture.launches);
});
it.each([
"missing-provenance",
"malformed-report",
"duplicate",
"missing-file",
"escaping",
"extra-file",
"symlink",
"directory-symlink",
"bad-map",
"source-mismatch",
"overflow-range",
"extra-provenance",
"snapshot-change",
"source-change",
"engine-change",
"startup-error",
])(
"rejects %s, rolls back publication and cleans its processes",
async (mode) => {
const fixture = await recoveryFixture(mode);
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected boundary failure");
const error = projectAnalysisError(result.error);
expect(["execution_failure", "unreadable_output"]).toContain(
error.code,
);
expect(error.details).toBeDefined();
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
await assertRecoveryCleanup(fixture.launches);
},
);
it("rejects byte ranges splitting a UTF-8 code point", async () => {
const fixture = await recoveryFixture("utf8-range", "🎯");
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected invalid UTF-8 boundary");
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
"UTF-8 byte range",
);
await assertRecoveryCleanup(fixture.launches);
});
it("retains valid partial output and exact failure diagnostics", async () => {
const fixture = await recoveryFixture("partial");
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
if (!result.ok) throw result.error;
const value = javascriptRecoveryResultSchema.parse(
result.value.normalized_result,
);
expect(value).toMatchObject({
status: "partial",
failed: 1,
warnings: [{ is_error: true, kind: "parse_error" }],
});
expect(value.modules).toHaveLength(1);
await assertRecoveryCleanup(fixture.launches);
});
},
);
describe.skipIf(process.platform !== "linux" || process.arch !== "x64")(
"Wakaru recovery lifecycle",
() => {
it("rejects an existing output without modifying it or launching recovery", async () => {
const fixture = await recoveryFixture();
await mkdir(fixture.output);
await writeFile(join(fixture.output, "keep.txt"), "keep");
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected existing-output rejection");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["output_directory"] }] },
});
expect(await readFile(join(fixture.output, "keep.txt"), "utf8")).toBe(
"keep",
);
expect(fixture.launches).toHaveLength(0);
});
it("cancels an active recovery and verifies owned cleanup", async () => {
const fixture = await recoveryFixture("hang");
const controller = new AbortController();
const resultPromise = fixture.service.recover(
{ path: fixture.path, output_directory: fixture.output },
{ signal: controller.signal },
);
const deadline = Date.now() + 10000;
while (true) {
const run = fixture.launches[1];
if (
run?.cwd !== undefined &&
(await access(join(run.cwd, "recovery-started")).then(
() => true,
() => false,
))
)
break;
if (Date.now() > deadline)
throw new Error("fixture recovery did not start");
await new Promise((resolve) => setTimeout(resolve, 10));
}
controller.abort();
const result = await resultPromise;
if (result.ok) throw new Error("expected cancellation");
expect(projectAnalysisError(result.error).code).toBe("cancelled");
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
await assertRecoveryCleanup(fixture.launches);
});
it("reports cleanup failure and retains the workspace named by the error", async () => {
const fixture = await recoveryFixture("cleanup-failure");
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
if (result.ok) throw new Error("expected cleanup failure");
expect(projectAnalysisError(result.error).code).toBe(
"cleanup_incomplete",
);
const launch = fixture.launches[0];
if (launch?.cwd === undefined)
throw new Error("missing process ownership");
await expect(access(launch.cwd)).resolves.toBeUndefined();
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
});
it("rejects an incompatible engine with its observed version", async () => {
const fixture = await recoveryFixture("wrong-version");
const result = await fixture.service.recover({
path: fixture.path,
output_directory: fixture.output,
});
if (result.ok) throw new Error("expected version failure");
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
"wakaru 0.0.0",
);
expect(projectAnalysisError(result.error).code).toBe(
"capability_unavailable",
);
await assertRecoveryCleanup(fixture.launches);
});
},
);
@@ -0,0 +1,64 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
assertRecoveryCleanup,
recoveryFixture,
} from "../../fixtures/javascript-recovery/provider.js";
it.skipIf(process.platform !== "linux" || process.arch !== "x64")(
"advertises and executes recovery through the named SDK contract without a binary target",
async () => {
const fixture = await recoveryFixture();
const session = createTestBinarySession(() => {
throw new Error("no binary provider should start");
});
const server = createServer(session, session, {
javascriptRecovery: fixture.provider,
});
const client = new Client({ name: "recovery-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = await client.listTools();
const advertised = tools.tools.find(
(tool) => tool.name === "recover_javascript_sources",
);
if (advertised === undefined || advertised.outputSchema === undefined)
throw new Error("recovery tool must advertise both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const args = { path: fixture.path, output_directory: fixture.output };
expect(ajv.validate(inputSchema, args)).toBe(true);
const response = await client.callTool({
name: "recover_javascript_sources",
arguments: args,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract(
"recover_javascript_sources",
).outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
expect(parsed.evidence_id).toBe(evidence.evidence_id);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
await assertRecoveryCleanup(fixture.launches);
},
);
@@ -19,6 +19,13 @@ describe("incremental module import boundaries", () => {
["src/server/probe.ts", "../browser/CdpBrowserProvider.js", false],
["src/application/probe.ts", "../browser/V8InspectorProvider.js", false],
["src/composition/probe.ts", "../browser/CdpBrowserProvider.js", true],
[
"src/application/probe.ts",
"../javascript/recovery/WakaruProvider.js",
false,
],
["src/domain/probe.ts", "../javascript/recovery/WakaruReport.js", false],
["src/server/probe.ts", "../javascript/recovery/WakaruProvider.js", false],
["src/domain/probe.ts", "./result.js", true],
["src/contracts/probe.ts", "../domain/result.js", true],
["src/application/probe.ts", "../domain/result.js", true],
+98
View File
@@ -0,0 +1,98 @@
import { readFile, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
const args = process.argv.slice(2);
const mode = process.env.REA_RECOVERY_FIXTURE_MODE ?? "normal";
if (args.includes("--version")) {
console.log(mode === "wrong-version" ? "wakaru 0.0.0" : "wakaru 1.13.0");
} else {
const input = args[0];
const output = args[args.indexOf("-o") + 1];
const bytes = await readFile(input);
await writeFile(join(dirname(output), "recovery-started"), "started");
if (mode === "hang") await new Promise(() => setInterval(() => {}, 1000));
if (mode === "startup-error") {
console.error("fixture: unsupported producer dependency");
process.exit(2);
}
if (mode === "snapshot-change")
await writeFile(input, Buffer.alloc(bytes.length, 0x61));
if (mode === "engine-change")
await writeFile(
process.env.REA_RECOVERY_ENGINE_PATH,
"#!/bin/sh\nexit 1\n",
);
if (mode === "source-change")
await writeFile(process.env.REA_RECOVERY_ORIGINAL_PATH, "changed original");
const filename = mode === "escaping" ? "../escaped.js" : "module.js";
const modules = [{ filename, kind: "javascript", status: "decompiled" }];
if (mode === "duplicate") modules.push(modules[0]);
if (mode !== "missing-file" && mode !== "escaping") {
if (mode === "symlink") await symlink(input, join(output, filename));
else
await writeFile(join(output, filename), "export const recovered = 42;\n");
}
if (mode === "extra-file")
await writeFile(join(output, "extra.js"), "unreported");
if (mode === "directory-symlink")
await symlink(dirname(input), join(output, "nested"));
if (mode === "bad-map") await writeFile(join(output, "module.js.map"), "{}");
if (mode === "normal")
await writeFile(
join(output, "module.js.map"),
JSON.stringify({
version: 3,
file: "module.js",
sources: ["../inputs/bundle.js"],
names: [],
mappings: "AAAA",
}),
);
const ranges =
mode === "overflow-range"
? [[0, bytes.length + 1]]
: mode === "utf8-range"
? [[0, 2]]
: [[0, bytes.length]];
const provenance = {
format: "unknown",
strategy: "structural",
modules: {
[filename]: {
input: mode === "source-mismatch" ? "/different.js" : input,
ranges,
extraction: "structural",
},
},
};
if (mode === "extra-provenance")
provenance.modules["extra.js"] = provenance.modules[filename];
if (mode !== "missing-provenance")
await writeFile(
join(output, "provenance.json"),
JSON.stringify(provenance),
);
const report = {
detected_formats: [],
safety: "normal",
modules,
warnings:
mode === "partial"
? [
{
filename,
kind: "parse_error",
is_error: true,
message: "fixture transform failed; retained source",
},
]
: [],
total: modules.length,
failed: mode === "partial" ? 1 : 0,
elapsed_ms: 1,
};
console.log(
mode === "malformed-report" ? "{invalid}" : JSON.stringify(report),
);
if (mode === "partial") process.exitCode = 1;
}
+90
View File
@@ -0,0 +1,90 @@
import { access, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, onTestFinished } from "vitest";
import { JavaScriptRecoveryService } from "../../../src/application/JavaScriptRecoveryService.js";
import { createJavaScriptRecoveryProvider } from "../../../src/composition/javascriptRecovery.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../temporaryDirectory.js";
/** Inject a producer through the production factory and real owned processes. */
export const recoveryFixture = async (
mode = "normal",
source = "module.exports = 42;",
) => {
const root = await createTestTempDirectory("rea-recovery-fixture-");
const path = join(root, "selected.js");
await writeFile(path, source);
const command = join(root, "fixture-wakaru");
await writeFile(command, "#!/bin/sh\nexit 0\n", { mode: 0o700 });
const launches: {
cwd: string | undefined;
pid: number | undefined;
args: readonly string[];
}[] = [];
const provider = createJavaScriptRecoveryProvider(
{ ...process.env, REA_WAKARU_COMMAND: command },
async (options) => {
const start = options.arguments.indexOf("--") + 2;
const child = await spawnOwnedProviderProcess({
...options,
command: process.execPath,
expectedCommand: process.execPath,
arguments: [
fileURLToPath(new URL("./producer.mjs", import.meta.url)),
...options.arguments.slice(start),
],
env: {
...options.env,
REA_RECOVERY_FIXTURE_MODE: mode,
REA_RECOVERY_ORIGINAL_PATH: path,
REA_RECOVERY_ENGINE_PATH: command,
},
});
launches.push({
cwd: options.cwd,
pid: child.process.pid,
args: options.arguments,
});
if (mode === "cleanup-failure") {
onTestFinished(async () => {
if (options.cwd !== undefined)
await rm(options.cwd, { recursive: true, force: true });
});
return {
...child,
cleanup: async () => ({
cleaned: false,
reason: "injected cleanup refusal",
}),
};
}
return child;
},
);
return {
provider,
service: new JavaScriptRecoveryService(provider),
path,
output: join(root, "output"),
root,
launches,
};
};
/** Verify the owned process groups and workspaces are absent. */
export const assertRecoveryCleanup = async (
launches: Awaited<ReturnType<typeof recoveryFixture>>["launches"],
): Promise<void> => {
for (const launch of launches) {
const pid = launch.pid;
if (pid !== undefined)
expect(() => process.kill(-pid, 0)).toThrowError(
expect.objectContaining({ code: "ESRCH" }),
);
if (launch.cwd !== undefined)
await expect(access(launch.cwd)).rejects.toMatchObject({
code: "ENOENT",
});
}
};