fix(tools)!: simplify direct invocation and harden boundary contracts (#555)

Remove REA permission grants, scope ceilings, approval confirmations, and inert settings. Preserve selected local evidence, accept caller-chosen commands and paths, and report actual runtime failures.

Harden provider results, schema serialization, snapshot evidence binding, archive paths, source maps, native screenshots, managed EH parsing, and cancellation cleanup. Regenerate tool metadata and document direct invocation.

BREAKING CHANGE: Removed permission configuration and policy commands, approval fields, filesystem scope inputs, and fixed confirmation options. Process capture inherits the host environment and accepts command names; callers must refresh tool schemas and migrate removed fields.
This commit is contained in:
morluto
2026-10-05 20:16:44 +08:00
committed by GitHub
parent 4f099a10f8
commit b5e98915c6
350 changed files with 5347 additions and 10599 deletions
+3 -1
View File
@@ -117,7 +117,9 @@ const browserScript = (port) => `
const { generation } = await response.json();
if (generation <= observedGeneration) return;
observedGeneration = generation;
history.pushState({}, "", "/app/session-" + String(generation));
const sessionUrl = new URL(window.location.href);
sessionUrl.pathname = "/app/session-" + String(generation);
history.pushState({}, "", sessionUrl);
}, 100);
//# sourceMappingURL=/app.js.map
`;
+1 -1
View File
@@ -89,7 +89,7 @@ async function sdkToolCatalog() {
}
}
const auxiliaryProviders = [
new ArtifactProvider(false, false, CATALOG_PLATFORM),
new ArtifactProvider(CATALOG_PLATFORM),
new NativeMacOSProvider(undefined, CATALOG_PLATFORM),
new ManagedStaticProvider(),
].map((provider) => ({
+54 -23
View File
@@ -1,7 +1,6 @@
import { execFile } from "node:child_process";
import { readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname } from "node:path";
import { promisify } from "node:util";
import { browserScenarioSchema } from "../../dist/domain/browserScenario.js";
@@ -18,7 +17,6 @@ const duplicateOriginStorage = (origin) => ({
value: {
source: "literal",
value: "first",
classification: "public",
},
},
],
@@ -31,9 +29,12 @@ const duplicateOriginStorage = (origin) => ({
value: {
source: "literal",
value: "second",
classification: "public",
},
},
{
name: "rea-secret-seed",
value: { source: "secret", secret_id: "verifier_storage" },
},
],
},
],
@@ -43,7 +44,15 @@ const duplicateOriginStorage = (origin) => ({
export function browserScenario(browser, origin) {
return browserScenarioSchema.parse({
browser,
start_url: { url: `${origin}/app`, query: [] },
start_url: {
url: `${origin}/app`,
query: [
{
name: "scenario_token",
value: { source: "secret", secret_id: "verifier_url" },
},
],
},
allowed_origins: [origin],
environment: {
viewport: { width: 1_280, height: 720, device_scale_factor: 1.25 },
@@ -51,7 +60,6 @@ export function browserScenario(browser, origin) {
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
@@ -61,7 +69,6 @@ export function browserScenario(browser, origin) {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
state: "visible",
},
@@ -72,17 +79,21 @@ export function browserScenario(browser, origin) {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
},
],
storage: duplicateOriginStorage(origin),
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: ["token"],
},
secrets: [
{
secret_id: "verifier_url",
environment_variable: "REA_BROWSER_VERIFIER_URL",
},
{
secret_id: "verifier_storage",
environment_variable: "REA_BROWSER_VERIFIER_SECRET",
},
],
capture: {
after_each_step: [
"screenshot",
@@ -115,7 +126,7 @@ export function browserScenario(browser, origin) {
}
/** Run scenario capture through the public one-shot CLI. */
export async function runScenarioCli(scenario, configuration) {
export async function runScenarioCli(scenario) {
const { stdout } = await execute(
process.execPath,
[
@@ -126,16 +137,7 @@ export async function runScenarioCli(scenario, configuration) {
],
{
cwd: process.cwd(),
env: {
...process.env,
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
dirname(scenario.browser.executable_path ?? process.execPath),
]),
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: "[]",
...configuration,
},
env: process.env,
maxBuffer: 64 * 1_024 * 1_024,
},
);
@@ -175,6 +177,35 @@ export function assertScenarioCapture(capture) {
!storageNames.includes("rea-second-seed")
)
throw new Error("Scenario launch did not retain duplicate-origin seeds");
const secretSeed =
final.artifacts.storage.state === "captured"
? final.artifacts.storage.value.local_storage.find(
({ name }) => name === "rea-secret-seed",
)
: undefined;
if (secretSeed?.value_state !== "redacted-secret")
throw new Error("Scenario launch did not redact its declared secret seed");
const finalUrl =
final.artifacts.url.state === "captured"
? final.artifacts.url.value.url
: "";
if (!finalUrl.includes("[REDACTED:verifier_url]"))
throw new Error("Scenario launch did not redact its declared URL secret");
const stepUrl = capture.steps
.map(({ after_url }) => after_url)
.find(({ url }) => url.includes("[REDACTED:verifier_url]"));
if (stepUrl?.redacted !== true)
throw new Error(
"Scenario step URL did not report declared-secret redaction",
);
const eventUrl = capture.events.items
.filter((event) => "url" in event && event.url !== null)
.map((event) => event.url)
.find(({ url }) => url.includes("[REDACTED:verifier_url]"));
if (eventUrl?.redacted !== true)
throw new Error(
"Scenario event URL did not report declared-secret redaction",
);
if (
capture.events.items.length === 0 ||
capture.completeness.equality_eligible !== true
+9 -4
View File
@@ -21,9 +21,6 @@ export async function verifyLargeScreenshotE2e(endpoint, origin) {
PATH: process.env.PATH ?? "/usr/bin:/bin",
REA_LOG_LEVEL: "silent",
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([origin]),
};
let client;
let transport;
@@ -39,7 +36,15 @@ export async function verifyLargeScreenshotE2e(endpoint, origin) {
);
const { stdout } = await promisify(execFile)(
process.execPath,
[entrypoint, "capture-web-screenshot", endpoint, target.id, "--json"],
[
entrypoint,
"capture-web-screenshot",
endpoint,
target.id,
"--allowed-origins",
origin,
"--json",
],
{ env, timeout: 60000, maxBuffer: 72 * 1024 * 1024 },
);
const cliEvidence = parseEvidence(JSON.parse(stdout));
+6 -7
View File
@@ -133,7 +133,7 @@ export function assertBundleAnalysis(result) {
);
}
/** Assert explicitly approved console, JSON, and WebSocket shape capture. */
/** Assert explicitly selected console text and JSON/WebSocket shape capture. */
export function assertSensitiveShapes(result) {
const request = result.network.requests.find(
(item) =>
@@ -151,12 +151,11 @@ export function assertSensitiveShapes(result) {
(event) => event.text_capture.values,
);
if (
!consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
consoleText.some(({ text }) => text.includes("console-secret-value"))
!consoleText.some(({ text }) =>
text.includes("authorization=Bearer console-secret-value"),
)
)
throw new Error(
"Real Chrome approved console text was not safely redacted",
);
throw new Error("Real Chrome selected console text was not preserved");
if (
!result.network.websocket_events.some(
(event) =>
@@ -174,8 +173,8 @@ export function assertSensitiveShapes(result) {
for (const secret of [
"request-body-secret-value",
"response-secret-value",
"request-secret-value",
"websocket-secret-value",
"console-secret-value",
])
if (serialized.includes(secret))
throw new Error(`Approved shape capture retained raw value: ${secret}`);
+1 -24
View File
@@ -332,20 +332,6 @@ async function createTargets(root, includeManaged) {
}
async function runCodex(prompt) {
const mcpEnvironment = [
["REA_BROWSER_OBSERVE_ENABLED", "true"],
[
"REA_BROWSER_CDP_ENDPOINTS_JSON",
JSON.stringify(["http://127.0.0.1:9222"]),
],
[
"REA_BROWSER_ALLOWED_ORIGINS_JSON",
JSON.stringify(["http://127.0.0.1:3000"]),
],
];
const mcpEnvironmentOverride = `mcp_servers.rea.env={${mcpEnvironment
.map(([name, value]) => `${name}=${JSON.stringify(value)}`)
.join(",")}}`;
const arguments_ = [
"exec",
"--ignore-user-config",
@@ -367,21 +353,12 @@ async function runCodex(prompt) {
`mcp_servers.rea.args=${JSON.stringify([join(repositoryRoot, "scripts/rea.mjs"), "mcp"])}`,
"-c",
`mcp_servers.rea.startup_timeout_sec=${String(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds)}`,
"-c",
mcpEnvironmentOverride,
...(optionalModel === undefined ? [] : ["--model", optionalModel]),
prompt,
];
const child = spawn(codex, arguments_, {
cwd: evaluationRoot,
env: {
...process.env,
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify(["http://127.0.0.1:9222"]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
"http://127.0.0.1:3000",
]),
},
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
const events = [];
+8 -34
View File
@@ -12,7 +12,6 @@ import { importManagedReconstructionEvidence } from "../dist/application/Managed
import { planManagedRuntimeCorrelationEvidence } from "../dist/application/ManagedRuntimeCorrelationService.js";
import { projectManagedApplicationGraphEvidence } from "../dist/application/ManagedApplicationGraphService.js";
import { traceApplicationFeatureEvidence } from "../dist/application/JavaScriptApplicationWorkflowService.js";
import { createPermissionAuthority } from "../dist/application/PermissionAuthority.js";
import { MANAGED_STATIC_PROVIDER } from "../dist/application/InvestigationProviders.js";
import { createEvidence } from "../dist/domain/evidence.js";
import {
@@ -250,29 +249,7 @@ try {
assert.equal(obfuscatedMembers.types[0]?.full_name, "Fixture.ꙮType");
assert.equal(obfuscatedMembers.methods[0]?.name, "λ⛧");
assert.equal(obfuscatedMembers.fields[0]?.name, "字段");
const runtimeExecutable = join(workspace, "dotnet");
await writeFile(runtimeExecutable, "#!/bin/sh\n");
const runtimeCeiling = {
capability: "managed_runtime",
roots: [workspace],
executables: [runtimeExecutable],
environment_names: [],
network: "none",
mount: false,
};
const runtimeAuthority = await createPermissionAuthority(
[runtimeCeiling],
[
{
...runtimeCeiling,
grant_id: "administrator:managed_runtime",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
],
);
assert.equal(runtimeAuthority.ok, true);
const runtimeExecutable = process.execPath;
const runtimeMethod = obfuscatedMembers.methods[0];
assert.ok(runtimeMethod);
const obfuscatedMembersEvidence = createEvidence(
@@ -317,14 +294,7 @@ try {
);
assert.equal(reconstructionImport.value.confidence, "inferred");
const runtimePlan = await planManagedRuntimeCorrelationEvidence(
{
policy: () => ({
status: "enabled",
roots: [workspace],
executablePath: runtimeExecutable,
}),
authority: runtimeAuthority.value,
},
{ configuration: () => ({ executablePath: runtimeExecutable }) },
{
static_members: obfuscatedMembersEvidence,
method: {
@@ -350,13 +320,17 @@ try {
assert.equal(runtimePlan.ok, true);
assert.equal(runtimePlan.value.normalized_result.executed, false);
assert.equal(
runtimePlan.value.normalized_result.authority_model.capability,
"managed_runtime",
runtimePlan.value.normalized_result.unsupported_until_executor_exists,
true,
);
assert.equal(
runtimePlan.value.normalized_result.effect_taxonomy.uses_debugger,
true,
);
assert.equal(
runtimePlan.value.normalized_result.requested_runtime.confinement,
"not-established",
);
const left = await fixture("token-drift-left.exe", {
methodName: "StableSemanticSlice",
+2 -7
View File
@@ -58,7 +58,6 @@ try {
if (!target.ok) throw target.error;
const observation = await observeNativeUi(target.value, "observe_native_ui", {
...scope,
observation_approved: true,
});
if (
!observation.ok &&
@@ -83,8 +82,6 @@ try {
"capture_native_ui_scenario",
{
...scope,
observation_approved: true,
actions_approved: true,
restore: "leave-as-is",
screenshot: false,
steps: [
@@ -114,8 +111,6 @@ try {
String(scope.pid),
"--window-id",
String(scope.window_id),
"--observation-approved",
"--actions-approved",
"--restore",
"leave-as-is",
"--steps",
@@ -135,14 +130,14 @@ try {
evidence.normalized_result?.steps?.length !== 2
)
throw new Error(
`Native UI CLI did not preserve the approved scenario: ${JSON.stringify(evidence.error ?? evidence.normalized_result?.steps?.map(({ outcome, reason }) => ({ outcome, reason })))}`,
`Native UI CLI did not preserve the selected scenario: ${JSON.stringify(evidence.error ?? evidence.normalized_result?.steps?.map(({ outcome, reason }) => ({ outcome, reason })))}`,
);
scenarioStatus = "selected-AX-button-action-and-CLI-parity-observed";
}
const mismatch = await observeNativeUi(
{ ...target.value, sha256: "0".repeat(64) },
"observe_native_ui",
{ ...scope, observation_approved: true },
scope,
);
if (mismatch.ok || !mismatch.error.message.includes("target-mismatch"))
throw new Error("Real helper did not reject changed target bytes");
+9 -4
View File
@@ -153,8 +153,6 @@ const verifyManagedRuntimePlan = async ({
],
{
...environment,
REA_MANAGED_RUNTIME_ENABLED: "true",
REA_MANAGED_RUNTIME_ROOTS_JSON: JSON.stringify([workspace]),
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: process.execPath,
},
),
@@ -163,14 +161,21 @@ const verifyManagedRuntimePlan = async ({
managedRuntimePlan.operation !== "plan_managed_runtime_correlation" ||
managedRuntimePlan.provider?.id !== "rea-dotnet-workflows" ||
managedRuntimePlan.normalized_result?.executed !== false ||
managedRuntimePlan.normalized_result?.authority_model?.capability !==
"managed_runtime" ||
managedRuntimePlan.normalized_result?.unsupported_until_executor_exists !==
true ||
managedRuntimePlan.normalized_result?.effect_taxonomy?.attaches_process !==
true ||
managedRuntimePlan.normalized_result?.effect_taxonomy
?.invokes_target_code !== false
)
throw new Error("packaged managed runtime-correlation CLI failed");
if (
managedRuntimePlan.normalized_result?.requested_runtime?.confinement !==
"not-established"
)
throw new Error(
"packaged managed runtime plan claimed unverified confinement",
);
};
const verifyManagedBoundaries = async ({ cli, managedPath, environment }) => {
+49 -30
View File
@@ -35,14 +35,11 @@ import {
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
import { verifyLargeScreenshotE2e } from "./lib/browser-screenshot-e2e.mjs";
const SECRET_VALUES = [
"network-secret-value",
"console-secret-value",
"storage-secret-value",
"websocket-secret-value",
"ax-private-label-value",
];
const REAL_BROWSER_STARTUP_TIMEOUT_MS = 30_000;
const SCENARIO_SECRET_VALUE = "rea-browser-verifier-secret";
const SCENARIO_URL_SECRET_VALUE = "rea-browser-url-verifier-secret";
process.env.REA_BROWSER_VERIFIER_SECRET = SCENARIO_SECRET_VALUE;
process.env.REA_BROWSER_VERIFIER_URL = SCENARIO_URL_SECRET_VALUE;
const verifierRun = createVerifierRun();
const executable = await browserExecutable();
@@ -99,10 +96,25 @@ try {
if (!observed.ok) throw observed.error;
assertObservation(observed.value, site.origin);
const serialized = JSON.stringify(observed.value);
for (const secret of [...SECRET_VALUES, "browser-secret-value"])
if (
!observed.value.target.url.includes("startup=browser-secret-value") ||
!observed.value.network.requests.some((request) =>
request.url.includes("token=network-secret-value"),
)
)
throw new Error(
"Passive browser result did not preserve ordinary URL queries",
);
for (const secret of [
"request-secret-value",
"request-body-secret-value",
"response-secret-value",
"storage-secret-value",
"websocket-secret-value",
])
if (serialized.includes(secret))
throw new Error(
`Passive browser result retained redacted value: ${secret}`,
`Passive browser result included unselected structured data: ${secret}`,
);
const withSource = await provider.inspectPage(
@@ -217,17 +229,12 @@ try {
mode: "connect",
cdp_endpoint: endpoint,
target_id: target,
ownership: "external",
cleanup: "disconnect-only",
},
site.origin,
);
let attachedScenario;
try {
attachedScenario = await runScenarioCli(attachedScenarioInput, {
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: JSON.stringify([site.origin]),
});
attachedScenario = await runScenarioCli(attachedScenarioInput);
} catch (cliError) {
const direct =
await new PlaywrightBrowserScenarioProvider().captureScenario(
@@ -239,12 +246,8 @@ try {
underlying instanceof Error
? `${underlying.name}: ${underlying.message}`
: String(underlying ?? direct.error.message);
const redactedDetails = [...SECRET_VALUES, "browser-secret-value"].reduce(
(message, secret) => message.replaceAll(secret, "<redacted>"),
details,
);
throw new Error(
`Attached browser scenario failed through both CLI and provider: ${redactedDetails}`,
`Attached browser scenario failed through both CLI and provider: ${details}`,
{ cause: cliError },
);
}
@@ -273,9 +276,6 @@ try {
{
mode: "launch",
executable_path: executable,
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
site.origin,
),
@@ -290,13 +290,32 @@ try {
if ([...profilesAfter].some((entry) => !profilesBefore.has(entry)))
throw new Error("Scenario launch retained a temporary browser profile");
assertScenarioCapture(launchedScenario.value);
for (const secret of ["network-secret-value", "websocket-url-secret"])
if (
JSON.stringify([attachedScenario, launchedScenario.value]).includes(
secret,
)
)
throw new Error(`Browser scenario retained sensitive value: ${secret}`);
const scenarioResults = JSON.stringify([
attachedScenario,
launchedScenario.value,
]);
for (const retainedValue of [
"token=network-secret-value",
"token=websocket-url-secret",
"authorization=Bearer console-secret-value",
"websocket-secret-value",
])
if (!scenarioResults.includes(retainedValue))
throw new Error(
`Browser scenario did not preserve selected value: ${retainedValue}`,
);
for (const unselectedValue of [
SCENARIO_SECRET_VALUE,
SCENARIO_URL_SECRET_VALUE,
"request-secret-value",
"request-body-secret-value",
"response-secret-value",
"storage-secret-value",
])
if (scenarioResults.includes(unselectedValue))
throw new Error(
`Browser scenario included unselected structured value: ${unselectedValue}`,
);
const largeScreenshot = await verifyLargeScreenshotE2e(endpoint, site.origin);
process.stdout.write(
+1 -2
View File
@@ -10,7 +10,7 @@ import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const executable = process.env.REA_ELECTRON_EXECUTABLE;
if (executable === undefined || executable.length === 0)
throw new Error(
"REA_ELECTRON_EXECUTABLE must be an absolute path to an approved Electron executable",
"REA_ELECTRON_EXECUTABLE must identify the Electron executable for this verification lane",
);
const repositoryRoot = fileURLToPath(new URL("..", import.meta.url));
@@ -46,7 +46,6 @@ const input = electronActiveObservationInputSchema.parse({
window_index: 1,
},
],
approved: true,
});
const verifierRun = createVerifierRun();
const result = await new PlaywrightElectronActiveProvider().capture(input);
+3 -45
View File
@@ -1,11 +1,9 @@
#!/usr/bin/env node
import { readFile, realpath } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { resolve } from "node:path";
import { PermissionAuthority } from "../dist/application/PermissionAuthority.js";
import { runControlledReplay } from "../dist/application/JavaScriptReplayService.js";
import { createPermissionPolicy } from "../dist/domain/permissionPolicy.js";
import { LinuxJavaScriptReplayRunner } from "../dist/replay/LinuxJavaScriptReplayRunner.js";
import { SystemJavaScriptReplayHost } from "../dist/replay/SystemJavaScriptReplayHost.js";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
@@ -42,18 +40,7 @@ const suppliedRight =
suppliedInput?.right === undefined
? undefined
: await canonicalSide(suppliedInput.right);
const roots = [
...new Set(
suppliedLeft === undefined
? [dirname(leftPath), dirname(rightPath)]
: [...suppliedLeft.modules, ...(suppliedRight?.modules ?? [])].map(
({ path }) => dirname(path),
),
),
];
const policy = {
status: "enabled",
roots,
const configuration = {
nodePath: process.execPath,
bubblewrapPath:
process.env.REA_JAVASCRIPT_REPLAY_BWRAP_PATH ?? "/usr/bin/bwrap",
@@ -64,39 +51,10 @@ const policy = {
process.env.REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH ?? "/usr/bin/systemctl",
shellPath: process.env.REA_JAVASCRIPT_REPLAY_SHELL_PATH ?? "/usr/bin/bash",
};
const ceiling = {
capability: "javascript_replay",
roots,
executables: [
policy.nodePath,
policy.bubblewrapPath,
policy.systemdRunPath,
policy.systemctlPath,
policy.shellPath,
],
environment_names: [],
network: "none",
mount: true,
};
const authority = new PermissionAuthority(
createPermissionPolicy(
[ceiling],
[
{
...ceiling,
grant_id: "administrator:javascript_replay",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
],
),
);
const dependencies = {
policy: () => policy,
configuration: () => configuration,
host: new SystemJavaScriptReplayHost(),
runner: new LinuxJavaScriptReplayRunner(),
authority,
};
const defaultInput = {
mode: "plan",
@@ -15,7 +15,6 @@ const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const root = await realpath(await mkdtemp(join(tmpdir(), "rea-inspector-")));
const environment = {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
};
const client = new Client({
name: "rea-inspector-conformance",