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:
@@ -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"
|
||||
|
||||
@@ -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" }>;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
};
|
||||
Reference in New Issue
Block a user