Merge remote-tracking branch 'origin/main' into feat/2072-ines-container

This commit is contained in:
64579525
2026-10-12 20:56:36 +08:00
88 changed files with 15887 additions and 351 deletions
+6
View File
@@ -123,6 +123,12 @@ export interface ProviderRequestActivitySnapshot {
/** Provider session bound to exactly one parsed artifact. */
export interface AnalysisClient extends AnalysisOperationPort {
/** Execute only if this operation can run without loading or starting a provider. */
executeIfReady?(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError> | undefined>;
/** Retained token-verified process snapshots for dynamic providers this client started. */
runtimeLineageSnapshots?(): readonly ProviderRuntimeLineageSnapshot[];
/** Current provider work that may outlive a timed-out or cancelled caller. */
+5 -2
View File
@@ -311,12 +311,15 @@ const detectArtifactFormat = async (
if (lower.endsWith(".app")) return "app-pack";
return zipPackageFormatForPath(lower) ?? "zip";
}
// Binary plists, including keyed archives, often use other extensions.
if (observed.bytesRead === 8 && magic.equals(Buffer.from("bplist00")))
return "plist";
const named = namedArtifactFormat(lower);
if (named !== undefined) return named;
if (
lower.endsWith(".pkg") &&
observed.bytesRead >= 4 &&
magic.subarray(0, 4).toString("ascii") === "xar!"
magic.subarray(0, 4).equals(Buffer.from("xar!"))
)
return "pkg";
if (lower.endsWith(".dmg")) {
@@ -327,7 +330,7 @@ const detectArtifactFormat = async (
const trailer = Buffer.alloc(4);
const read = await handle.read(trailer, 0, trailer.length, size - 512);
throwIfTargetResolutionCancelled(signal);
if (read.bytesRead === 4 && trailer.toString("ascii") === "koly")
if (read.bytesRead === 4 && trailer.equals(Buffer.from("koly")))
return "dmg";
}
}
+4 -7
View File
@@ -504,14 +504,11 @@ const removeManagedSkills = async (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): Promise<UninstallItem> => {
// Every destination shares one summary item, so each result is labeled by
// the directory it refers to.
const results = await Promise.all(
skillDestinations(home, undefined, environment, platform).map(
({ client, path }) =>
removeManagedSkill(
path,
client === "claude_code" ? "Claude Code skill" : "skill",
fileSystem,
),
skillDestinations(home, undefined, environment, platform).map(({ path }) =>
removeManagedSkill(path, path, fileSystem),
),
);
const failed = results.find(({ status }) => status === "failed");
+45
View File
@@ -81,7 +81,9 @@ export class BinarySession
| undefined;
#transition: Promise<void> = Promise.resolve();
#transitionGeneration = 0;
#transitionPending = 0;
readonly #calls = new Map<Promise<unknown>, number>();
readonly #promptCompletionControllers = new Set<AbortController>();
readonly #providerRouter: SessionProviderRouter;
readonly #runtimeUnavailability = new Map<
string,
@@ -532,6 +534,38 @@ export class BinarySession
return call.finally(() => this.#calls.delete(call));
}
/** Run a prompt lookup only against an already connected provider child. */
executeIfProviderReady(
name: Parameters<AnalysisOperationPort["execute"]>[0],
arguments_: Readonly<Record<string, JsonValue>>,
options?: Pick<ExecutionOptions, "signal" | "selectorOrigin">,
): Promise<Result<AnalysisExecution, AnalysisError> | undefined> {
const active = this.#active;
if (
this.#transitionPending > 0 ||
active === undefined ||
active.client.executeIfReady === undefined
)
return Promise.resolve(undefined);
const controller = new AbortController();
this.#promptCompletionControllers.add(controller);
const signal =
options?.signal === undefined
? controller.signal
: AbortSignal.any([controller.signal, options.signal]);
const generation = this.#transitionGeneration;
const call = active.client.executeIfReady(name, arguments_, {
...options,
signal,
});
this.#calls.set(call, generation);
return call.finally(() => {
this.#calls.delete(call);
this.#promptCompletionControllers.delete(controller);
});
}
/** Admit one composed request until its result and session bookkeeping settle. */
withAdmittedAnalysis<Value>(
operationName: string,
@@ -728,6 +762,9 @@ export class BinarySession
#serialize<T>(
operation: (admittedThrough: number) => Promise<T>,
): Promise<T> {
for (const controller of this.#promptCompletionControllers)
controller.abort();
this.#transitionPending += 1;
// Later calls wait for this transition and must not be included in its drain.
const admittedThrough = this.#transitionGeneration++;
const result = this.#transition.then(
@@ -738,6 +775,14 @@ export class BinarySession
() => undefined,
() => undefined,
);
void result.then(
() => {
this.#transitionPending -= 1;
},
() => {
this.#transitionPending -= 1;
},
);
return result;
}
@@ -14,6 +14,7 @@ import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { WorkflowSnapshotRecordInput } from "./BinarySessionRecords.js";
import type {
AnalysisExecution,
AnalysisOperation,
AnalysisOperationPort,
ExecutionOptions,
@@ -35,6 +36,12 @@ export interface SavedAnalysisSnapshot {
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
export interface BinarySessionPort
extends AnalysisOperationPort, InvestigationRecordPort {
/** Execute only against a positively ready, already-created provider client. */
executeIfProviderReady(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: Pick<ExecutionOptions, "signal" | "selectorOrigin">,
): Promise<Result<AnalysisExecution, AnalysisError> | undefined>;
/** Hold the active target binding through a complete composed operation. */
withAdmittedAnalysis<Value>(
operationName: string,
@@ -94,6 +94,15 @@ export class CompositeProvider implements AnalysisProvider {
return outcomes.find((outcome) => !outcome.ok) ?? ok(null);
};
return {
executeIfReady: (operation, parameters, options) => {
const provider = this.#providerByOperation.get(operation);
const client =
provider === undefined ? undefined : clients.get(provider);
return (
client?.executeIfReady?.(operation, parameters, options) ??
Promise.resolve(undefined)
);
},
execute: (operation, parameters, options) => {
if (operation === "health")
return Promise.resolve(
@@ -79,6 +79,14 @@ class LazyAnalysisClient implements AnalysisClient {
#loading: Promise<AnalysisClient> | undefined;
#closed = false;
executeIfReady: NonNullable<AnalysisClient["executeIfReady"]> = (
operation,
parameters,
options,
) =>
this.#client?.executeIfReady?.(operation, parameters, options) ??
Promise.resolve(undefined);
constructor(loadClient: () => Promise<AnalysisClient>, providerId: string) {
this.#loadClient = loadClient;
this.#providerId = providerId;
+2 -2
View File
@@ -179,7 +179,7 @@ const classifyRootFormat = async (
if (hasZipSignature(prefix)) return zipRootPackageFormat(lower);
if (
lower.endsWith(".pkg") &&
prefix.subarray(0, 4).toString("ascii") === "xar!"
prefix.subarray(0, 4).equals(Buffer.from("xar!"))
)
return "pkg";
if (lower.endsWith(".dmg") && (await hasKolyTrailer(handle))) return "dmg";
@@ -199,5 +199,5 @@ const hasKolyTrailer = async (handle: FileHandle): Promise<boolean> => {
if (size < 512) return false;
const trailer = Buffer.alloc(4);
const read = await handle.read(trailer, 0, trailer.length, size - 512);
return read.bytesRead === 4 && trailer.toString("ascii") === "koly";
return read.bytesRead === 4 && trailer.equals(Buffer.from("koly"));
};
@@ -39,7 +39,9 @@ it("preserves an already captured response shape without marking it unavailable"
},
},
});
events.ingestResponseBody("request-1", {
const candidate = events.responseBodyRequests()[0];
expect(candidate).toBeDefined();
events.ingestResponseBody(candidate!, {
body: '{"response":true}',
base64Encoded: false,
});
@@ -62,7 +64,7 @@ it("preserves an already captured response shape without marking it unavailable"
capturedShape,
);
expect(events.network.get("request-1")?.body_shapes.status).toBe("included");
expect(events.responseBodyRequestIds()).toEqual([]);
expect(events.responseBodyRequests()).toEqual([]);
expect(events.completeness.snapshot().unavailable_sections).not.toContain(
"json_body_shapes",
);
+72 -10
View File
@@ -7,11 +7,18 @@ import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
import * as handlers from "./CdpCaptureEventHandlers.js";
import { isJsonMediaType } from "./CdpCaptureEventHelpers.js";
import { recordValue } from "./CdpCaptureValues.js";
import { cdpStringValue, recordValue } from "./CdpCaptureValues.js";
export interface ResponseBodyCandidate {
readonly requestId: string;
readonly occurrence: number;
}
/** Event accumulator that validates and normalizes payloads at ingestion. */
export class CdpCaptureEvents implements CdpCaptureEventsState {
#scriptMetadataBudgetExclusionsRecorded = false;
readonly #networkRequestOccurrences = new Map<string, number>();
readonly #responseBodyExaminedOccurrences = new Map<string, number>();
readonly scripts = new Map<string, CapturedScript>();
readonly scriptMetadataBudgetOmissionsById = new Map<string, true>();
rejectedScriptMetadataBudgetCount = 0;
@@ -64,6 +71,8 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
this.executionContextFrames.clear();
this.network.clear();
this.networkRequestTimestamps.clear();
this.#networkRequestOccurrences.clear();
this.#responseBodyExaminedOccurrences.clear();
this.malformedRedirectRequestIds.clear();
this.webSocketConnectionsById.clear();
this.console.length = 0;
@@ -128,9 +137,18 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
case "Debugger.scriptParsed":
handlers.handleScriptParsed(this, params);
break;
case "Network.requestWillBeSent":
case "Network.requestWillBeSent": {
const requestId = cdpStringValue(params.requestId);
const previous =
requestId === undefined ? undefined : this.network.get(requestId);
handlers.handleRequestWillBeSent(this, params);
if (requestId !== undefined && this.network.get(requestId) !== previous)
this.#networkRequestOccurrences.set(
requestId,
(this.#networkRequestOccurrences.get(requestId) ?? 0) + 1,
);
break;
}
case "Network.responseReceived":
handlers.handleResponseReceived(this, params);
break;
@@ -165,24 +183,68 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
: null;
}
responseBodyRequestIds(): readonly string[] {
responseBodyRequests(): readonly ResponseBodyCandidate[] {
if (!this.input.include_json_body_shapes) return [];
return [...this.network.values()]
.filter(
(request) => !this.malformedRedirectRequestIds.has(request.request_id),
)
.filter((request) => isJsonMediaType(request.mime_type))
.map((request) => request.request_id);
.flatMap((request) => {
const occurrence = this.#networkRequestOccurrences.get(
request.request_id,
);
return occurrence === undefined
? []
: [{ requestId: request.request_id, occurrence }];
});
}
responseBodyUnavailable(requestId: string): void {
if (this.malformedRedirectRequestIds.has(requestId)) return;
bodyShapes.updateResponseBodyShape(this, requestId, null);
currentResponseBodyRequest(
candidate: ResponseBodyCandidate,
): NetworkState | undefined {
if (
candidate.occurrence !==
this.#networkRequestOccurrences.get(candidate.requestId)
)
return undefined;
return this.network.get(candidate.requestId);
}
responseBodyUnavailable(candidate: ResponseBodyCandidate): void {
if (this.currentResponseBodyRequest(candidate) === undefined) return;
this.#responseBodyExaminedOccurrences.set(
candidate.requestId,
candidate.occurrence,
);
if (this.malformedRedirectRequestIds.has(candidate.requestId)) return;
bodyShapes.updateResponseBodyShape(this, candidate.requestId, null);
this.completeness.unavailable("json_body_shapes");
}
ingestResponseBody(requestId: string, value: unknown): void {
if (this.malformedRedirectRequestIds.has(requestId)) return;
bodyShapes.ingestResponseBodyShape(this, requestId, value);
/**
* Mark eligible response bodies that arrived after the fetch pass was
* enumerated.
*/
settleUnexaminedResponseBodies(): void {
for (const candidate of this.responseBodyRequests()) {
const request = this.currentResponseBodyRequest(candidate);
if (
request?.body_shapes.response === null &&
this.#responseBodyExaminedOccurrences.get(candidate.requestId) !==
candidate.occurrence
)
this.responseBodyUnavailable(candidate);
}
}
ingestResponseBody(candidate: ResponseBodyCandidate, value: unknown): void {
if (this.currentResponseBodyRequest(candidate) === undefined) return;
this.#responseBodyExaminedOccurrences.set(
candidate.requestId,
candidate.occurrence,
);
if (this.malformedRedirectRequestIds.has(candidate.requestId)) return;
bodyShapes.ingestResponseBodyShape(this, candidate.requestId, value);
}
}
+18 -14
View File
@@ -153,6 +153,7 @@ const captureAuthorizedPage = async (
);
if (!input.include_storage_keys)
state.events.completeness.exclude("storage_keys", "not_approved", null);
await report(context.progress, 3, "Normalizing browser evidence");
const completedFrameResult = await authorizedMainFrame({
connection: context.connection,
sessionId: context.sessionId,
@@ -165,7 +166,10 @@ const captureAuthorizedPage = async (
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
if (state.events.navigationDuringCapture || completedUrl !== attachedUrl)
throw new BrowserObservationError("inspect_web_page", "target_changed");
await report(context.progress, 3, "Normalizing browser evidence");
// Body IDs were enumerated before asynchronous CDP reads. Events remain
// enabled through the final capture, so account for eligible responses that
// arrived while those reads were pending.
state.events.settleUnexaminedResponseBodies();
state.events.recordScriptMetadataBudgetExclusions();
return {
inspection: normalizedInspection(state, {
@@ -185,14 +189,14 @@ const captureAuthorizedPage = async (
const captureJsonResponseBodies = async (
state: CaptureState,
): Promise<void> => {
const requestIds = state.events.responseBodyRequestIds();
for (let index = 0; index < requestIds.length; index += 1) {
const requestId = requestIds[index];
if (requestId === undefined) continue;
const request = state.events.network.get(requestId);
if (request === undefined) continue;
if (request.encoded_data_length === null) {
state.events.responseBodyUnavailable(requestId);
const requests = state.events.responseBodyRequests();
for (let index = 0; index < requests.length; index += 1) {
const candidate = requests[index];
if (candidate === undefined) continue;
const current = state.events.currentResponseBodyRequest(candidate);
if (current === undefined) continue;
if (current.encoded_data_length === null) {
state.events.responseBodyUnavailable(candidate);
continue;
}
let result: unknown;
@@ -200,7 +204,7 @@ const captureJsonResponseBodies = async (
result = await optionalCdpCommand(
state.context,
"Network.getResponseBody",
{ requestId },
{ requestId: candidate.requestId },
state.limitations,
);
} catch (cause: unknown) {
@@ -211,17 +215,17 @@ const captureJsonResponseBodies = async (
cause.reportedMessage === null
)
throw cause;
state.events.responseBodyUnavailable(requestId);
state.events.responseBodyUnavailable(candidate);
state.limitations.push(
`Response body unavailable for request ${requestId}: ${cause.userMessage}`,
`Response body unavailable for request ${candidate.requestId}: ${cause.userMessage}`,
);
continue;
}
if (result !== undefined) {
state.events.ingestResponseBody(requestId, result);
state.events.ingestResponseBody(candidate, result);
continue;
}
for (const remaining of requestIds.slice(index))
for (const remaining of requests.slice(index))
state.events.responseBodyUnavailable(remaining);
return;
}
+4 -6
View File
@@ -16,6 +16,7 @@ import { logCliCommand } from "../cliLogging.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { registerProjectManagedApplicationGraph } from "./managedProjectGraphCommand.js";
import { managedMembersInputSchema } from "../contracts/managed/managedToolContracts.js";
export const registerManagedCommands = (
cli: CliInstance,
@@ -60,12 +61,9 @@ const registerInspectManagedMembers = (
path: z.string().describe("Managed PE executable or assembly path"),
}),
options: z.object({
type: z
.array(z.string())
.optional()
.describe(
"Inspect only members declared by this exact type full name, such as System.Threading.Monitor; a nested type is named by its bare name, which selects every nested type of that name (repeatable)",
),
type: managedMembersInputSchema.shape.type_names.describe(
"Inspect only members declared by this exact type full name, such as System.Threading.Monitor; a nested type is named by its bare name, which selects every nested type of that name (repeatable)",
),
}),
run: ({ args, options }) =>
logCliCommand(logger, "inspect-managed-members", () =>
@@ -1,172 +1,200 @@
import { describe, expect, it } from "vitest";
import { expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
describe("Electron API identity", () => {
it("recovers APIs through an ES module default import of Electron", () => {
const analysis = analyzeJavaScriptStaticSource(`
import electron from "electron";
const { ipcMain } = electron;
new electron.BrowserWindow({ webPreferences: { preload: "./preload.js" } });
electron.contextBridge.exposeInMainWorld("api", { ping: true });
electron.ipcRenderer.invoke("default:ping");
ipcMain.handle("destructured:ping", () => "pong");
electron.default.ipcMain.handle("nested-default", () => "local");
`);
it("recovers APIs through an ES module default import of Electron", () => {
const analysis = analyzeJavaScriptStaticSource(`
import electron from "electron";
const { ipcMain } = electron;
new electron.BrowserWindow({ webPreferences: { preload: "./preload.js" } });
electron.contextBridge.exposeInMainWorld("api", { ping: true });
electron.ipcRenderer.invoke("default:ping");
ipcMain.handle("destructured:ping", () => "pong");
electron.default.ipcMain.handle("nested-default", () => "local");
`);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: "./preload.js" },
]);
expect(analysis.electron.context_bridge_apis).toMatchObject([
{ api_key: "api", members: ["ping"] },
]);
expect(
analysis.electron.ipc.map(({ side, operation, channel }) => ({
side,
operation,
channel,
})),
).toEqual([
{ side: "renderer", operation: "invoke", channel: "default:ping" },
{ side: "main", operation: "handle", channel: "destructured:ping" },
]);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: "./preload.js" },
]);
expect(analysis.electron.context_bridge_apis).toMatchObject([
{ api_key: "api", members: ["ping"] },
]);
expect(
analysis.electron.ipc.map(({ side, operation, channel }) => ({
side,
operation,
channel,
})),
).toEqual([
{ side: "renderer", operation: "invoke", channel: "default:ping" },
{ side: "main", operation: "handle", channel: "destructured:ping" },
]);
});
it("recovers APIs and sender checks written with optional chaining", () => {
const analysis = analyzeJavaScriptStaticSource(`
const { contextBridge, ipcMain, utilityProcess } = require("electron");
contextBridge?.exposeInMainWorld("api", {});
utilityProcess?.fork("./worker.js");
ipcMain?.handle("optional:ping", (event) => {
if (!event.senderFrame?.url.startsWith("file://")) return null;
return event.sender?.getURL() === "file:///index.html";
});
`);
expect(analysis.electron.context_bridge_apis).toMatchObject([
{ api_key: "api" },
]);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: "./worker.js" },
]);
expect(analysis.electron.ipc).toMatchObject([
{ side: "main", operation: "handle", channel: "optional:ping" },
]);
expect(
analysis.electron.sender_validations.map(
({ subject, mechanism, expected }) => ({
subject,
mechanism,
expected: expected.value,
}),
),
).toEqual([
{
subject: "sender-url",
mechanism: "call:startsWith",
expected: "file://",
},
{
subject: "sender-url",
mechanism: "comparison:===",
expected: "file:///index.html",
},
]);
});
it("preserves empty and computed literal contextBridge member keys", () => {
const analysis = analyzeJavaScriptStaticSource(`
const { contextBridge } = require("electron");
const dynamicKey = getKey();
contextBridge.exposeInMainWorld("api", {
"": { nested: { "": true } },
["computed"]: true,
});
contextBridge.exposeInMainWorld("dynamic", {
[dynamicKey]: true,
});
`);
const finding = analysis.electron.context_bridge_apis.find(
({ api_key }) => api_key === "api",
);
expect(finding).toMatchObject({
api_status: "object-literal",
members: ["", ".nested", ".nested.", "computed"],
unknown_members: 0,
});
it("recovers APIs and sender checks written with optional chaining", () => {
const analysis = analyzeJavaScriptStaticSource(`
const { contextBridge, ipcMain, utilityProcess } = require("electron");
contextBridge?.exposeInMainWorld("api", {});
utilityProcess?.fork("./worker.js");
ipcMain?.handle("optional:ping", (event) => {
if (!event.senderFrame?.url.startsWith("file://")) return null;
return event.sender?.getURL() === "file:///index.html";
});
`);
expect(analysis.electron.context_bridge_apis).toMatchObject([
{ api_key: "api" },
]);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: "./worker.js" },
]);
expect(analysis.electron.ipc).toMatchObject([
{ side: "main", operation: "handle", channel: "optional:ping" },
]);
expect(
analysis.electron.sender_validations.map(
({ subject, mechanism, expected }) => ({
subject,
mechanism,
expected: expected.value,
}),
),
).toEqual([
{
subject: "sender-url",
mechanism: "call:startsWith",
expected: "file://",
},
{
subject: "sender-url",
mechanism: "comparison:===",
expected: "file:///index.html",
},
]);
});
it("follows bundler namespace interop helpers without accepting other writes", () => {
const analysis = analyzeJavaScriptStaticSource(`
var __toESM = (mod) => mod;
var __importStar = (mod) => mod;
let electron = require("electron");
electron = __toESM(electron);
new electron.BrowserWindow({ webPreferences: { preload: "./rolldown.js" } });
var import_electron = __toESM(require("electron"));
new import_electron.BrowserWindow({ webPreferences: { preload: "./esbuild.js" } });
function _interopRequireWildcard(mod) { return mod; }
const Electron = __importStar(require("electron"));
new Electron.BrowserWindow({ webPreferences: { preload: "./tsc.js" } });
let replaced = require("electron");
replaced = __toESM(require("./fake"));
new replaced.BrowserWindow({ webPreferences: { preload: "./replaced.js" } });
let rewritten = require("electron");
rewritten = __toESM(rewritten);
rewritten = fake;
new rewritten.BrowserWindow({ webPreferences: { preload: "./rewritten.js" } });
const babel = _interopRequireWildcard(require("electron"));
new babel.BrowserWindow({ webPreferences: { preload: "./babel.js" } });
function nested() {
const __toESM = (mod) => mod;
const scoped = __toESM(require("electron"));
new scoped.BrowserWindow({ webPreferences: { preload: "./nested.js" } });
}
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./rolldown.js", "./esbuild.js", "./tsc.js", "./babel.js"]);
});
it("does not trust unbound helper names or non-function helper values", () => {
const analysis = analyzeJavaScriptStaticSource(`
const __toESM = makeLookalike();
const electron = __toESM(require("electron"));
new electron.BrowserWindow({});
let unbound = require("electron");
unbound = __importStar(unbound);
new unbound.BrowserWindow({});
`);
expect(analysis.electron.browser_windows).toEqual([]);
});
it("follows stable declaration aliases but not an assigned default parameter", () => {
const analysis = analyzeJavaScriptStaticSource(`
const direct = require("electron");
const constAlias = direct;
new constAlias.BrowserWindow({webPreferences:{preload:"./const.js"}});
let letAlias = require("electron");
new letAlias.BrowserWindow({webPreferences:{preload:"./let.js"}});
const { BrowserWindow } = require("electron");
new BrowserWindow({webPreferences:{preload:"./destructured.js"}});
function withDefault(electron = require("./not-electron")) {
if (flag) electron = require("electron");
new electron.BrowserWindow({webPreferences:{preload:"./default.js"}});
}
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./const.js", "./let.js", "./destructured.js"]);
});
it("preserves one initializer across variable redeclarations without accepting writes", () => {
const analysis = analyzeJavaScriptStaticSource(`
var electron;
var electron = require("electron");
var electron;
new electron.BrowserWindow({webPreferences:{preload:"./redeclared.js"}});
var replaced;
var replaced = require("electron");
replaced = fake;
new replaced.BrowserWindow({webPreferences:{preload:"./replaced.js"}});
var initializedTwice = require("electron");
var initializedTwice = fake;
new initializedTwice.BrowserWindow({});
var conditional;
if (flag) { var conditional = require("electron"); }
new conditional.BrowserWindow({});
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./redeclared.js"]);
});
expect(finding?.resolution_basis).toBeUndefined();
expect(analysis.electron.context_bridge_apis).toContainEqual(
expect.objectContaining({
api_key: "dynamic",
unknown_members: 1,
}),
);
});
it("follows bundler namespace interop helpers without accepting other writes", () => {
const analysis = analyzeJavaScriptStaticSource(`
var __toESM = (mod) => mod;
var __importStar = (mod) => mod;
let electron = require("electron");
electron = __toESM(electron);
new electron.BrowserWindow({ webPreferences: { preload: "./rolldown.js" } });
var import_electron = __toESM(require("electron"));
new import_electron.BrowserWindow({ webPreferences: { preload: "./esbuild.js" } });
function _interopRequireWildcard(mod) { return mod; }
const Electron = __importStar(require("electron"));
new Electron.BrowserWindow({ webPreferences: { preload: "./tsc.js" } });
let replaced = require("electron");
replaced = __toESM(require("./fake"));
new replaced.BrowserWindow({ webPreferences: { preload: "./replaced.js" } });
let rewritten = require("electron");
rewritten = __toESM(rewritten);
rewritten = fake;
new rewritten.BrowserWindow({ webPreferences: { preload: "./rewritten.js" } });
const babel = _interopRequireWildcard(require("electron"));
new babel.BrowserWindow({ webPreferences: { preload: "./babel.js" } });
function nested() {
const __toESM = (mod) => mod;
const scoped = __toESM(require("electron"));
new scoped.BrowserWindow({ webPreferences: { preload: "./nested.js" } });
}
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./rolldown.js", "./esbuild.js", "./tsc.js", "./babel.js"]);
});
it("does not trust unbound helper names or non-function helper values", () => {
const analysis = analyzeJavaScriptStaticSource(`
const __toESM = makeLookalike();
const electron = __toESM(require("electron"));
new electron.BrowserWindow({});
let unbound = require("electron");
unbound = __importStar(unbound);
new unbound.BrowserWindow({});
`);
expect(analysis.electron.browser_windows).toEqual([]);
});
it("follows stable declaration aliases but not an assigned default parameter", () => {
const analysis = analyzeJavaScriptStaticSource(`
const direct = require("electron");
const constAlias = direct;
new constAlias.BrowserWindow({webPreferences:{preload:"./const.js"}});
let letAlias = require("electron");
new letAlias.BrowserWindow({webPreferences:{preload:"./let.js"}});
const { BrowserWindow } = require("electron");
new BrowserWindow({webPreferences:{preload:"./destructured.js"}});
function withDefault(electron = require("./not-electron")) {
if (flag) electron = require("electron");
new electron.BrowserWindow({webPreferences:{preload:"./default.js"}});
}
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./const.js", "./let.js", "./destructured.js"]);
});
it("preserves one initializer across variable redeclarations without accepting writes", () => {
const analysis = analyzeJavaScriptStaticSource(`
var electron;
var electron = require("electron");
var electron;
new electron.BrowserWindow({webPreferences:{preload:"./redeclared.js"}});
var replaced;
var replaced = require("electron");
replaced = fake;
new replaced.BrowserWindow({webPreferences:{preload:"./replaced.js"}});
var initializedTwice = require("electron");
var initializedTwice = fake;
new initializedTwice.BrowserWindow({});
var conditional;
if (flag) { var conditional = require("electron"); }
new conditional.BrowserWindow({});
`);
expect(
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
).toEqual(["./redeclared.js"]);
});
@@ -4,6 +4,7 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { ElectronStaticValue } from "./electronStaticAnalysisTypes.js";
import {
readExactJavaScriptLiteral,
semanticStaticPropertyKey,
semanticStaticPropertyName,
} from "./javascriptAstValues.js";
import { sourceSlice } from "./javascriptStaticAnalysisHelpers.js";
@@ -124,7 +125,7 @@ export const collectContextBridgeMembers = (
members: [],
unknown: 0,
};
collectMembersAt(node, "", 0, state);
collectMembersAt(node, [], state);
const members = [...new Set(state.members)].sort(compareUnicodeCodePoints);
return {
status: "object-literal",
@@ -135,11 +136,10 @@ export const collectContextBridgeMembers = (
const collectMembersAt = (
object: t.ObjectExpression,
prefix: string,
depth: number,
prefix: readonly string[],
state: { members: string[]; unknown: number },
): void => {
if (depth >= 8) {
if (prefix.length >= 8) {
state.unknown += 1;
return;
}
@@ -148,15 +148,16 @@ const collectMembersAt = (
state.unknown += 1;
continue;
}
const name = semanticStaticPropertyName(property.key, property.computed);
if (name === "" || property.computed) {
const name = semanticStaticPropertyKey(property.key, property.computed);
if (name === null) {
state.unknown += 1;
continue;
}
const path = prefix === "" ? name : `${prefix}.${name}`;
const segments = [...prefix, name];
const path = segments.join(".");
state.members.push(path);
if (t.isObjectProperty(property) && t.isObjectExpression(property.value))
collectMembersAt(property.value, path, depth + 1, state);
collectMembersAt(property.value, segments, state);
}
};
@@ -503,6 +503,38 @@ it("resolves renamed default and namespace import helpers from their syntax", ()
.every((step) => step.label.length > 0),
).toBe(true);
});
it("resolves an empty bootstrap module key through an exported Electron bridge", () => {
const result = analyzeJavaScriptStaticSource(`(() => {
const modules = {
""(module) { module.exports = require("electron"); },
9(module, exports, load) {
const electron = load("");
electron.contextBridge.exposeInMainWorld("desktop", {
copy: () => electron.ipcRenderer.send("test:empty-module"),
});
},
};
function load(id) {
const module = { exports: {} };
modules[id].call(module.exports, module, module.exports, load);
return module.exports;
}
load(9);
})();`);
expect(result.bundler_registrations).toMatchObject([
{
entry_module_keys: ["9"],
modules: [{ module_key: "" }, { module_key: "9" }],
},
]);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
entry: "desktop.copy",
channel: "test:empty-module",
terminal: "electron.ipcRenderer.send",
}),
);
});
it("does not trust helper names or follow returns after a definite throw", () => {
for (const helper of [
`function __toESM() {return {ipcRenderer:{send(){}}}}`,
@@ -13,6 +13,7 @@ import type {
} from "./javascriptStaticAnalysisTypes.js";
import {
readExactJavaScriptLiteral,
semanticStaticPropertyKey,
semanticStaticPropertyName,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
@@ -131,15 +132,15 @@ export const moduleFactory = (
/** Derive a literal or explicitly computed module key. */
export const modulePropertyName = (
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
): string =>
t.isObjectMethod(property) || t.isObjectProperty(property)
? property.computed &&
!t.isStringLiteral(property.key) &&
!t.isNumericLiteral(property.key)
? `[computed@${String(property.start ?? -1)}]`
: semanticStaticPropertyName(property.key, property.computed) ||
`[unknown@${String(property.start ?? -1)}]`
): string => {
if (!t.isObjectMethod(property) && !t.isObjectProperty(property))
return `[unknown@${String(property.start ?? -1)}]`;
const key = semanticStaticPropertyKey(property.key, property.computed);
if (key !== null) return key;
return property.computed
? `[computed@${String(property.start ?? -1)}]`
: `[unknown@${String(property.start ?? -1)}]`;
};
/** Read the factory-local bundler require parameter when declared. */
export const factoryRequireName = (
+28 -1
View File
@@ -115,6 +115,7 @@ export class GhidraClient {
#lastDiagnostics: Readonly<Record<string, JsonValue>> = {};
#startupController: AbortController | undefined;
#startPromise: Promise<GhidraStartResult> | undefined;
#ready = false;
#closePromise: Promise<void> | undefined;
readonly #failure = bindGhidraSessionFailure(
() => this.#diagnostics(),
@@ -216,7 +217,8 @@ export class GhidraClient {
void started.then(
(result) => {
signal?.removeEventListener("abort", onAbort);
if (!result.ok) reset();
if (result.ok) this.#ready = true;
else reset();
},
(cause: unknown) => {
this.#logger.debug(
@@ -293,6 +295,20 @@ export class GhidraClient {
);
}
/** Dispatch against the connected bridge without invoking startup or retry. */
callToolIfReady(
operation: GhidraOperation,
parameters: Readonly<Record<string, JsonValue>>,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<JsonValue, GhidraSessionError> | undefined> {
if (!this.isReady()) return Promise.resolve(undefined);
return this.#requestQueue.run(
operation,
parameters,
options.signal === undefined ? {} : { signal: options.signal },
);
}
/** Read the private immutable source for format parsers that require captured bytes. */
readTargetSnapshot(
maximumBytes?: number,
@@ -416,6 +432,16 @@ export class GhidraClient {
}
}
/** True only after the authenticated startup handshake has completed. */
isReady(): boolean {
return (
this.#ready &&
this.#socket !== undefined &&
!this.#socket.destroyed &&
this.#closePromise === undefined
);
}
#cleanupError(cause: unknown): AnalysisError {
if (cause instanceof AnalysisError && cause.cleanupIncomplete) return cause;
return new ProviderCleanupError(
@@ -462,6 +488,7 @@ export class GhidraClient {
}
#requestClose(forceStop: boolean): Promise<void> {
this.#ready = false;
const starting = this.#startPromise;
const controller = this.#startupController;
controller?.abort();
+58 -13
View File
@@ -108,6 +108,7 @@ export type GhidraProviderClientFactory = (
Partial<
Pick<
GhidraClient,
| "callToolIfReady"
| "operationHealthSnapshot"
| "runtimeLineage"
| "readTargetSnapshot"
@@ -667,6 +668,40 @@ export const createGhidraProviderClient = (input: {
startupTimeoutMs: config.ghidraStartupTimeoutMs,
})
: undefined;
const projectExecution = (
operation: AnalysisOperation,
normalized: JsonValue,
rawResult: JsonValue,
observationLimitations: readonly string[] = [],
) => {
const relationshipCoverage = relationshipCoverageFor(operation);
return createAnalysisExecution(normalized, committedProfile.provider, {
rawResult,
analysisProfile: committedProfile,
...(relationshipCoverage === undefined ? {} : { relationshipCoverage }),
limitations: [
...limitationsFor(operation),
...observationLimitations,
...sessionLimitations(),
],
});
};
const inventoryExecution = (
operation: "list_documents" | "list_procedures",
called: Result<JsonValue, GhidraSessionError>,
) => {
if (!called.ok)
return err(
projectSessionError(
operation,
called.error,
config.ghidraStartupTimeoutMs,
),
);
const parsed = parseGhidraInventoryResult(operation, called.value);
if (!parsed.ok) return parsed;
return ok(projectExecution(operation, parsed.value, called.value));
};
return {
execute: async (operation, parameters, options) => {
if (extensionFailure !== undefined) return err(extensionFailure);
@@ -724,6 +759,8 @@ export const createGhidraProviderClient = (input: {
? {}
: { progress: options.progress }),
});
if (operation === "list_documents" || operation === "list_procedures")
return inventoryExecution(operation, called);
if (!called.ok)
return err(
projectSessionError(
@@ -827,22 +864,30 @@ export const createGhidraProviderClient = (input: {
if (!attested.ok) return attested;
normalized = attested.value;
}
const relationshipCoverage = relationshipCoverageFor(operation);
return ok(
createAnalysisExecution(normalized, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
...(relationshipCoverage === undefined
? {}
: { relationshipCoverage }),
limitations: [
...limitationsFor(operation),
...observationLimitations,
...sessionLimitations(),
],
}),
projectExecution(
operation,
normalized,
called.value,
observationLimitations,
),
);
},
executeIfReady: async (operation, parameters, options) => {
if (operation !== "list_documents" && operation !== "list_procedures")
return undefined;
if (extensionFailure !== undefined) return err(extensionFailure);
const input = parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
if (client.callToolIfReady === undefined) return undefined;
const called = await client.callToolIfReady(
operation,
input.value,
options?.signal === undefined ? {} : { signal: options.signal },
);
if (called === undefined) return undefined;
return inventoryExecution(operation, called);
},
operationHealthSnapshot: () => client.operationHealthSnapshot?.(),
runtimeLineageSnapshots: () => {
const observation = client.runtimeLineage?.() ?? null;
+35 -2
View File
@@ -121,6 +121,7 @@ export class HopperClient {
#launcherFailureDiagnostic: HopperStartupFailureDiagnostic | undefined;
#operationFailure: OperationFailureRecord | undefined;
#startupController: AbortController | undefined;
#ready = false;
#startupFailureResult: AnalysisError | undefined;
#runId: string | undefined;
#startPromise: Promise<Result<HopperServerInfo, AnalysisError>> | undefined;
@@ -257,6 +258,16 @@ export class HopperClient {
};
}
/** True only after the authenticated health handshake has completed. */
isReady(): boolean {
return (
this.#ready &&
this.#socket !== undefined &&
!this.#socket.destroyed &&
this.#closePromise === undefined
);
}
/** Launch the bridge once and complete its authenticated health handshake. */
start(
signal?: AbortSignal,
@@ -292,7 +303,7 @@ export class HopperClient {
if (!result.ok) {
this.#rememberStartupFailure(result.error);
reset();
}
} else this.#ready = true;
},
(cause: unknown) => {
this.#logger.debug(
@@ -466,7 +477,28 @@ export class HopperClient {
): Promise<Result<JsonValue, AnalysisError>> {
const started = await this.start(options.signal);
if (!started.ok) return started;
const result = await this.#request(name, arguments_, options);
return this.#normalizeToolResult(
name,
await this.#request(name, arguments_, options),
);
}
/** Dispatch against the connected bridge without invoking startup or retry. */
callToolIfReady(
name: string,
arguments_: Readonly<Record<string, JsonValue>> = {},
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<JsonValue, AnalysisError> | undefined> {
if (!this.isReady()) return Promise.resolve(undefined);
return this.#request(name, arguments_, options).then((result) =>
this.#normalizeToolResult(name, result),
);
}
#normalizeToolResult(
name: string,
result: Result<JsonValue, AnalysisError>,
): Result<JsonValue, AnalysisError> {
return !result.ok &&
result.error instanceof HopperRemoteError &&
result.error.diagnosticType === "capability_unavailable"
@@ -579,6 +611,7 @@ export class HopperClient {
options: HopperClientCloseOptions = {},
): Promise<Result<null, AnalysisError>> {
this.#closing = true;
this.#ready = false;
try {
return await cleanupHopperSession({
socket: this.#socket,
+54 -32
View File
@@ -5,6 +5,7 @@ import { accessSync, constants, statSync } from "node:fs";
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
import type {
AnalysisClient,
AnalysisOperation,
AnalysisClientContext,
AnalysisProfileResolutionOptions,
AnalysisProviderCandidate,
@@ -16,6 +17,7 @@ import type {
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { AppConfig } from "../config/types.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "pino";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
@@ -251,6 +253,40 @@ export class HopperProvider implements AnalysisProviderCandidate {
this.logger.info(diagnostic, "Hopper bridge reported a diagnostic"),
});
const regexSearch = new HopperRegexSearch(client);
const projectExecution = (
operation: AnalysisOperation,
normalized: JsonValue,
rawResult: JsonValue | null = null,
) =>
createAnalysisExecution(normalized, executionProvider, {
// Only the file-offset mapping differs from Hopper's reply.
rawResult,
...(profile === undefined ? {} : { analysisProfile: profile }),
...(operation === "procedure_callers" ||
operation === "procedure_callees"
? { relationshipCoverage: { status: "complete" as const } }
: {}),
limitations: [
...(preparedImage === undefined
? []
: [
"REA loaded a verified thin Mach-O slice from the original FAT64 source. Identity and file offsets refer to the original file. The owned temporary image and its Hopper document close together, including on MCP shutdown.",
]),
...(CAPABILITIES.find(
(descriptor) => descriptor.operation === operation,
)?.limitations ?? []),
...(operation === "read_bytes"
? [
"Hopper byte reads stop at the containing segment's exclusive end; a readable prefix is returned with complete=false when the requested range crosses it.",
]
: []),
...(operation === "procedure_references"
? [
"Native CallReference classifications and unresolved targets are preserved. Detailed reference flags and coverage beyond reported CallReference objects remain unknown.",
]
: []),
],
});
return {
execute: async (operation, parameters, options) => {
const result =
@@ -265,40 +301,26 @@ export class HopperProvider implements AnalysisProviderCandidate {
? await mapHopperFileOffset(target, result.value, options?.signal)
: result;
return mapped.ok
? {
ok: true,
value: createAnalysisExecution(mapped.value, executionProvider, {
// Only the file-offset mapping differs from Hopper's reply.
rawResult: mapped === result ? null : result.value,
...(profile === undefined ? {} : { analysisProfile: profile }),
...(operation === "procedure_callers" ||
operation === "procedure_callees"
? { relationshipCoverage: { status: "complete" as const } }
: {}),
limitations: [
...(preparedImage === undefined
? []
: [
"REA loaded a verified thin Mach-O slice from the original FAT64 source. Identity and file offsets refer to the original file. The owned temporary image and its Hopper document close together, including on MCP shutdown.",
]),
...(CAPABILITIES.find(
(descriptor) => descriptor.operation === operation,
)?.limitations ?? []),
...(operation === "read_bytes"
? [
"Hopper byte reads stop at the containing segment's exclusive end; a readable prefix is returned with complete=false when the requested range crosses it.",
]
: []),
...(operation === "procedure_references"
? [
"Native CallReference classifications and unresolved targets are preserved. Detailed reference flags and coverage beyond reported CallReference objects remain unknown.",
]
: []),
],
}),
}
? ok(
projectExecution(
operation,
mapped.value,
mapped === result ? null : result.value,
),
)
: mapped;
},
executeIfReady: async (operation, parameters, options) => {
if (operation !== "list_documents" && operation !== "list_procedures")
return undefined;
const result = await client.callToolIfReady(
operation,
parameters,
options?.signal === undefined ? {} : { signal: options.signal },
);
if (result === undefined || !result.ok) return result;
return ok(projectExecution(operation, result.value));
},
runtimeLineageSnapshots: () => {
const observation = client.runtimeLineage();
return observation === null
+80
View File
@@ -116,6 +116,86 @@ describe("headless IDA producer pagination", () => {
});
describe("attached IDA observation semantics", () => {
it("returns cold and pending startup calls immediately, then cancels queued work before dispatch", async () => {
const { producer, client } = await fixture("headless");
await expect(client.executeIfReady("list_procedures", {})).resolves.toBe(
undefined,
);
expect(producer.connects).toBe(0);
let enterOpen: (() => void) | undefined;
let finishOpen: (() => void) | undefined;
const openEntered = new Promise<void>((resolve) => {
enterOpen = resolve;
});
const openGate = new Promise<void>((resolve) => {
finishOpen = resolve;
});
producer.beforeCall = async (name) => {
if (name === "idb_open") {
enterOpen?.();
await openGate;
}
};
const startup = client.execute("list_procedures", {});
await openEntered;
await expect(client.executeIfReady("list_strings", {})).resolves.toBe(
undefined,
);
expect(
producer.calls.filter(({ name }) => name === "idb_open"),
).toHaveLength(1);
finishOpen?.();
const started = await startup;
if (!started.ok) throw started.error;
const warm = await client.executeIfReady("list_procedures", {});
if (warm === undefined) throw new Error("expected ready IDA dispatch");
if (!warm.ok) throw warm.error;
expect(warm.value.result).toEqual([
expect.objectContaining({ address: "0x1000", value: "main" }),
]);
let enterRead: (() => void) | undefined;
let finishRead: (() => void) | undefined;
const readEntered = new Promise<void>((resolve) => {
enterRead = resolve;
});
const readGate = new Promise<void>((resolve) => {
finishRead = resolve;
});
producer.beforeCall = async (name) => {
if (name === "list_funcs") {
enterRead?.();
await readGate;
}
};
const active = client.execute("list_procedures", {});
await readEntered;
const controller = new AbortController();
const queued = client.executeIfReady(
"list_strings",
{},
{
signal: controller.signal,
},
);
controller.abort();
await expect(queued).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
finishRead?.();
const activeResult = await active;
if (!activeResult.ok) throw activeResult.error;
expect(
producer.calls.filter(({ name }) => name === "list_funcs"),
).toHaveLength(3);
expect(producer.calls.some(({ name }) => name === "find_regex")).toBe(
false,
);
await client.close();
});
it("accepts a normalized spelling of the bound document path", async () => {
const { target, producer, client } = await fixture();
const equivalent =
+30 -1
View File
@@ -1,4 +1,8 @@
import { z } from "zod";
import {
ABORTED,
waitForAbortable,
} from "../application/binary/AbortablePromise.js";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -141,10 +145,35 @@ export class IdaSessionClient implements AnalysisClient {
return call;
}
async executeIfReady(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
if (!this.#openCompleted || this.#closed || this.#closing)
return Promise.resolve(undefined);
const call = this.#tail.then(() => {
if (!this.#openCompleted || this.#closed || this.#closing)
return undefined;
if (wasCancelled(options))
return err(new AnalysisCancelledError(operation));
return this.#execute(operation, parameters, options, true);
});
this.#tail = call.then(
() => undefined,
() => undefined,
);
const result = await waitForAbortable(call, options?.signal);
return result === ABORTED
? err(new AnalysisCancelledError(operation))
: result;
}
async #execute(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
readyOnly = false,
) {
if (this.#closed || this.#closing)
return err(
@@ -202,7 +231,7 @@ export class IdaSessionClient implements AnalysisClient {
parameters,
};
try {
await this.#start();
if (!readyOnly) await this.#start();
const before = await this.#observe(options);
failureContext.metadataBefore = before;
if (wasCancelled(options)) throw new AnalysisCancelledError(operation);
+6 -10
View File
@@ -1,4 +1,4 @@
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -23,7 +23,7 @@ export type PrivateRuntimeRootCapability =
| {
readonly available: true;
readonly reason: null;
readonly proof: "posix-mode-0700";
readonly proof: "posix-mkdtemp-owner-only";
};
/** Report whether this process can establish a private runtime root. */
@@ -32,7 +32,7 @@ export const privateRuntimeRootCapability = (
): PrivateRuntimeRootCapability =>
platform === "win32"
? windowsNativeCapabilities(platform).private_runtime_dacl
: { available: true, reason: null, proof: "posix-mode-0700" };
: { available: true, reason: null, proof: "posix-mkdtemp-owner-only" };
/** Expected failure when a runtime root's privacy boundary is unavailable. */
export class PrivateRuntimeRootUnavailableError extends Error {
@@ -77,13 +77,9 @@ export class PrivateRuntimeRoot {
const path = await mkdtemp(
join(options.parent ?? tmpdir(), options.prefix ?? "rea-provider-"),
);
try {
await chmod(path, 0o700);
return new PrivateRuntimeRoot(path);
} catch (cause: unknown) {
await rm(path, { recursive: true, force: true });
throw cause;
}
// POSIX mkdtemp establishes owner-only access atomically. Return its owner
// without a fallible permission rewrite and rollback after allocation.
return new PrivateRuntimeRoot(path);
}
/**
+33 -3
View File
@@ -1,3 +1,5 @@
import { AsyncLocalStorage } from "node:async_hooks";
import {
McpServer,
isCallToolResult,
@@ -34,6 +36,12 @@ export interface CompactInputSchemaPresentation {
readonly budgetBytes: number;
}
const currentRequestSignal = new AsyncLocalStorage<AbortSignal>();
/** Signal for the completion request currently being dispatched by the SDK. */
export const currentMcpRequestSignal = (): AbortSignal | undefined =>
currentRequestSignal.getStore();
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
@@ -124,6 +132,7 @@ class ErrorEvidenceTransport implements Transport {
onmessage: Transport["onmessage"];
readonly hasPerRequestStream?: boolean;
private readonly pendingTools = new Map<RequestId, string>();
private readonly pendingCompletions = new Map<RequestId, AbortController>();
constructor(
private readonly transport: Transport,
@@ -141,6 +150,8 @@ class ErrorEvidenceTransport implements Transport {
typeof message.params?.["name"] === "string"
)
this.pendingTools.set(message.id, message.params["name"]);
if (isJSONRPCRequest(message) && message.method === "completion/complete")
this.pendingCompletions.set(message.id, new AbortController());
// The SDK suppresses replies after cancellation, so send() cannot release
// this bookkeeping. Keep transport authentication outside retained data.
if (
@@ -148,14 +159,28 @@ class ErrorEvidenceTransport implements Transport {
message.method === "notifications/cancelled"
) {
const id = message.params?.["requestId"];
if (typeof id === "string" || typeof id === "number")
if (typeof id === "string" || typeof id === "number") {
this.pendingTools.delete(id);
this.pendingCompletions.get(id)?.abort();
this.pendingCompletions.delete(id);
}
}
this.onmessage?.(message, extra);
const completion =
isJSONRPCRequest(message) && message.method === "completion/complete"
? this.pendingCompletions.get(message.id)
: undefined;
if (completion === undefined) this.onmessage?.(message, extra);
else
currentRequestSignal.run(completion.signal, () =>
this.onmessage?.(message, extra),
);
};
transport.onerror = (error) => this.onerror?.(error);
transport.onclose = () => {
this.pendingTools.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
this.onclose?.();
};
}
@@ -176,6 +201,9 @@ class ErrorEvidenceTransport implements Transport {
await this.transport.close();
} finally {
this.pendingTools.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
}
}
@@ -211,8 +239,10 @@ class ErrorEvidenceTransport implements Transport {
await this.transport.send({ ...recovered, result }, options);
} else await this.transport.send(recovered, options);
} finally {
if (!isJSONRPCRequest(message) && id !== undefined)
if (!isJSONRPCRequest(message) && id !== undefined) {
this.pendingTools.delete(id);
this.pendingCompletions.delete(id);
}
}
}
+39 -4
View File
@@ -2,9 +2,11 @@ import type { EvidenceReader } from "../application/investigation/InvestigationR
import { z } from "zod";
import { uniqueSorted } from "../domain/canonicalOrdering.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import type { PromptCompletionKind } from "../contracts/promptContracts.js";
import { currentMcpRequestSignal } from "./EvidenceMcpServer.js";
import { artifactInventoryResultSchema } from "../domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
import { parseProcessCapture } from "../domain/process/processCaptureParsing.js";
@@ -57,9 +59,13 @@ const completionCandidates = async (
): Promise<readonly string[]> => {
switch (kind) {
case "document":
return documentCandidates(analysis);
return documentCandidates(analysis, session);
case "procedure":
return procedureCandidates(analysis, context?.arguments?.document);
return procedureCandidates(
analysis,
session,
context?.arguments?.document,
);
case "provider":
return providerCandidates(session);
case "evidence":
@@ -74,8 +80,15 @@ const completionCandidates = async (
const documentCandidates = async (
analysis: AnalysisOperationPort,
session: BinarySessionPort | undefined,
): Promise<readonly string[]> => {
const result = await analysis.execute("list_documents", {});
const result = await completionInventoryLookup(
analysis,
session,
"list_documents",
{},
);
if (result === undefined) return [];
if (!result.ok) return [];
const parsed = documentListSchema.safeParse(result.value.result);
return parsed.success ? parsed.data : [];
@@ -83,12 +96,19 @@ const documentCandidates = async (
const procedureCandidates = async (
analysis: AnalysisOperationPort,
session: BinarySessionPort | undefined,
document: string | undefined,
): Promise<readonly string[]> => {
const byAddress = new Map<string, string>();
const input =
document === undefined || document.length === 0 ? {} : { document };
const result = await analysis.execute("list_procedures", input);
const result = await completionInventoryLookup(
analysis,
session,
"list_procedures",
input,
);
if (result === undefined) return [];
if (result.ok) {
const parsed = z
.array(z.object({ address: z.string(), value: z.string() }))
@@ -111,6 +131,21 @@ const procedureCandidates = async (
return candidates;
};
const completionInventoryLookup = async (
analysis: AnalysisOperationPort,
session: BinarySessionPort | undefined,
operation: "list_documents" | "list_procedures",
parameters: Readonly<Record<string, JsonValue>>,
) => {
const signal = currentMcpRequestSignal();
const options = signal === undefined ? {} : { signal };
const result =
session === undefined
? await analysis.execute(operation, parameters, options)
: await session.executeIfProviderReady(operation, parameters, options);
return signal?.aborted === true ? undefined : result;
};
const providerCandidates = (
session: BinarySessionPort | undefined,
): readonly string[] => {
+14 -1
View File
@@ -166,7 +166,7 @@ it("bounds section header bytes while accepting a five-byte size LEB", () => {
"Sections:",
"",
" Type start=0x0000000a end=0x0000000b (size=0x00000001) count: 0",
` Custom start=0x${start.toString(16).padStart(8, "0")} end=0x${(start + 1).toString(16).padStart(8, "0")} (size=0x00000001) "\"`,
` Custom start=0x${start.toString(16).padStart(8, "0")} end=0x${(start + 1).toString(16).padStart(8, "0")} (size=0x00000001) ""`,
"",
"Section Details:",
"",
@@ -211,6 +211,19 @@ it("frames custom section names at their NUL-terminated objdump display", async
/custom-section header/u,
);
});
it("preserves leading U+FEFF as custom-name data, not a debug-name marker", () => {
const parsed = parseWabtWat(
'(module (@custom "\\ef\\bb\\bfsection" "payload") (@custom "\\ef\\bb\\bfname" "payload") (@custom "\\ef\\bb\\bf" "payload") (@custom "" "payload"))',
);
expect(parsed.customSectionNames).toEqual([
"\uFEFFsection",
"\uFEFFname",
"\uFEFF",
"",
]);
expect(parsed.debugModuleNames).toEqual([]);
expect(() => parseWabtWat('(module (@custom "\\ff" "payload"))')).toThrow();
});
it("extracts escaped WAT import/export forms while retaining multiline producer text", async () => {
const text = await readFile(
new URL("../../tests/fixtures/wasm/decoded.wat", import.meta.url),
+5 -3
View File
@@ -147,9 +147,11 @@ export const parseWabtWat = (text: string) => {
if (prefix === null)
throw new Error("Unsupported WABT custom-section name.");
const nameString = watString(form, prefix[0].length);
const name = new TextDecoder("utf-8", { fatal: true }).decode(
nameString.bytes,
);
// A WASM name is length-delimited UTF-8; leading U+FEFF is name data.
const name = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true,
}).decode(nameString.bytes);
customSectionNames.push(name);
if (name === "name") {
const payloadPrefix = /^\s+"/u.exec(form.slice(nameString.end));