feat(web): export captured scripts for JavaScript application analysis (#801)

* feat(web): export captured scripts for JavaScript application analysis

Add capture adapters, conservative source path projection, verified exclusive publication and a shared CLI/MCP workflow. Retain source identities, missing content and competing URL versions in a complete manifest for existing static analysis.

Refs: #774
Closes: #799
Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* test(web): include script export in independent effect audit

Register the new contract family in the independent inventory audit and verify the filesystem, session, network and idempotence metadata of the named export contract.

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

* fix(web): preserve capture limitation values in export manifests

Align the export boundary with passive capture’s string contract instead of rejecting an admitted empty limitation. Cover the publisher boundary and regenerate canonical schemas and identities.

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 05:24:32 +08:00
committed by GitHub
parent 894c30ef02
commit 472b72a530
47 changed files with 2158 additions and 35 deletions
@@ -53,6 +53,13 @@ export const ANDROID_APPLICATION_PROVIDER = {
version: "1",
} as const;
/** Provider identity for verified publication of retained website scripts. */
export const WEB_SCRIPT_EXPORT_PROVIDER = {
id: "rea-web-script-export",
name: "REA captured script export",
version: "1",
} as const;
/** Provider identity for deterministic static JavaScript application analysis. */
export const JAVASCRIPT_APPLICATION_PROVIDER = {
id: "rea-javascript-application",
+174
View File
@@ -0,0 +1,174 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { z } from "zod";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { publishWebScripts } from "../browser/assets/PublishWebScripts.js";
import { selectScriptCapture } from "../browser/assets/ScriptCaptureAdapters.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
import {
exportWebScriptsInputSchema,
type ExportWebScriptsInput,
} from "../domain/webScriptExport.js";
import { WebScriptExportError } from "../domain/webScriptExportError.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import { WEB_SCRIPT_EXPORT_PROVIDER as PROVIDER } from "./InvestigationProviders.js";
const OPERATION = "export_web_scripts";
/** Export one local capture through the shared CLI/MCP application workflow. */
export const exportWebScripts = async (
rawInput: unknown,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const input = exportWebScriptsInputSchema.safeParse(rawInput);
return input.success
? exportWebScriptsValidated(input.data, options)
: err(
new AnalysisInputError(
OPERATION,
undefined,
projectInputIssues(input.error.issues, rawInput),
),
);
};
/** Publish input already parsed by a named adapter contract. */
export const exportWebScriptsValidated = async (
input: ExportWebScriptsInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
if (!isAbsolute(input.capture_path) || !isAbsolute(input.output_directory))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: [],
reason: "invalid_format",
message:
"capture_path and output_directory must be absolute filesystem paths on this host.",
},
]),
);
try {
options.signal?.throwIfAborted();
const bytes = await readFile(input.capture_path, {
signal: options.signal,
});
const loaded = parseCapture(bytes);
if (!loaded.ok) return loaded;
options.signal?.throwIfAborted();
const sha256 = createHash("sha256").update(bytes).digest("hex");
const result = await publishWebScripts(
input,
loaded.value,
sha256,
options.signal,
);
return ok(
createEvidence(
{ path: input.capture_path, sha256, format: "file" },
PROVIDER,
{
predicateType: "rea.web-script-export",
operation: OPERATION,
parameters: {
capture_path: input.capture_path,
output_directory: input.output_directory,
},
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "derived",
authority: "historical-reference",
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: result.manifest.path }],
evidenceLinks:
loaded.value.sourceEvidenceId === null
? []
: [loaded.value.sourceEvidenceId],
},
),
);
} catch (cause: unknown) {
if (cause instanceof WebScriptExportError) return err(cause);
if (options.signal?.aborted === true)
return err(new AnalysisCancelledError(OPERATION));
if (cause instanceof ArtifactReaderFailure)
return err(
new WebScriptExportError(
cause.reason,
input.output_directory,
cause.message,
),
);
if (cause instanceof z.ZodError)
return err(new AnalysisOutputError(OPERATION, cause.message, { cause }));
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
)
return err(
new WebScriptExportError(
"io",
`${input.capture_path} → ${input.output_directory}`,
cause.message,
),
);
return err(
new ProviderAdapterError(PROVIDER.id, OPERATION, {
cause,
diagnostics: {
capture_path: input.capture_path,
output_directory: input.output_directory,
error_name: cause instanceof Error ? cause.name : "UnknownError",
error_message:
cause instanceof Error
? cause.message
: typeof cause === "string"
? cause
: "Unknown script export failure",
},
}),
);
}
};
const parseCapture = (
bytes: Buffer,
): Result<ReturnType<typeof selectScriptCapture>, AnalysisError> => {
try {
const text = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true,
}).decode(bytes);
const json = safeParseJson(text);
if (!json.ok) throw new TypeError(json.error);
return ok(selectScriptCapture(json.value));
} catch (cause: unknown) {
return err(
new AnalysisInputError(OPERATION, { cause }, [
{
path: ["capture_path"],
reason: "invalid_format",
message:
cause instanceof Error
? cause.message
: "Capture is not valid UTF-8 JSON evidence.",
},
]),
);
}
};
+38
View File
@@ -0,0 +1,38 @@
import type { WebPageInspection } from "../../domain/browserObservation.js";
import type { CapturedWebScript } from "../../domain/webScriptExport.js";
/** Project verified Debugger sources without fetching resource URLs. */
export const pageScripts = (
capture: Pick<WebPageInspection, "scripts">,
): CapturedWebScript[] =>
capture.scripts.items.map((script) => ({
source: {
kind: "page-script",
script_key: script.script_key,
frame_id: script.frame_id,
is_module: script.is_module,
language: script.language,
source_map_url: script.source_map_url,
},
url: script.url,
content: !script.source.included
? {
state: "unavailable",
reason: "source-not-included",
message: script.source.reason || "Debugger source was not included.",
}
: script.language !== null && script.language !== "JavaScript"
? {
state: "unavailable",
reason: "unsupported-language",
message: `Debugger reported language ${script.language}; JavaScript export was not inferred.`,
}
: {
state: "captured",
bytes: Buffer.from(script.source.artifact.text, "utf8"),
sha256: script.source.artifact.sha256,
media_type: script.source.artifact.media_type,
redacted: null,
representation: "debugger-source-utf8",
},
}));
+102
View File
@@ -0,0 +1,102 @@
import { createHash } from "node:crypto";
import { join } from "node:path";
import { Readable } from "node:stream";
import { SafeOutputTree } from "../../artifacts/SafeOutputTree.js";
import {
webScriptExportManifestSchema,
webScriptExportResultSchema,
type ExportWebScriptsInput,
type WebScriptExportResult,
} from "../../domain/webScriptExport.js";
import { planWebScriptExport } from "../../domain/webScriptExportPlan.js";
import { WebScriptExportError } from "../../domain/webScriptExportError.js";
import type { SelectedScriptCapture } from "./ScriptCaptureAdapters.js";
const LIMITATIONS = [
"Only script bytes retained in this capture are exported. Sources are not refetched or executed, and a response or Debugger source does not prove execution.",
"Ordinary unambiguous URL paths preserve relative module layouts by origin. Query variants, collisions, inline sources, and unrepresentable paths are isolated; their browser module relationships remain unknown.",
"Local JavaScript analysis does not implement browser import maps, root-relative URL resolution, remote URL loading, or browser runtime behavior. It may strip import queries and fragments; isolated variants are not canonical targets.",
"Source-map declarations are retained as metadata. No source maps or missing dependencies are fetched or reconstructed.",
"Captured response bytes are browser-decoded bytes; Debugger sources are the exposed text encoded as UTF-8. Redacted bytes are exported exactly as retained, and may no longer parse as JavaScript.",
];
/** Exclusively publish verified bytes and a manifest, rolling back partial work. */
export const publishWebScripts = async (
input: ExportWebScriptsInput,
capture: SelectedScriptCapture & { readonly sourceEvidenceId: string | null },
captureSha256: string,
signal?: AbortSignal,
): Promise<WebScriptExportResult> => {
const planned = planWebScriptExport(capture.scripts);
const tree = await SafeOutputTree.create(input.output_directory);
try {
signal?.throwIfAborted();
const records = planned.map(({ record }) => record);
const manifest = webScriptExportManifestSchema.parse({
capture_path: input.capture_path,
capture_sha256: captureSha256,
capture_kind: capture.kind,
source_evidence_id: capture.sourceEvidenceId,
capture_completeness: capture.completeness,
output_directory: tree.outputRoot,
analysis_input: records.some(
({ content }) => content.state === "exported",
)
? { input_path: join(tree.outputRoot, "files"), format: "directory" }
: null,
scripts: records,
limitations: [
...capture.limitations,
...LIMITATIONS,
...(records.some(({ content }) => content.state === "exported")
? []
: [
"No script bytes were exportable. Include script sources in inspect_web_page or select response_body in capture_browser_scenario, then capture again.",
]),
],
});
const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
const digest = createHash("sha256").update(bytes).digest("hex");
const result = webScriptExportResultSchema.parse({
...manifest,
manifest: {
path: join(tree.outputRoot, "manifest.json"),
sha256: digest,
bytes: bytes.length,
},
});
for (const { script, record } of planned) {
signal?.throwIfAborted();
if (
script.content.state === "captured" &&
record.content.state === "exported"
)
await tree.write(
`files/${record.content.relative_path}`,
Readable.from([script.content.bytes]),
script.content.sha256,
signal,
);
}
await tree.write("manifest.json", Readable.from([bytes]), digest, signal);
signal?.throwIfAborted();
await tree.commit();
return result;
} catch (cause: unknown) {
try {
await tree.rollback();
} catch (cleanupCause: unknown) {
throw new WebScriptExportError(
"io",
tree.outputRoot,
`Publication failed (${message(cause)}); rollback failed (${message(cleanupCause)}). Remove the residual output directory before retrying.`,
[tree.outputRoot],
);
}
throw cause;
}
};
const message = (cause: unknown): string =>
cause instanceof Error ? cause.message : "Unknown publication failure";
+129
View File
@@ -0,0 +1,129 @@
import type { BrowserScenarioCapture } from "../../domain/browserScenarioCapture.js";
import type { BrowserScenarioEvent } from "../../domain/browserScenarioCaptureValues.js";
import type { BrowserNetworkBody } from "../../domain/browserNetworkEvidence.js";
import type { CapturedWebScript } from "../../domain/webScriptExport.js";
type RequestEvent = Extract<BrowserScenarioEvent, { kind: "request" }>;
type ResponseEvent = Extract<BrowserScenarioEvent, { kind: "response" }>;
type ContentEvent = Extract<BrowserScenarioEvent, { kind: "network-content" }>;
interface ResponseIndex {
readonly responses: Map<string, ResponseEvent[]>;
readonly contents: Map<number, ContentEvent[]>;
readonly requests: Map<string, number>;
}
/** Join script response bytes only through explicit transaction and event identity. */
export const scenarioScripts = (
capture: BrowserScenarioCapture,
): CapturedWebScript[] => {
const index = indexResponses(capture.events.items);
return capture.events.items.flatMap((request): CapturedWebScript[] => {
if (request.kind !== "request" || request.resource_type !== "script")
return [];
return [projectRequest(request, index)];
});
};
const indexResponses = (
events: readonly BrowserScenarioEvent[],
): ResponseIndex => {
const index: ResponseIndex = {
responses: new Map(),
contents: new Map(),
requests: new Map(),
};
for (const event of events) {
if (event.kind === "request" && event.transaction_id !== undefined)
index.requests.set(
event.transaction_id,
(index.requests.get(event.transaction_id) ?? 0) + 1,
);
if (event.kind === "response" && event.transaction_id !== undefined)
append(index.responses, event.transaction_id, event);
if (event.kind === "network-content" && event.phase === "response")
append(index.contents, event.source_event_sequence, event);
}
return index;
};
const projectRequest = (
request: RequestEvent,
index: ResponseIndex,
): CapturedWebScript => {
const id = request.transaction_id;
const matches = id === undefined ? [] : (index.responses.get(id) ?? []);
const response = matches.length === 1 ? matches[0] : undefined;
const bodies =
response === undefined ? [] : (index.contents.get(response.sequence) ?? []);
const body = bodies.length === 1 ? bodies[0]?.body : undefined;
const ambiguous =
(id !== undefined && index.requests.get(id) !== 1) ||
matches.length > 1 ||
bodies.length > 1;
return {
source: {
kind: "scenario-response",
transaction_id: id ?? null,
request_sequence: request.sequence,
response_sequence: ambiguous ? null : (response?.sequence ?? null),
status: ambiguous ? null : (response?.status ?? null),
},
url: request.url.url,
content: projectBody(body, id, ambiguous),
};
};
const unavailable = (
reason: string,
message: string,
): CapturedWebScript["content"] => ({ state: "unavailable", reason, message });
const projectBody = (
body: BrowserNetworkBody | undefined,
transactionId: string | undefined,
ambiguous: boolean,
): CapturedWebScript["content"] => {
if (ambiguous)
return unavailable(
"ambiguous-transaction",
"The capture does not identify one request, response, and content record for this transaction.",
);
if (body === undefined)
return unavailable(
transactionId === undefined
? "transaction-identity-unavailable"
: "response-content-not-retained",
"No selected, completed script response bytes were retained for this request.",
);
if (body.state === "unavailable")
return unavailable(body.reason, body.message);
if (body.state !== "captured")
return unavailable(
body.state,
"No selected, completed script response bytes were retained for this request.",
);
if (body.representation !== "browser-decoded-response-bytes")
return unavailable(
"unsupported-body-representation",
`Captured representation ${body.representation} is not script response bytes.`,
);
return {
state: "captured",
bytes: Buffer.from(body.content, "base64"),
sha256: body.sha256,
media_type: body.media_type,
redacted: body.redacted,
representation: body.representation,
};
};
const append = <Key, Value>(
map: Map<Key, Value[]>,
key: Key,
value: Value,
): void => {
const existing = map.get(key);
if (existing === undefined) map.set(key, [value]);
else existing.push(value);
};
@@ -0,0 +1,184 @@
import { describe, expect, it } from "vitest";
import {
scriptCaptureEvidenceFixture,
scriptScenarioFixture,
} from "../../../tests/fixtures/webScriptCapture.js";
import { createWebTextArtifact } from "../../domain/webContentArtifact.js";
import { pageScripts } from "./PageScriptCapture.js";
import { selectScriptCapture } from "./ScriptCaptureAdapters.js";
describe("passive script projection", () => {
it("preserves passive source bytes, declarations, and unavailable languages", () => {
const artifact = createWebTextArtifact(
"export const 中文 = '值';",
"text/javascript",
);
const base = {
script_key: `scr_${"a".repeat(64)}`,
frame_id: "frame",
url: "https://a.test/main.js",
origin: "https://a.test",
cdp_hash: "cdp-hash",
length: artifact.text.length,
is_module: true,
language: "JavaScript",
source_map_url: "main.js.map",
resource_reconciliation: {
status: "exact",
resource_key: `res_${"b".repeat(64)}`,
} as const,
source: { included: true, artifact } as const,
};
const scripts = pageScripts({
scripts: {
total: 3,
items: [
base,
{ ...base, language: "WebAssembly" },
{ ...base, source: { included: false, reason: "not selected" } },
],
},
});
expect(scripts[0]?.content).toMatchObject({
state: "captured",
sha256: artifact.sha256,
bytes: Buffer.from(artifact.text),
representation: "debugger-source-utf8",
redacted: null,
});
expect(scripts[0]?.source).toMatchObject({
source_map_url: "main.js.map",
frame_id: "frame",
});
expect(scripts[1]?.content).toMatchObject({
state: "unavailable",
reason: "unsupported-language",
});
expect(scripts[2]?.content).toMatchObject({
state: "unavailable",
message: "not selected",
});
});
});
describe("script capture identity and response projection", () => {
it("joins identical URLs by transaction and source event, retaining binary bytes", () => {
const capture = scriptScenarioFixture([
{
url: "https://fixture.test/main.js",
bytes: Buffer.from([255, 0, 254]),
},
{ url: "https://fixture.test/main.js", bytes: Buffer.from("second") },
]);
capture.events.items.reverse();
const scripts = selectScriptCapture(capture).scripts;
expect(scripts[0]?.content).toMatchObject({ bytes: Buffer.from("second") });
expect(scripts[1]?.content).toMatchObject({
bytes: Buffer.from([255, 0, 254]),
});
expect(scripts[0]?.source).toMatchObject({
transaction_id: "request-2",
response_sequence: 5,
});
});
it("keeps a metadata-only script request explicitly unavailable", () => {
const capture = scriptScenarioFixture();
capture.events.items = capture.events.items.filter(
({ kind }) => kind !== "network-content",
);
capture.events.retained = capture.events.items.length;
expect(selectScriptCapture(capture).scripts[0]?.content).toMatchObject({
state: "unavailable",
reason: "response-content-not-retained",
});
});
it("authenticates saved Evidence and rejects changed result bytes", () => {
const evidence = scriptCaptureEvidenceFixture();
expect(selectScriptCapture(evidence).sourceEvidenceId).toBe(
evidence.evidence_id,
);
expect(() =>
selectScriptCapture({
...evidence,
normalized_result: scriptScenarioFixture([]),
}),
).toThrow("semantic identifier");
});
it("rejects invalid content digests before publication", () => {
const capture = scriptScenarioFixture();
const content = capture.events.items.find(
({ kind }) => kind === "network-content",
);
if (
content?.kind !== "network-content" ||
content.body.state !== "captured"
)
throw new Error("Missing fixture body");
content.body.sha256 = "0".repeat(64);
expect(() => selectScriptCapture(capture)).toThrow("Expected a valid");
});
it("refuses to select one byte source from duplicate transaction identities", () => {
const capture = scriptScenarioFixture();
const request = capture.events.items[0];
if (request?.kind !== "request") throw new Error("Missing request");
capture.events.items.push({ ...request, sequence: 4 });
capture.events.retained = 4;
expect(selectScriptCapture(capture).scripts[0]?.source).toMatchObject({
response_sequence: null,
status: null,
});
expect(
selectScriptCapture(capture).scripts.every(
({ content }) =>
content.state === "unavailable" &&
content.reason === "ambiguous-transaction",
),
).toBe(true);
});
it("retains declared redaction and rejects an unexpected response representation", () => {
const capture = scriptScenarioFixture();
const content = capture.events.items.find(
({ kind }) => kind === "network-content",
);
if (
content?.kind !== "network-content" ||
content.body.state !== "captured"
)
throw new Error("Missing response bytes");
content.body.redacted = true;
expect(selectScriptCapture(capture).scripts[0]?.content).toMatchObject({
state: "captured",
redacted: true,
});
content.body.representation = "browser-exposed-request-bytes";
expect(selectScriptCapture(capture).scripts[0]?.content).toMatchObject({
state: "unavailable",
reason: "unsupported-body-representation",
message: expect.stringContaining("browser-exposed-request-bytes"),
});
});
it("does not join legacy metadata by URL when transaction identity is absent", () => {
const capture = scriptScenarioFixture();
capture.events.items = capture.events.items.filter(
({ kind }) => kind !== "network-content",
);
for (const event of capture.events.items)
if (event.kind === "request" || event.kind === "response")
delete event.transaction_id;
capture.events.retained = capture.events.items.length;
expect(selectScriptCapture(capture).scripts[0]).toMatchObject({
source: { transaction_id: null },
content: {
state: "unavailable",
reason: "transaction-identity-unavailable",
},
});
});
});
@@ -0,0 +1,83 @@
import { webPageInspectionSchema } from "../../domain/browserObservation.js";
import { browserScenarioCaptureSchema } from "../../domain/browserScenarioCapture.js";
import { parseEvidence } from "../../domain/evidence.js";
import type {
CapturedWebScript,
WebScriptExportResult,
} from "../../domain/webScriptExport.js";
import { pageScripts } from "./PageScriptCapture.js";
import { scenarioScripts } from "./ScenarioScriptCapture.js";
/** Capture-specific parsing and source selection, independent of publication. */
export interface ScriptCaptureAdapter {
readonly operation: string;
readonly parse: (input: unknown) => SelectedScriptCapture | undefined;
}
/** Verified source records with the original capture coverage and limitations. */
export interface SelectedScriptCapture {
readonly kind: WebScriptExportResult["capture_kind"];
readonly completeness: WebScriptExportResult["capture_completeness"];
readonly scripts: readonly CapturedWebScript[];
readonly limitations: readonly string[];
}
/** Built-in adapters; add capture formats here without changing the publisher. */
export const SCRIPT_CAPTURE_ADAPTERS: readonly ScriptCaptureAdapter[] = [
{
operation: "inspect_web_page",
parse: (input) => {
const parsed = webPageInspectionSchema.safeParse(input);
return parsed.success
? {
kind: "page-inspection",
completeness: parsed.data.completeness,
scripts: pageScripts(parsed.data),
limitations: parsed.data.limitations,
}
: undefined;
},
},
{
operation: "capture_browser_scenario",
parse: (input) => {
const parsed = browserScenarioCaptureSchema.safeParse(input);
return parsed.success
? {
kind: "browser-scenario",
completeness: parsed.data.completeness,
scripts: scenarioScripts(parsed.data),
limitations: parsed.data.limitations,
}
: undefined;
},
},
];
/** Reject unsupported/malformed captures and tampered Evidence before writing. */
export const selectScriptCapture = (
raw: unknown,
adapters: readonly ScriptCaptureAdapter[] = SCRIPT_CAPTURE_ADAPTERS,
): SelectedScriptCapture & { readonly sourceEvidenceId: string | null } => {
if (
typeof raw === "object" &&
raw !== null &&
("normalized_result" in raw || "evidence_id" in raw)
) {
const evidence = parseEvidence(raw);
const selected = adapters
.find(({ operation }) => operation === evidence.operation)
?.parse(evidence.normalized_result);
if (selected !== undefined)
return { ...selected, sourceEvidenceId: evidence.evidence_id };
} else {
for (const adapter of adapters) {
const selected = adapter.parse(raw);
if (selected !== undefined)
return { ...selected, sourceEvidenceId: null };
}
}
throw new TypeError(
"Expected a valid inspect_web_page or capture_browser_scenario capture, with retained script sources or response bytes. Evidence envelopes must have a matching operation and semantic identifier.",
);
};
+2
View File
@@ -12,6 +12,7 @@ import { registerAndroidCommands } from "./cli/androidCommands.js";
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
import { registerProcessCommands } from "./cli/processCommands.js";
import { registerBrowserCommands } from "./cli/browserCommands.js";
import { registerWebScriptCommands } from "./cli/webScriptCommands.js";
import { registerAdvancedBrowserCommands } from "./cli/browserAdvancedCommands.js";
import { registerBrowserScenarioCommands } from "./cliBrowserScenarioCommands.js";
import { registerElectronCommands } from "./cli/electronCommands.js";
@@ -54,6 +55,7 @@ export const createCli = (
registerEvidenceCommands(cli, logger);
registerProcessCommands(cli, logger, environment);
registerBrowserCommands(cli, logger);
registerWebScriptCommands(cli, logger);
registerAdvancedBrowserCommands(cli, logger);
registerBrowserScenarioCommands(cli, logger);
registerElectronCommands(cli, logger);
+41
View File
@@ -0,0 +1,41 @@
import { Cli, z } from "incur";
import { exportWebScripts } from "../application/WebScriptExportService.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "../logger.js";
/** Register the local captured-script export CLI workflow. */
export const registerWebScriptCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.exportWebScripts, {
description:
"Export retained website scripts into an absent directory for static JavaScript analysis",
args: z.object({
capturePath: z
.string()
.describe("Absolute path to saved page or scenario capture JSON"),
outputDirectory: z
.string()
.describe(
"Absolute absent directory for verified scripts and manifest",
),
}),
run: ({ args }) =>
logCliCommand(logger, CLI_COMMANDS.exportWebScripts, async () => {
const result = await exportWebScripts({
capture_path: args.capturePath,
output_directory: args.outputDirectory,
});
return result.ok
? result.value
: {
error: "Script export failed",
...projectAnalysisError(result.error),
};
}),
});
};
+1
View File
@@ -60,6 +60,7 @@ export const CLI_COMMANDS = Object.freeze({
listBrowserTargets: "list-browser-targets",
inspectWebPage: "inspect-web-page",
analyzeWebBundle: "analyze-web-bundle",
exportWebScripts: "export-web-scripts",
observeWebSession: "observe-web-session",
discoverWebMcpTools: "discover-webmcp-tools",
compareWebCaptures: "compare-web-captures",
+23 -1
View File
@@ -17,8 +17,9 @@ import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
import { TOOL_EFFECTS } from "./toolEffects.js";
import { TOOL_CONTRACTS } from "./toolContracts.js";
import { TOOL_CONTRACTS, toolContract } from "./toolContracts.js";
import {
CLI_COMMAND_ALIASES,
CLI_COMMAND_NAMES,
@@ -84,11 +85,32 @@ describe("tool contract surface", () => {
...ELECTRON_TOOL_CONTRACTS,
...JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
...WEB_SCRIPT_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
].map(({ name }) => name);
expect(Object.keys(TOOL_EFFECTS).sort()).toEqual(names.sort());
});
it("advertises local script publication and exclusive output authority", () => {
const contract = toolContract("export_web_scripts");
expect(contract.effects).toEqual({
mutatesTarget: false,
mutatesSession: true,
writesFilesystem: true,
launchesProcess: false,
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
idempotent: false,
});
expect(contract.annotations).toEqual({
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
});
});
it("marks process scenario capture as open world", () => {
expect(
SESSION_TOOL_CONTRACTS.find(
+1
View File
@@ -78,6 +78,7 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
"evaluate_reconstruction_coverage",
"export_evidence_bundle",
"extract_artifact",
"export_web_scripts",
"find_changed_behavior",
"find_xrefs_to_name",
"get_call_graph",
+2
View File
@@ -8,6 +8,7 @@ import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
@@ -28,6 +29,7 @@ export const TOOL_CONTRACTS = [
...ELECTRON_TOOL_CONTRACTS,
...JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
...WEB_SCRIPT_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
] as const;
+5
View File
@@ -215,6 +215,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
list_javascript_runtime_targets: browserEvidence,
observe_javascript_runtime: browserEvidence,
analyze_javascript_application: evidence,
export_web_scripts: effects({
mutatesSession: true,
writesFilesystem: true,
idempotent: false,
}),
reconcile_javascript_runtime: evidence,
trace_application_feature: evidence,
trace_javascript_semantics: evidence,
+29
View File
@@ -0,0 +1,29 @@
import {
exportWebScriptsInputSchema,
webScriptExportResultSchema,
} from "../domain/webScriptExport.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
/** Local captured-script publication contracts shared by CLI and MCP. */
export const WEB_SCRIPT_TOOL_CONTRACTS = [
{
name: "export_web_scripts",
...toolContractMetadata("export_web_scripts"),
description:
"Export JavaScript bytes already retained in one local inspect_web_page or capture_browser_scenario JSON capture (normalized result or complete Evidence). Writes scripts and a digest-verified manifest into an absent absolute output_directory. Returns all source URLs, script or transaction/event references, unavailable states, and an analysis_input for analyze_javascript_application when any bytes were exported. Include script sources in inspect_web_page or select capture.network.response_body in scenarios. No refetch or execution. Safe unambiguous URL layouts preserve relative module paths; versions, query variants, inline scripts, and path collisions are isolated with explicit resolution limitations.",
kind: "application",
inputSchema: exportWebScriptsInputSchema,
outputSchema: evidenceResultOf(webScriptExportResultSchema),
examples: [
{
title: "Export a saved website capture for static JavaScript analysis",
input: {
capture_path: "/analysis/capture.json",
output_directory: "/analysis/exported-scripts",
},
},
],
},
] as const satisfies readonly ToolContract[];
+1
View File
@@ -12,6 +12,7 @@ export class ArtifactOperationError extends AnalysisError {
| "decode_interface_builder"
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "export_web_scripts"
| "analyze_javascript_application",
readonly reason:
| "cancelled"
+123
View File
@@ -0,0 +1,123 @@
import { z } from "zod";
import { browserCompletenessSchema } from "./browserCompleteness.js";
import { browserScenarioCompletenessSchema } from "./browserScenarioCaptureValues.js";
import { digestSchema, prefixedDigestSchema } from "./digests.js";
/** Export already captured scripts into one absent, caller-selected directory. */
export const exportWebScriptsInputSchema = z.strictObject({
capture_path: z
.string()
.min(1)
.describe(
"Absolute filesystem path to saved inspect_web_page or capture_browser_scenario JSON, normalized result or complete Evidence",
),
output_directory: z
.string()
.min(1)
.describe(
"Absolute absent filesystem directory for verified scripts and manifest; parent directory must exist",
),
});
export type ExportWebScriptsInput = z.output<
typeof exportWebScriptsInputSchema
>;
const sourceSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("page-script"),
script_key: z.string().min(1),
frame_id: z.string().nullable(),
is_module: z.boolean(),
language: z.string().nullable(),
source_map_url: z.string().nullable(),
}),
z.strictObject({
kind: z.literal("scenario-response"),
transaction_id: z.string().nullable(),
request_sequence: z.number().int().min(1),
response_sequence: z.number().int().min(1).nullable(),
status: z.number().nullable(),
}),
]);
/** Exact retained-source identity and publication outcome. */
export const exportedWebScriptSchema = z.strictObject({
source: sourceSchema,
url: z.string(),
content: z.discriminatedUnion("state", [
z.strictObject({
state: z.literal("exported"),
relative_path: z.string().min(1),
layout: z.enum(["url-path", "isolated"]),
layout_reason: z.string().nullable(),
sha256: digestSchema,
bytes: z.number().int().min(0),
media_type: z.string().nullable(),
redacted: z.boolean().nullable(),
representation: z.enum([
"debugger-source-utf8",
"browser-decoded-response-bytes",
]),
}),
z.strictObject({
state: z.literal("unavailable"),
reason: z.string().min(1),
message: z.string().min(1),
}),
]),
});
export type ExportedWebScript = z.output<typeof exportedWebScriptSchema>;
/** Persisted manifest, also returned inline without duplicating script bytes. */
export const webScriptExportManifestSchema = z.strictObject({
capture_path: z.string().min(1),
capture_sha256: digestSchema,
capture_kind: z.enum(["page-inspection", "browser-scenario"]),
source_evidence_id: prefixedDigestSchema("ev").nullable(),
capture_completeness: z.union([
browserCompletenessSchema,
browserScenarioCompletenessSchema,
]),
output_directory: z.string().min(1),
analysis_input: z
.strictObject({
input_path: z.string().min(1),
format: z.literal("directory"),
})
.nullable(),
scripts: z.array(exportedWebScriptSchema),
limitations: z.array(z.string()),
});
/** Verified publication including the digest of the persisted manifest. */
export const webScriptExportResultSchema = webScriptExportManifestSchema.extend(
{
manifest: z.strictObject({
path: z.string().min(1),
sha256: digestSchema,
bytes: z.number().int().min(0),
}),
},
);
export type WebScriptExportResult = z.output<
typeof webScriptExportResultSchema
>;
/** Adapter input to the provider-neutral path planner and publisher. */
export interface CapturedWebScript {
readonly source: ExportedWebScript["source"];
readonly url: string;
readonly content:
| {
readonly state: "captured";
readonly bytes: Buffer;
readonly sha256: string;
readonly media_type: string | null;
readonly redacted: boolean | null;
readonly representation:
| "debugger-source-utf8"
| "browser-decoded-response-bytes";
}
| Extract<ExportedWebScript["content"], { state: "unavailable" }>;
}
+20
View File
@@ -0,0 +1,20 @@
import { ArtifactOperationError } from "./artifactOperationError.js";
/** Publication failure retaining its input/output target and cleanup state. */
export class WebScriptExportError extends ArtifactOperationError {
override readonly userMessage: string;
override readonly cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
constructor(
reason: ArtifactOperationError["reason"],
target: string,
diagnostic: string,
residualPaths: readonly string[] = [],
) {
super("export_web_scripts", reason);
this.userMessage = `Script export failed for ${target}: ${diagnostic}`;
this.cleanupResources = residualPaths;
this.cleanupIncomplete = residualPaths.length > 0;
}
}
+121
View File
@@ -0,0 +1,121 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import type { CapturedWebScript } from "./webScriptExport.js";
import { planWebScriptExport } from "./webScriptExportPlan.js";
const source = (url: string, index = 1): CapturedWebScript => {
const bytes = Buffer.from(`export const marker = ${index};`);
return {
url,
source: {
kind: "page-script",
script_key: `script-${index}`,
frame_id: null,
is_module: true,
language: "JavaScript",
source_map_url: null,
},
content: {
state: "captured",
bytes,
sha256: createHash("sha256").update(bytes).digest("hex"),
media_type: "text/javascript",
redacted: null,
representation: "debugger-source-utf8",
},
};
};
describe("captured script path projection", () => {
it("preserves ordinary relative layouts separately for each origin", () => {
const planned = planWebScriptExport([
source("https://a.test/app/main.js"),
source("https://a.test/app/lib/value.mjs", 2),
source("https://b.test/app/main.js", 3),
]);
const paths = planned.map(({ record }) =>
record.content.state === "exported" ? record.content.relative_path : "",
);
expect(paths[0]).toMatch(/^origins\/[a-f0-9]{64}\/app\/main.js$/u);
expect(paths[1]?.replace("lib/value.mjs", "main.js")).toBe(paths[0]);
expect(paths[2]).not.toBe(paths[0]);
});
it.each([
["https://a.test/main.js", "https://a.test/main.js"],
["https://a.test/main.js", "https://a.test/main.js?v=2"],
["https://a.test/A/main.js", "https://a.test/a/other.js"],
["https://a.test/main.js", "https://a.test/main.js/child.js"],
])(
"isolates every version in a conflicting layout (%s, %s)",
(first, second) => {
const planned = planWebScriptExport([source(first), source(second, 2)]);
expect(
planned.every(
({ record }) =>
record.content.state === "exported" &&
record.content.layout === "isolated",
),
).toBe(true);
expect(
new Set(
planned.map(({ record }) =>
record.content.state === "exported"
? record.content.relative_path
: null,
),
).size,
).toBe(2);
},
);
it.each([
"",
"https://a.test/main.js?v=2",
"https://a.test/main.js#variant",
"data:text/javascript,export{}",
"https://a.test/%2fescape.js",
"https://a.test/CON.js",
"https://a.test/目录/main.js",
"https://a.test/app",
])(
"retains unrepresentable URLs without using them as filesystem paths: %s",
(url) => {
const [{ record } = { record: undefined }] = planWebScriptExport([
source(url),
]);
expect(record).toMatchObject({
url,
content: {
state: "exported",
layout: "isolated",
relative_path: expect.stringMatching(
/^isolated\/source-1-[a-f0-9]{64}\.js$/u,
),
},
});
},
);
it("does not choose a canonical version when a competing source is unavailable", () => {
const missing: CapturedWebScript = {
...source("https://a.test/main.js?v=2", 2),
content: {
state: "unavailable",
reason: "not_requested",
message: "Not retained",
},
};
const planned = planWebScriptExport([
source("https://a.test/main.js"),
missing,
]);
expect(planned[0]?.record.content).toMatchObject({
state: "exported",
layout: "isolated",
});
expect(planned[1]?.record.content).toEqual(missing.content);
});
});
+145
View File
@@ -0,0 +1,145 @@
import { createHash } from "node:crypto";
import type {
CapturedWebScript,
ExportedWebScript,
} from "./webScriptExport.js";
const hash = (text: string): string =>
createHash("sha256").update(text).digest("hex");
const PORTABLE_SEGMENT = /^[A-Za-z0-9_~.-]+$/u;
const RESERVED_SEGMENT = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu;
/** One planned file, or an explicit missing source with no filesystem effect. */
export interface PlannedWebScript {
readonly script: CapturedWebScript;
readonly record: ExportedWebScript;
}
/** Preserve safe URL layouts only when every captured path is unambiguous. */
export const planWebScriptExport = (
scripts: readonly CapturedWebScript[],
): readonly PlannedWebScript[] => {
const candidates = scripts.map(candidatePath);
const conflicts = conflictingPaths(candidates);
return scripts.map((script, index) => {
if (script.content.state === "unavailable")
return {
script,
record: {
source: script.source,
url: script.url,
content: script.content,
},
};
const candidate = candidates[index];
const reason = conflicts.has(index)
? "Captured paths collide by content version, case, or file/directory prefix."
: (candidate?.reason ?? null);
const path = reason === null ? candidate?.path : undefined;
return {
script,
record: {
source: script.source,
url: script.url,
content: {
state: "exported",
relative_path:
path ??
`isolated/source-${index + 1}-${hash(JSON.stringify(script.source))}.js`,
layout: path === undefined ? "isolated" : "url-path",
layout_reason: reason,
sha256: script.content.sha256,
bytes: script.content.bytes.length,
media_type: script.content.media_type,
redacted: script.content.redacted,
representation: script.content.representation,
},
},
};
});
};
interface CandidatePath {
readonly path?: string;
readonly reason: string | null;
}
const candidatePath = (script: CapturedWebScript): CandidatePath => {
let url: URL;
try {
url = new URL(script.url);
} catch {
return {
reason: "Source has no absolute HTTP URL (for example an inline script).",
};
}
if (url.protocol !== "http:" && url.protocol !== "https:")
return { reason: "Source URL scheme has no local module layout mapping." };
const parts = url.pathname.slice(1).split("/");
if (
!/\.(?:js|mjs|cjs)$/u.test(url.pathname) ||
parts.some(
(part) =>
!PORTABLE_SEGMENT.test(part) ||
part === "." ||
part === ".." ||
part.endsWith(".") ||
RESERVED_SEGMENT.test(part),
)
)
return {
reason: "URL path is not an ordinary portable JavaScript module path.",
};
return {
path: `origins/${hash(url.origin)}/${parts.join("/")}`,
reason:
url.search !== "" ||
url.hash !== "" ||
url.username !== "" ||
url.password !== ""
? "URL query, fragment, or credentials cannot select a canonical local module."
: null,
};
};
// Register every prefix so case collisions in parent directories and a file
// conflicting with a directory isolate all affected sources, not just the last.
const conflictingPaths = (
candidates: readonly CandidatePath[],
): Set<number> => {
const prefixes = new Map<
string,
{
spellings: Set<string>;
indices: number[];
files: number[];
}
>();
candidates.forEach(({ path }, index) => {
if (path === undefined) return;
const parts = path.split("/");
parts.forEach((_, position) => {
const spelling = parts.slice(0, position + 1).join("/");
const key = spelling.toLowerCase();
const entry = prefixes.get(key) ?? {
spellings: new Set<string>(),
indices: [],
files: [],
};
entry.spellings.add(spelling);
entry.indices.push(index);
if (position === parts.length - 1) entry.files.push(index);
prefixes.set(key, entry);
});
});
const conflicts = new Set<number>();
for (const entry of prefixes.values())
if (
entry.spellings.size > 1 ||
entry.files.length > 1 ||
(entry.files.length > 0 && entry.indices.length > entry.files.length)
)
for (const index of entry.indices) conflicts.add(index);
return conflicts;
};
File diff suppressed because one or more lines are too long
+2
View File
@@ -14,6 +14,7 @@ import { registerApplicationTools } from "./registerApplicationTools.js";
import { registerArtifactTools } from "./registerArtifactTools.js";
import { registerBrowserScenarioTool } from "./registerBrowserScenarioTool.js";
import { registerBrowserTools } from "./registerBrowserTools.js";
import { registerWebScriptTool } from "./registerWebScriptTool.js";
import { registerElectronTools } from "./registerElectronTools.js";
import { registerEnhancedTools } from "./registerEnhancedTools.js";
import { registerJavaScriptRuntimeObservationTools } from "./registerJavaScriptRuntimeObservationTools.js";
@@ -252,6 +253,7 @@ const registerObservationTools = ({
recordEvidenceWithUnknown,
}: ServerToolContext): void => {
const common = { logger, recordEvidence };
registerWebScriptTool(server, common);
registerBrowserTools(server, {
...common,
browser: options.browserObservation,
+34
View File
@@ -0,0 +1,34 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { exportWebScriptsValidated } from "../application/WebScriptExportService.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
/** Register local script export without requiring a live browser provider. */
export const registerWebScriptTool = (
server: McpServer,
options: {
readonly logger: Logger;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
},
): void => {
const contract = toolContract("export_web_scripts");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
const result = await logToolExecution(options.logger, contract.name, () =>
exportWebScriptsValidated(input, { signal: context.mcpReq.signal }),
);
if (!result.ok) return toCallToolResult(result, contract);
const recorded = options.recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult(result, contract);
},
);
};