feat(browser): trace captured website module imports (#879)

* feat(browser): trace captured website module imports

Compose verified exported scripts, inert native import syntax and a narrow
Chromium resolution port. Preserve query/fragment identity, import-map context,
all reported capture candidates and explicit unknown execution. Share named
CLI/MCP contracts and retain native reports, diagnostics and cleanup failures.

Add focused boundary regressions and a real module-loading oracle to the
existing conditional Chrome lane. No captured application code is executed
by module tracing, and no selected website asset is refetched.

Refs #851, #774

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

* fix(browser): preserve module contexts and source bindings

Keep capture completeness inline, validate actual source text against its
digest, and separate unsupported URL contexts from malformed input.
Use the importer origin for native module resolution and the selected map
base independently, including mixed HTTP/HTTPS and escaped HTML attributes.

Refs #851, #774

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
ysopwnable
2026-10-07 14:59:52 +08:00
committed by GitHub
parent 507e8b3c7b
commit 01be082e9e
48 changed files with 2911 additions and 21 deletions
+1
View File
@@ -13,6 +13,7 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "export_web_scripts"
| "trace_web_module_imports"
| "analyze_javascript_application",
readonly reason:
| "cancelled"
+1
View File
@@ -3,6 +3,7 @@ export type BrowserObservationOperation =
| "list_browser_targets"
| "inspect_web_page"
| "analyze_web_bundle"
| "trace_web_module_imports"
| "observe_web_session"
| "discover_webmcp_tools"
| "compare_web_captures"
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import {
collectWebModuleImports,
matchCapturedModules,
} from "./webModuleImports.js";
import { exportedWebScriptSchema } from "./webScriptExport.js";
describe("native module syntax observations", () => {
it("collects native imports and re-exports, preserving empty strings and computed unknowns", () => {
const source =
'import ""; import x from "./x.js"; export * from "./all.js"; export {x} from "pkg"; import(`./literal.js`); import(`./${name}.js`); import(expr);';
const result = collectWebModuleImports(source);
expect(result.state).toBe("parsed");
expect(result.imports.map((item) => [item.kind, item.specifier])).toEqual([
["static-import", ""],
["static-import", "./x.js"],
["re-export", "./all.js"],
["re-export", "pkg"],
["dynamic-import", "./literal.js"],
["dynamic-import", null],
["dynamic-import", null],
]);
for (const item of result.imports)
expect(source.slice(item.start.offset, item.end.offset)).toBe(
item.expression,
);
});
it("excludes erased TypeScript imports/exports and bundler inference", () => {
const result = collectWebModuleImports(
'import type {T} from "types"; import {type X} from "also-types"; export type {T} from "export-types"; export {type Y} from "only-types"; import {type T, value} from "mixed"; __webpack_require__.e(4); __vitePreload(() => 1, ["chunk.js"]);',
);
expect(result.imports.map((item) => item.specifier)).toEqual(["mixed"]);
});
it("uses UTF-16 source locations after astral characters", () => {
const source = 'const emoji = "😀";\nimport "./x.js";';
const item = collectWebModuleImports(source).imports[0];
expect(item?.start).toEqual({
offset: source.indexOf('"./x.js"'),
line: 2,
column: 7,
});
});
it("reports unparseable input without asserting an empty complete graph", () => {
const result = collectWebModuleImports('import "./ok.js"; function {');
expect(result).toMatchObject({ state: "unparseable", imports: [] });
expect(result.diagnostics.length).toBeGreaterThan(0);
});
});
const script = (
url: string,
kind: "page-script" | "scenario-response",
sha256 = "a".repeat(64),
) =>
exportedWebScriptSchema.parse({
url,
source:
kind === "page-script"
? {
kind,
script_key: "script1",
frame_id: null,
is_module: true,
language: "JavaScript",
source_map_url: null,
}
: {
kind,
transaction_id: "txn",
request_sequence: 1,
response_sequence: 2,
status: 200,
},
content: {
state: "exported",
relative_path: "modules/a.js",
layout: "isolated",
layout_reason: "fixture",
sha256,
bytes: 1,
media_type: "text/javascript",
redacted: false,
representation:
kind === "page-script"
? "debugger-source-utf8"
: "browser-decoded-response-bytes",
},
});
describe("captured module candidates", () => {
it("keeps query versions separate and response fragment matching weaker", () => {
const scripts = [
script("https://app.test/a.js?v=1#one", "page-script"),
script("https://app.test/a.js?v=1#two", "page-script"),
script("https://app.test/a.js?v=1", "scenario-response"),
script("https://app.test/a.js?v=2", "scenario-response"),
];
expect(
matchCapturedModules("https://app.test/a.js?v=1#one", scripts).map(
(item) => [item.script_index, item.match],
),
).toEqual([
[0, "exact-reported-url"],
[2, "response-url-without-fragment"],
]);
});
it("preserves every captured version at the same URL and never picks one", () => {
const url = "https://app.test/a.js";
const candidates = matchCapturedModules(url, [
script(url, "scenario-response"),
script(url, "scenario-response", "b".repeat(64)),
]);
expect(candidates).toHaveLength(2);
expect(
matchCapturedModules(
"https://app.test/lazy.js",
candidates.map((item) => item.script),
),
).toEqual([]);
});
});
+132
View File
@@ -0,0 +1,132 @@
import { traverseFast, isStringLiteral, isTemplateLiteral } from "@babel/types";
import type { Node } from "@babel/types";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import type { WebModuleImport } from "./webModuleTrace.js";
import type { ExportedWebScript } from "./webScriptExport.js";
/** Collect native import syntax, excluding erased type-only references. */
export const collectWebModuleImports = (
source: string,
): {
readonly imports: readonly WebModuleImport[];
readonly state: "parsed" | "unparseable";
readonly diagnostics: readonly string[];
} => {
const ast = parseJavaScriptSource(source);
if (ast === null)
return {
imports: [],
state: "unparseable",
diagnostics: ["Source could not be parsed; imports are unknown."],
};
const imports: WebModuleImport[] = [];
const add = (kind: WebModuleImport["kind"], expression: Node): void => {
if (
expression.start === null ||
expression.start === undefined ||
expression.end === null ||
expression.end === undefined ||
expression.loc === null ||
expression.loc === undefined
)
return;
const specifier = isStringLiteral(expression)
? expression.value
: isTemplateLiteral(expression) && expression.expressions.length === 0
? (expression.quasis[0]?.value.cooked ?? null)
: null;
imports.push({
kind,
specifier,
expression: source.slice(expression.start, expression.end),
start: {
offset: expression.start,
line: expression.loc.start.line,
column: expression.loc.start.column,
},
end: {
offset: expression.end,
line: expression.loc.end.line,
column: expression.loc.end.column,
},
});
};
traverseFast(ast, (node) => {
if (node.type === "ImportDeclaration") {
if (node.importKind === "type" || node.importKind === "typeof") return;
if (
node.specifiers.length > 0 &&
node.specifiers.every(
(s) =>
s.type === "ImportSpecifier" &&
(s.importKind === "type" || s.importKind === "typeof"),
)
)
return;
add("static-import", node.source);
} else if (
node.type === "ExportAllDeclaration" ||
node.type === "ExportNamedDeclaration"
) {
if (
node.exportKind === "type" ||
node.source === null ||
node.source === undefined
)
return;
if (
node.type === "ExportNamedDeclaration" &&
node.specifiers.length > 0 &&
node.specifiers.every(
(s) => s.type === "ExportSpecifier" && s.exportKind === "type",
)
)
return;
add("re-export", node.source);
} else if (node.type === "ImportExpression")
add("dynamic-import", node.source);
else if (
node.type === "CallExpression" &&
node.callee.type === "Import" &&
node.arguments[0] !== undefined
)
add("dynamic-import", node.arguments[0]);
});
imports.sort((a, b) => a.start.offset - b.start.offset);
return {
imports,
state: "parsed",
diagnostics: ast.errors?.map((error) => error.message) ?? [],
};
};
/** Match reported URLs without collapsing query or module fragment identity. */
export const matchCapturedModules = (
url: string,
scripts: readonly ExportedWebScript[],
) => {
const candidates: {
script_index: number;
match: "exact-reported-url" | "response-url-without-fragment";
script: ExportedWebScript;
}[] = [];
scripts.forEach((script, script_index) => {
if (script.url === url)
candidates.push({ script_index, match: "exact-reported-url", script });
else if (script.source.kind === "scenario-response") {
try {
const transport = new URL(url);
transport.hash = "";
if (transport.href === script.url)
candidates.push({
script_index,
match: "response-url-without-fragment",
script,
});
} catch (cause: unknown) {
void cause;
}
}
});
return candidates;
};
+126
View File
@@ -0,0 +1,126 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import {
exportedWebScriptSchema,
webScriptExportManifestSchema,
} from "./webScriptExport.js";
/** Inspect one captured script's native ES module relationships. */
export const webModuleTraceInputSchema = z.strictObject({
manifest_path: z
.string()
.min(1)
.describe("Absolute path to an export_web_scripts manifest"),
script_index: z
.number()
.int()
.min(0)
.describe("Zero-based index in manifest.scripts"),
importer_url: z
.string()
.min(1)
.optional()
.describe(
"Explicit HTTP(S) module URL; useful when captured inline/base context is unknown",
),
import_map: z
.strictObject({
path: z
.string()
.min(1)
.describe("Absolute local import-map JSON path; no fetch"),
base_url: z
.string()
.min(1)
.describe("Explicit HTTP(S) base for the selected map"),
})
.optional(),
});
export type WebModuleTraceInput = z.output<typeof webModuleTraceInputSchema>;
/** Byte identity of one selected local artifact. */
export const webModuleFileSchema = z.strictObject({
path: z.string().min(1),
sha256: digestSchema,
bytes: z.number().int().min(0),
});
export type WebModuleFile = z.output<typeof webModuleFileSchema>;
const positionSchema = z.strictObject({
offset: z.number().int().min(0),
line: z.number().int().min(1),
column: z.number().int().min(0),
});
/** Parser observations do not assert that a dependency was loaded. */
export const webModuleImportSchema = z.strictObject({
kind: z.enum(["static-import", "re-export", "dynamic-import"]),
specifier: z.string().nullable(),
expression: z.string(),
start: positionSchema,
end: positionSchema,
});
export type WebModuleImport = z.output<typeof webModuleImportSchema>;
/** Native resolver output, including the engine's exact failure text. */
export const webModuleResolutionSchema = z.discriminatedUnion("state", [
z.strictObject({ state: z.literal("resolved"), url: z.string().min(1) }),
z.strictObject({ state: z.literal("rejected"), message: z.string() }),
]);
export type WebModuleResolution = z.output<typeof webModuleResolutionSchema>;
const candidateSchema = z.strictObject({
script_index: z.number().int().min(0),
match: z.enum(["exact-reported-url", "response-url-without-fragment"]),
script: exportedWebScriptSchema,
});
/** Complete outgoing imports with captured candidates and explicit unknowns. */
export const webModuleTraceResultSchema = z.strictObject({
manifest: webModuleFileSchema.extend({
reported_output_directory: z.string(),
...webScriptExportManifestSchema.pick({
capture_path: true,
capture_sha256: true,
capture_kind: true,
capture_completeness: true,
source_evidence_id: true,
}).shape,
}),
source: webModuleFileSchema.extend({
script_index: z.number().int().min(0),
script: exportedWebScriptSchema,
}),
importer: z.strictObject({
url: z.string().min(1),
basis: z.enum(["caller-selected", "reported-source-url"]),
}),
import_map: webModuleFileSchema
.extend({ base_url: z.string().min(1) })
.nullable(),
parser: z.strictObject({
state: z.enum(["parsed", "unparseable"]),
diagnostics: z.array(z.string()),
location_units: z.literal("UTF-16 offsets and columns; one-based lines"),
}),
engine: z
.strictObject({ id: z.string().min(1), version: z.string().min(1) })
.nullable(),
imports: z.array(
webModuleImportSchema.extend({
resolution: z.union([
webModuleResolutionSchema,
z.strictObject({
state: z.literal("unknown"),
reason: z.literal("computed-specifier"),
}),
]),
captured_candidates: z.array(candidateSchema),
execution: z.literal("unknown"),
}),
),
diagnostics: z.array(z.string()),
limitations: z.array(z.string()),
});
export type WebModuleTraceResult = z.output<typeof webModuleTraceResultSchema>;