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
@@ -333,3 +333,25 @@ describe("capability inventory: caller guidance", () => {
});
});
});
describe("optional JavaScript recovery availability", () => {
it("keeps optional recovery target-free and does not disable other static workflows", () => {
expect(entry("recover_javascript_sources", status())).toMatchObject({
available: false,
reason: "provider_missing",
remediation: expect.stringContaining("REA_WAKARU_COMMAND"),
});
expect(
entry("recover_javascript_sources", status(), {
processCaptureEnabled: true,
javascriptRecoveryEnabled: true,
}),
).toMatchObject({
available: true,
surface: "application",
});
expect(entry("analyze_javascript_application", status())).toMatchObject({
available: true,
});
});
});
+9
View File
@@ -36,6 +36,7 @@ export type AvailabilityPolicy = {
readonly firmwareInspectionEnabled?: boolean;
readonly firmwareExtractionEnabled?: boolean;
readonly androidAnalysisEnabled?: boolean;
readonly javascriptRecoveryEnabled?: boolean;
readonly browserObservationEnabled?: boolean;
readonly browserScenarioEnabled?: boolean;
readonly electronObservationEnabled?: boolean;
@@ -236,6 +237,14 @@ const workflowAvailabilityFor = ({
kind,
policy,
}: AvailabilityContext): Availability | null => {
if (name === "recover_javascript_sources")
return policy.javascriptRecoveryEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux x64, provide an absolute REA_WAKARU_COMMAND for Wakaru 1.13.0 and util-linux prlimit. No binary target is required.",
};
if (kind === "firmware-provider") {
const enabled =
name === "inspect_firmware_regions"
+15
View File
@@ -0,0 +1,15 @@
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { JavaScriptRecoveryInput } from "../domain/javascriptRecovery.js";
import type { Result } from "../domain/result.js";
import type {
AnalysisExecution,
ExecutionOptions,
} from "./AnalysisProvider.js";
/** Typed boundary for upstream source recovery without exposing its protocol. */
export interface JavaScriptRecoveryPort {
recover(
input: JavaScriptRecoveryInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,161 @@
import { describe, expect, it } from "vitest";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
import type {
JavaScriptRecoveryInput,
JavaScriptRecoveryResult,
} from "../domain/javascriptRecovery.js";
import { createAnalysisExecution } from "./AnalysisProvider.js";
import { JavaScriptRecoveryService } from "./JavaScriptRecoveryService.js";
const artifact = { path: "/tmp/bundle.js", sha256: "a".repeat(64), bytes: 20 };
const recoveryResult = (): JavaScriptRecoveryResult => ({
source: {
...artifact,
snapshot_path: "/tmp/work/inputs/bundle.js",
published_copy: artifact,
},
engine: {
id: "fixture-recovery",
version: "1",
executable: artifact,
audited_source_revision: "pinned",
executed_source_revision: null,
},
options: { extraction_mode: "structural", rewrite_level: "standard" },
status: "complete",
detected_formats: [],
reported_safety: "normal",
reported_strategy: "structural",
reported_format: "unknown",
total: 0,
failed: 0,
modules: [],
warnings: [],
report: artifact,
provenance: artifact,
manifest: artifact,
analysis_input: null,
runtime_equivalence: "unknown",
limitations: ["Not executed"],
});
const providerIdentity = {
id: "fixture-recovery",
name: "Fixture recovery",
version: "1",
};
const input = { path: artifact.path, output_directory: "/tmp/output" };
describe("JavaScript recovery workflow", () => {
it("passes normalized requests to a typed port and returns derived Evidence", async () => {
const received: JavaScriptRecoveryInput[] = [];
const service = new JavaScriptRecoveryService({
recover: async (request) => {
received.push(request);
return ok(
createAnalysisExecution(recoveryResult(), providerIdentity, {
subject: { ...artifact, format: "javascript" },
limitations: ["Not executed"],
}),
);
},
});
const result = await service.recover(input);
if (!result.ok) throw result.error;
expect(received).toEqual([
{ ...input, extraction_mode: "structural", rewrite_level: "standard" },
]);
expect(result.value).toMatchObject({
operation: "recover_javascript_sources",
confidence: "derived",
authority: "shipped-artifact",
provider: providerIdentity,
});
});
it("preserves a missing provider reason", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"fixture-recovery",
"recover_javascript_sources",
"fixture missing engine",
);
const result = await new JavaScriptRecoveryService({
recover: async () => err(failure),
}).recover(input);
expect(result).toEqual(err(failure));
});
it.each([
"invalid-result",
"missing-subject",
"subject-mismatch",
"engine-mismatch",
])("rejects %s returned across the port", async (mode) => {
const service = new JavaScriptRecoveryService({
recover: async () =>
ok(
createAnalysisExecution(
mode === "invalid-result" ? {} : recoveryResult(),
mode === "engine-mismatch"
? { ...providerIdentity, id: "another-engine" }
: providerIdentity,
mode === "missing-subject"
? {}
: {
subject: {
path:
mode === "subject-mismatch" ? "/wrong.js" : artifact.path,
sha256: artifact.sha256,
format: "javascript" as const,
},
},
),
),
});
const result = await service.recover(input);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected invalid port output");
expect(result.error._tag).toBe("AnalysisOutputError");
});
it.each(["path", "output_directory"])(
"rejects relative %s before acquiring the recovery engine",
async (field) => {
let invoked = false;
const service = new JavaScriptRecoveryService({
recover: async () => {
invoked = true;
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
"recover_javascript_sources",
"engine missing",
),
);
},
});
const result = await service.recover({
...input,
[field]: "relative.js",
});
expect(invoked).toBe(false);
if (result.ok) throw new Error("expected invalid path");
expect(result.error._tag).toBe("AnalysisInputError");
expect(result.error).toMatchObject({
issues: [{ path: [field], reason: "invalid_format" }],
});
},
);
it("rejects malformed and pre-cancelled input before acquiring the port", async () => {
const service = new JavaScriptRecoveryService({
recover: async () => {
throw new Error("port must not execute");
},
});
const invalid = await service.recover({});
if (invalid.ok) throw new Error("expected malformed input");
expect(invalid.error._tag).toBe("AnalysisInputError");
const cancelled = await service.recover(input, {
signal: AbortSignal.abort(),
});
if (cancelled.ok) throw new Error("expected cancellation");
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
});
});
@@ -0,0 +1,95 @@
import { isAbsolute } from "node:path";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import {
javascriptRecoveryInputSchema,
javascriptRecoveryResultSchema,
} from "../domain/javascriptRecovery.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { JavaScriptRecoveryPort } from "./JavaScriptRecoveryPort.js";
const OPERATION = "recover_javascript_sources";
/** Shared CLI/MCP parsing and Evidence for derived JavaScript artifacts. */
export class JavaScriptRecoveryService {
constructor(readonly provider: JavaScriptRecoveryPort) {}
/** Recover sources and bind the result to its original immutable input. */
async recover(
input: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(OPERATION));
const parsed = javascriptRecoveryInputSchema.safeParse(input);
if (!parsed.success)
return err(
new AnalysisInputError(
OPERATION,
{ cause: parsed.error },
projectInputIssues(parsed.error.issues, input),
),
);
const invalidPaths = (["path", "output_directory"] as const).filter(
(field) => !isAbsolute(parsed.data[field]),
);
if (invalidPaths.length > 0)
return err(
new AnalysisInputError(
OPERATION,
undefined,
invalidPaths.map((field) => ({
path: [field],
reason: "invalid_format",
message: `${field} must be an absolute filesystem path on this host.`,
})),
),
);
const execution = await this.provider.recover(parsed.data, options);
if (!execution.ok) return execution;
const result = javascriptRecoveryResultSchema.safeParse(
execution.value.result,
);
if (!result.success || execution.value.subject === null)
return err(
new AnalysisOutputError(
OPERATION,
"Recovery did not return a valid result bound to the original source",
),
);
if (
result.data.source.path !== parsed.data.path ||
execution.value.subject.path !== result.data.source.path ||
execution.value.subject.sha256 !== result.data.source.sha256 ||
execution.value.provider.id !== result.data.engine.id ||
execution.value.provider.version !== result.data.engine.version
)
return err(
new AnalysisOutputError(
OPERATION,
"Recovery source or engine identity disagrees with its Evidence binding",
),
);
return ok(
createEvidence(execution.value.subject, execution.value.provider, {
operation: OPERATION,
parameters: jsonObjectSchema.parse(parsed.data),
result: result.data,
rawResult: execution.value.rawResult,
locations: execution.value.locations,
limitations: execution.value.limitations,
confidence: "derived",
authority: "shipped-artifact",
}),
);
}
}