refactor(tools): remove artificial analysis ceilings

This commit is contained in:
morluto
2026-09-29 16:29:23 +08:00
parent 36aeec9586
commit 2f08c7c932
202 changed files with 2314 additions and 3072 deletions
+11 -32
View File
@@ -26,10 +26,7 @@ import {
} from "./CdpElectronScriptEvents.js";
import { captureElectronScripts } from "./CdpElectronScripts.js";
import { captureElectronWorkers } from "./CdpElectronWorkers.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "./ElectronFileScope.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
interface ElectronContext {
readonly connection: CdpConnection;
@@ -42,7 +39,6 @@ interface ElectronContext {
}
interface ElectronInspectionState {
readonly roots: readonly string[];
readonly completeness: CdpCaptureCompleteness;
readonly scripts: ElectronScriptDraft[];
readonly executionContextFrames: Map<string, string>;
@@ -51,17 +47,16 @@ interface ElectronInspectionState {
navigationDuringCapture: boolean;
}
/** Passively inspect one root-confined Electron file page. */
/** Passively inspect one Electron file page from the selected CDP endpoint. */
export const inspectCdpElectronPage = async (
context: ElectronContext,
): Promise<ElectronPageInspection> => {
const state: ElectronInspectionState = {
roots: await canonicalElectronRoots(context.input.allowed_file_roots),
completeness: new CdpCaptureCompleteness(),
scripts: [],
executionContextFrames: new Map(),
limitations: [
"Only canonical file paths contained by an approved root are retained.",
"Local file paths exposed by the selected CDP target are retained in the observation.",
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
"Script contents require separate source-capture approval and remain byte bounded.",
],
@@ -150,7 +145,7 @@ const authorizeInitialFrames = async (
context.sessionId,
context.signal,
);
const frames = await captureFrames(result, state.roots, state.completeness);
const frames = await captureFrames(result, state.completeness);
if (frames[0] === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
return frames;
@@ -182,18 +177,13 @@ const captureElectronContent = async (
> => {
await report(context.progress, 2, "Capturing Electron structure");
const frameIds = new Set(frames.map((frame) => frame.frame_id));
const resources = await captureResources(
context,
state.roots,
state.completeness,
);
const dom = await captureDom(context, state.roots, state.completeness);
const resources = await captureResources(context, state.completeness);
const dom = await captureDom(context, state.completeness);
const scripts = await captureElectronScripts({
connection: context.connection,
sessionId: context.sessionId,
...(context.signal === undefined ? {} : { signal: context.signal }),
request: context.input,
roots: state.roots,
scripts: state.scripts,
executionContextFrames: state.executionContextFrames,
frameIds,
@@ -204,7 +194,6 @@ const captureElectronContent = async (
...(context.signal === undefined ? {} : { signal: context.signal }),
target: context.target,
request: context.input,
roots: state.roots,
frameIds,
completeness: state.completeness,
limitations: state.limitations,
@@ -223,7 +212,7 @@ const assertStableMainFrame = async (
context.sessionId,
context.signal,
);
const afterPath = await mainFilePath(result, state.roots);
const afterPath = await mainFilePath(result);
if (afterPath === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
if (state.navigationDuringCapture || afterPath !== expectedPath)
@@ -242,7 +231,6 @@ const navigatedFrameId = (event: CdpEvent): string | undefined => {
const captureFrames = async (
result: unknown,
roots: readonly string[],
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["frames"]> => {
const frameTree = recordValue(requiredRecord(result).frameTree);
@@ -258,10 +246,7 @@ const captureFrames = async (
if (current === undefined) break;
const frame = recordValue(current.tree.frame);
const frameId = stringValue(frame?.id);
const path = await authorizedElectronFile(
stringValue(frame?.url) ?? "",
roots,
);
const path = await authorizedElectronFile(stringValue(frame?.url) ?? "");
if (frameId === undefined || path === undefined) {
completeness.exclude("frames", "out_of_target_scope");
continue;
@@ -279,7 +264,6 @@ const captureFrames = async (
const captureResources = async (
context: ElectronContext,
roots: readonly string[],
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["resources"]> => {
const result = await context.connection.send(
@@ -300,7 +284,6 @@ const captureResources = async (
for (const resource of recordsValue(tree.resources)) {
const path = await authorizedElectronFile(
stringValue(resource.url) ?? "",
roots,
);
if (path === undefined) {
completeness.exclude("resources", "out_of_target_scope");
@@ -332,7 +315,6 @@ const captureResources = async (
const captureDom = async (
context: ElectronContext,
roots: readonly string[],
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["dom"]> => {
const result = requiredRecord(
@@ -350,7 +332,7 @@ const captureDom = async (
let total = 0;
for (const document of recordsValue(result.documents)) {
const documentUrl = stringAt(strings, document.documentURL);
if ((await authorizedElectronFile(documentUrl, roots)) === undefined) {
if ((await authorizedElectronFile(documentUrl)) === undefined) {
completeness.exclude("dom", "out_of_target_scope");
continue;
}
@@ -382,13 +364,10 @@ const captureDom = async (
return { total_nodes: total, nodes };
};
const mainFilePath = async (
result: unknown,
roots: readonly string[],
): Promise<string | undefined> => {
const mainFilePath = async (result: unknown): Promise<string | undefined> => {
const frameTree = recordValue(requiredRecord(result).frameTree);
const frame = recordValue(frameTree?.frame);
return await authorizedElectronFile(stringValue(frame?.url) ?? "", roots);
return await authorizedElectronFile(stringValue(frame?.url) ?? "");
};
const arrayValue = (value: unknown): readonly unknown[] =>
+7 -28
View File
@@ -29,10 +29,7 @@ import {
type CdpTargetSession,
} from "./CdpTargetSession.js";
import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "./ElectronFileScope.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
/** Public identity committed by passive Electron observations. */
export const CDP_ELECTRON_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
@@ -42,7 +39,7 @@ export const CDP_ELECTRON_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
});
const IDENTITY = CDP_ELECTRON_PROVIDER_IDENTITY;
/** Passive Electron provider with canonical file-root confinement. */
/** Passive Electron provider for local file pages exposed by loopback CDP. */
export class CdpElectronProvider implements ElectronObservationPort {
identity(): ProviderIdentity {
return IDENTITY;
@@ -53,14 +50,12 @@ export class CdpElectronProvider implements ElectronObservationPort {
options: ExecutionOptions = {},
): Promise<Result<ElectronTargetList, AnalysisError>> {
try {
const roots = await canonicalElectronRoots(input.allowed_file_roots);
const discovery = await discoverCdpEndpoint(
input.cdp_endpoint,
"list_electron_targets",
options.signal,
);
const allowed = [];
let outsideRoot = 0;
let unsupportedUrl = 0;
let nonPage = 0;
let unconnectable = 0;
@@ -69,10 +64,9 @@ export class CdpElectronProvider implements ElectronObservationPort {
nonPage += 1;
continue;
}
const path = await authorizedElectronFile(target.url, roots);
const path = await authorizedElectronFile(target.url);
if (path === undefined) {
if (isFileUrl(target.url)) outsideRoot += 1;
else unsupportedUrl += 1;
unsupportedUrl += 1;
continue;
}
if (!hasCdpTargetWebSocket(discovery, target)) {
@@ -95,12 +89,11 @@ export class CdpElectronProvider implements ElectronObservationPort {
browser: discovery.version,
targets: allowed,
excluded: {
outside_root: outsideRoot,
unsupported_url: unsupportedUrl,
non_page: nonPage,
},
limitations: [
"Only page targets whose canonical file path is contained by an approved root are listed.",
"Every local file page exposed by the selected loopback CDP endpoint is eligible for listing.",
...(unconnectable === 0
? []
: [
@@ -120,17 +113,12 @@ export class CdpElectronProvider implements ElectronObservationPort {
): Promise<Result<ElectronPageInspection, AnalysisError>> {
let targetSession: CdpTargetSession | undefined;
try {
const roots = await canonicalElectronRoots(input.allowed_file_roots);
const discovery = await discoverCdpEndpoint(
input.cdp_endpoint,
"inspect_electron_page",
options.signal,
);
const target = await authorizeTarget(
discovery.targets,
input.target_id,
roots,
);
const target = await authorizeTarget(discovery.targets, input.target_id);
targetSession = await openCdpTargetSession(
discovery,
target,
@@ -168,27 +156,18 @@ export class CdpElectronProvider implements ElectronObservationPort {
const authorizeTarget = async (
targets: readonly CdpEndpointTarget[],
targetId: string,
roots: readonly string[],
): Promise<CdpEndpointTarget> => {
const target = targets.find(({ id }) => id === targetId);
if (target === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_found");
if (
target.type !== "page" ||
(await authorizedElectronFile(target.url, roots)) === undefined
(await authorizedElectronFile(target.url)) === undefined
)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
return target;
};
const isFileUrl = (value: string): boolean => {
try {
return new URL(value).protocol === "file:";
} catch {
return false;
}
};
const providerError = (
cause: unknown,
operation: BrowserObservationOperation,
+2 -3
View File
@@ -18,14 +18,13 @@ interface ElectronScriptCaptureInput {
readonly sessionId: string | undefined;
readonly signal?: AbortSignal;
readonly request: InspectElectronPageInput;
readonly roots: readonly string[];
readonly scripts: readonly ElectronScriptDraft[];
readonly executionContextFrames: ReadonlyMap<string, string>;
readonly frameIds: ReadonlySet<string>;
readonly completeness: CdpCaptureCompleteness;
}
/** Normalize root-confined script metadata and optionally approved source. */
/** Normalize local script metadata and optionally approved source. */
export const captureElectronScripts = async (
input: ElectronScriptCaptureInput,
): Promise<ElectronPageInspection["scripts"]> => {
@@ -33,7 +32,7 @@ export const captureElectronScripts = async (
const items: ElectronPageInspection["scripts"]["items"] = [];
const seen = new Set<string>();
for (const script of input.scripts) {
const path = await authorizedElectronFile(script.rawUrl, input.roots);
const path = await authorizedElectronFile(script.rawUrl);
if (path === undefined) {
input.completeness.exclude("scripts", "out_of_target_scope");
continue;
+2 -6
View File
@@ -9,13 +9,12 @@ import type { CdpEndpointTarget } from "./CdpEndpoint.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
/** Inventory root-confined worker targets without attaching to them. */
/** Inventory local worker targets without attaching to them. */
export const captureElectronWorkers = async (input: {
readonly connection: CdpConnection;
readonly signal?: AbortSignal;
readonly target: CdpEndpointTarget;
readonly request: InspectElectronPageInput;
readonly roots: readonly string[];
readonly frameIds: ReadonlySet<string>;
readonly completeness: CdpCaptureCompleteness;
readonly limitations: string[];
@@ -47,10 +46,7 @@ export const captureElectronWorkers = async (input: {
input.completeness.exclude("workers", "out_of_target_scope");
continue;
}
const path = await authorizedElectronFile(
stringValue(target.url) ?? "",
input.roots,
);
const path = await authorizedElectronFile(stringValue(target.url) ?? "");
if (path === undefined) {
input.completeness.exclude("workers", "out_of_target_scope");
continue;
+4 -16
View File
@@ -1,21 +1,10 @@
import { realpath } from "node:fs/promises";
import { realpath, stat } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { fileURLToPath } from "node:url";
import { isPathWithinRoot } from "../domain/localPath.js";
/** Canonicalize operator roots before evaluating any Electron file target. */
export const canonicalElectronRoots = async (
roots: readonly string[],
): Promise<readonly string[]> => {
const canonical: string[] = [];
for (const root of roots) canonical.push(await realpath(root));
return [...new Set(canonical)].sort();
};
/** Resolve one file URL and reject host, encoding, and symlink root escapes. */
/** Resolve one local file URL while rejecting remote hosts and encoded separators. */
export const authorizedElectronFile = async (
value: string,
roots: readonly string[],
): Promise<string | undefined> => {
if (/%(?:2f|5c)/iu.test(value)) return undefined;
let url: URL;
@@ -40,11 +29,10 @@ export const authorizedElectronFile = async (
if (!isAbsolute(path) || path.includes("\0")) return undefined;
let canonical: string;
try {
if (!(await stat(path)).isFile()) return undefined;
canonical = await realpath(path);
} catch {
return undefined;
}
return roots.some((root) => isPathWithinRoot(root, canonical))
? canonical
: undefined;
return canonical;
};
+9 -26
View File
@@ -3,39 +3,28 @@ import {
sanitizeBrowserUrl,
} from "../domain/browserObservation.js";
import type { JavaScriptRuntimeLocation } from "../domain/javascriptRuntimeObservation.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "./ElectronFileScope.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
export type RuntimeLocationDecision =
| { readonly allowed: true; readonly location: JavaScriptRuntimeLocation }
| {
readonly allowed: false;
readonly reason:
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
readonly reason: "unsupported_location";
};
/** Canonicalize exact filesystem scopes before Inspector attachment. */
export const canonicalRuntimeRoots = canonicalElectronRoots;
/** Authorize one protocol URL without retaining an out-of-scope value. */
/** Resolve a protocol location exposed by the explicitly selected Inspector endpoint. */
export const authorizeRuntimeLocation = async (
value: string,
roots: readonly string[],
origins: readonly string[],
): Promise<RuntimeLocationDecision> => {
if (value.startsWith("node:") && value.length <= 4_096)
if (value.startsWith("node:") && value.length > 0)
return {
allowed: true,
location: { kind: "builtin", specifier: value },
};
if (value.startsWith("file:")) {
const filePath = await authorizedElectronFile(value, roots);
const filePath = await authorizedElectronFile(value);
return filePath === undefined
? { allowed: false, reason: "outside_file_roots" }
? { allowed: false, reason: "unsupported_location" }
: { allowed: true, location: { kind: "file", file_path: filePath } };
}
let url: URL;
@@ -47,8 +36,8 @@ export const authorizeRuntimeLocation = async (
if (!["http:", "https:"].includes(url.protocol))
return { allowed: false, reason: "unsupported_location" };
const parsedOrigin = browserOriginSchema.safeParse(url.origin);
if (!parsedOrigin.success || !origins.includes(parsedOrigin.data))
return { allowed: false, reason: "outside_origins" };
if (!parsedOrigin.success)
return { allowed: false, reason: "unsupported_location" };
return {
allowed: true,
location: {
@@ -62,10 +51,4 @@ export const authorizeRuntimeLocation = async (
/** Authorize a target whose Node Inspector URL omits its main entry path. */
export const authorizeRuntimeTargetLocation = async (
value: string,
targetType: string,
roots: readonly string[],
origins: readonly string[],
): Promise<RuntimeLocationDecision> =>
// A bare file:// URL contains no source identity. Do not attach to the
// first configured root merely because the target happens to be Node.
authorizeRuntimeLocation(value, roots, origins);
): Promise<RuntimeLocationDecision> => authorizeRuntimeLocation(value);
+3 -14
View File
@@ -10,18 +10,13 @@ import { authorizeRuntimeLocation } from "./JavaScriptRuntimeScope.js";
import type { CaptureState, ScriptDraft } from "./V8InspectorProvider.js";
import type { AuthorizedV8InspectorTarget } from "./V8InspectorEndpoint.js";
type ExclusionReason =
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
type ExclusionReason = "unsupported_location";
/** Empty durable-location exclusion counters. */
export const createInspectorExclusionCounts = (): Record<
ExclusionReason,
number
> => ({
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
});
@@ -30,7 +25,7 @@ export const describeInspectorTargetLimitations = (): string[] => [
"REA attaches to an already-running exact target and never launches, resumes, evaluates, pauses, or mutates it.",
"Only Runtime.enable and Debugger.enable are sent; source text, object values, EventEmitter activity, and Electron IPC are not inspected.",
"Target IDs and locations are authorized, but the Inspector protocol does not authenticate an operating-system process ID or Electron role.",
"Some Electron main targets report only file://; for those targets, the first approved file root is recorded as a scope fallback and script locations are authorized independently.",
"Every target exposed by the selected Inspector endpoint is eligible for observation; target IDs and locations are not authenticated as operating-system process identity.",
"No runtime graph depth is traversed because passive Inspector events do not establish require/import caller edges.",
];
@@ -38,7 +33,6 @@ interface FinalizeCaptureInput {
readonly input: ObserveJavaScriptRuntimeInput;
readonly runtime: JavaScriptRuntimeTargetList["runtime"];
readonly target: AuthorizedV8InspectorTarget;
readonly roots: readonly string[];
readonly state: CaptureState;
}
@@ -47,7 +41,6 @@ export const finalizeInspectorCapture = async ({
input,
runtime,
target,
roots,
state,
}: FinalizeCaptureInput): Promise<JavaScriptRuntimeObservation> => {
const exclusions = createInspectorExclusionCounts();
@@ -56,11 +49,7 @@ export const finalizeInspectorCapture = async ({
JavaScriptRuntimeObservation["scripts"]["items"][number]
>();
for (const draft of state.scripts) {
const decision = await authorizeRuntimeLocation(
draft.rawUrl,
roots,
input.allowed_origins,
);
const decision = await authorizeRuntimeLocation(draft.rawUrl);
if (!decision.allowed) {
exclusions[decision.reason] += 1;
continue;
+5 -23
View File
@@ -25,10 +25,7 @@ import {
delayWithCancellation,
} from "./CdpCaptureValues.js";
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
import {
authorizeRuntimeTargetLocation,
canonicalRuntimeRoots,
} from "./JavaScriptRuntimeScope.js";
import { authorizeRuntimeTargetLocation } from "./JavaScriptRuntimeScope.js";
import {
createInspectorExclusionCounts,
describeInspectorTargetLimitations,
@@ -85,7 +82,6 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
options: ExecutionOptions = {},
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>> {
try {
const roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"list_javascript_runtime_targets",
@@ -94,12 +90,7 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
const allowed: AuthorizedV8InspectorTarget[] = [];
const excluded = createInspectorExclusionCounts();
for (const target of discovery.targets) {
const decision = await authorizeRuntimeTargetLocation(
target.url,
target.type,
roots,
input.allowed_origins,
);
const decision = await authorizeRuntimeTargetLocation(target.url);
if (!decision.allowed) {
excluded[decision.reason] += 1;
continue;
@@ -132,13 +123,12 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>> {
let connection: CdpConnection | undefined;
try {
const roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"observe_javascript_runtime",
options.signal,
);
const target = await authorizedTarget(discovery.targets, input, roots);
const target = await authorizedTarget(discovery.targets, input);
if (input.runtime_kind !== undefined)
assertRuntimeKind(target, input.runtime_kind);
connection = await CdpConnection.connect(
@@ -161,7 +151,6 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
input,
runtime: discovery.runtime,
target,
roots,
state,
});
return ok(javascriptRuntimeObservationSchema.parse(result));
@@ -183,7 +172,6 @@ const projectTarget = (target: AuthorizedV8InspectorTarget) => ({
const authorizedTarget = async (
targets: readonly V8InspectorTarget[],
input: ObserveJavaScriptRuntimeInput,
roots: readonly string[],
): Promise<AuthorizedV8InspectorTarget> => {
const target = targets.find(({ id }) => id === input.target_id);
if (target === undefined)
@@ -191,12 +179,7 @@ const authorizedTarget = async (
"observe_javascript_runtime",
"target_not_found",
);
const decision = await authorizeRuntimeTargetLocation(
target.url,
target.type,
roots,
input.allowed_origins,
);
const decision = await authorizeRuntimeTargetLocation(target.url);
if (
target.attached ||
!decision.allowed ||
@@ -322,8 +305,7 @@ const ingestContext = (
event.method === "Runtime.executionContextCreated"
? "created"
: "destroyed",
origin:
origin !== null && input.allowed_origins.includes(origin) ? origin : null,
origin: origin === "" ? null : origin,
};
const bytes = metadataBytes(draft);
retainEvent(state, bytes);