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
+4 -23
View File
@@ -11,7 +11,6 @@ import {
HopperStartError,
HopperTimeoutError,
NoBinaryOpenError,
PermissionRequiredError,
ProviderSelectionError,
ReplayPlanStaleError,
UnknownRegistryError,
@@ -40,19 +39,7 @@ export const analysisErrorRemediationAction = (
if (error instanceof UnknownRegistryError && error.reason === "not-found")
return "Check that the unknown_id belongs to this session, then retry.";
if (error instanceof ReplayPlanStaleError)
return "Review the rebuilt replay plan and explicitly approve its new digest.";
if (error instanceof PermissionRequiredError) {
switch (error.remediation) {
case "configure":
return "Add the exact missing scope beneath the administrator ceiling, then retry.";
case "elicit":
return "Approve the exact missing scope, then retry the operation.";
case "restart":
return "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.";
case "grant":
return "The administrator ceiling already covers this scope; issue a grant for it (a project grant, or the documented auto-grant setting for an unattended environment), then retry.";
}
}
return "Rebuild the replay plan and retry with its current digest.";
return analysisErrorUserMessage(error);
};
@@ -60,7 +47,6 @@ export const analysisErrorCategory = (
error: AnalysisError,
): AnalysisErrorProjection["category"] => {
if (error instanceof ReplayPlanStaleError) return "integrity_mismatch";
if (error instanceof PermissionRequiredError) return "permission_required";
if (
error instanceof ProviderSelectionError &&
error.reason === "provider_unavailable"
@@ -74,7 +60,7 @@ export const analysisErrorCategory = (
error instanceof HopperRemoteError &&
error.diagnosticType === "authorization"
)
return "permission_required";
return "unavailable";
if (error instanceof HopperProcessError || error instanceof HopperStartError)
return "unavailable";
if (error instanceof ArtifactOperationError)
@@ -103,7 +89,7 @@ const artifactErrorCategory = (
if (reason === "integrity") return "integrity_mismatch";
if (reason === "limit") return "truncated";
if (reason === "cancelled") return "cancelled";
if (reason === "policy" || reason === "unavailable") return "unavailable";
if (reason === "unavailable") return "unavailable";
return "execution_failure";
};
@@ -125,8 +111,6 @@ const STATIC_ERROR_CATEGORIES: Readonly<
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof ReplayPlanStaleError)
return "The controlled replay plan changed before execution. Refresh the current state and try again.";
if (error instanceof PermissionRequiredError)
return "This operation needs additional local permission. Review the requested scope and remediation.";
if (error instanceof AnalysisInputError)
return "Analysis input is invalid. Check the arguments and try again.";
const hopperMessage = hopperErrorUserMessage(error);
@@ -225,10 +209,8 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
if (reason === "path")
return "Artifact contains an unsafe or conflicting internal path. Inspect the reported path and correct the artifact before retrying.";
if (reason === "policy")
return "Artifact integrity continuation is disabled by policy. Configure REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true and retry only if continuing after mismatches is approved.";
if (reason === "unavailable")
return "Artifact processing is unavailable for the current target or policy. Check artifact support and required approvals.";
return "Artifact processing is unavailable for the current target or host. Check artifact support and required tools.";
if (reason === "format" || reason === "integrity")
return "Artifact is invalid or has changed. Get a fresh copy and try again.";
return "Artifact could not be read or written. Check file access and try again.";
@@ -268,7 +250,6 @@ const KNOWN_ERROR_TAGS = {
ConfigurationError: true,
NoBinaryOpenError: true,
BinaryTargetError: true,
PermissionRequiredError: true,
ReplayPlanStaleError: true,
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
@@ -9,7 +9,6 @@ import {
HopperRemoteError,
HopperStartError,
HopperTimeoutError,
PermissionRequiredError,
ProviderAdapterError,
ReplayPlanStaleError,
UnknownRegistryError,
@@ -184,53 +183,6 @@ describe("analysis error projection: caller contract", () => {
});
});
it.each([
[
"configure",
false,
false,
"Add the exact missing scope beneath the administrator ceiling, then retry.",
],
[
"elicit",
false,
true,
"Approve the exact missing scope, then retry the operation.",
],
[
"restart",
true,
false,
"Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.",
],
] as const)(
"projects %s permission remediation into stable protocol fields",
(remediation, restartRequired, elicitationSupported, action) => {
const projected = projectAnalysisError(
new PermissionRequiredError({
requested: {
capability: "process_capture",
roots: ["/workspace/evidence.json"],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: "read:evidence",
},
missing: { roots: ["/workspace/evidence.json"] },
ceiling: null,
remediation,
}),
);
expect(projected.remediation).toEqual({
action,
restart_required: restartRequired,
elicitation_supported: elicitationSupported,
});
},
);
it("gives missing residual unknowns lookup-specific remediation", () => {
expect(
projectAnalysisError(new UnknownRegistryError("not-found")),
@@ -245,18 +197,4 @@ describe("analysis error projection: caller contract", () => {
details: { reason: "not-found" },
});
});
it("distinguishes disabled integrity continuation from format support", () => {
expect(
projectAnalysisError(
new ArtifactOperationError("inventory_artifact", "policy"),
),
).toMatchObject({
code: "artifact_operation_failed",
category: "unavailable",
message: expect.stringContaining(
"REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true",
),
});
});
});
+1 -51
View File
@@ -1,8 +1,4 @@
import type { JsonValue } from "./jsonValue.js";
import type {
MissingPermissionScope,
PermissionScope,
} from "./permissionPolicy.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -17,7 +13,6 @@ import {
HopperProcessError,
HopperRemoteError,
HopperTimeoutError,
PermissionRequiredError,
ProviderAdapterError,
ProviderSelectionError,
ReplayPlanStaleError,
@@ -47,12 +42,6 @@ export const projectAnalysisError = (
retryable: RETRYABLE_CODES.has(code),
remediation: {
action: analysisErrorRemediationAction(error),
restart_required:
error instanceof PermissionRequiredError &&
error.remediation === "restart",
...(error instanceof PermissionRequiredError
? { elicitation_supported: error.remediation === "elicit" }
: {}),
},
...(details === undefined ? {} : { details }),
};
@@ -61,7 +50,6 @@ export const projectAnalysisError = (
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
if (error.cleanupIncomplete) return "cleanup_incomplete";
if (error instanceof ReplayPlanStaleError) return "plan_stale";
if (error instanceof PermissionRequiredError) return "permission_required";
if (error instanceof ProviderSelectionError)
return error.reason === "provider_unavailable"
? "provider_unavailable"
@@ -124,8 +112,6 @@ const processCaptureCode = (
): AnalysisErrorProjection["code"] => {
if (error.cleanupIncomplete) return "cleanup_incomplete";
if (error.userCategory === "cancelled") return "cancelled";
if (error.userCategory === "permission_required")
return "permission_required";
return "process_capture_failed";
};
@@ -133,7 +119,6 @@ type SpecializedErrorTag =
| "ArtifactOperationError"
| "BrowserObservationError"
| "EvidenceFileError"
| "PermissionRequiredError"
| "ProcessCaptureError"
| "ProviderSelectionError"
| "ReplayPlanStaleError"
@@ -171,7 +156,6 @@ const staticErrorCode = (
case "ArtifactOperationError":
case "BrowserObservationError":
case "EvidenceFileError":
case "PermissionRequiredError":
case "ProcessCaptureError":
case "ProviderSelectionError":
case "ReplayPlanStaleError":
@@ -214,17 +198,10 @@ const requestErrorDetails = (
};
if (error instanceof ReplayPlanStaleError)
return {
approved_plan_digest: error.approvedDigest,
expected_plan_digest: error.expectedDigest,
actual_plan_digest: error.actualDigest,
application_code_admitted: false,
};
if (error instanceof PermissionRequiredError)
return {
capability: error.requested.capability,
requested: scopeDetails(error.requested),
missing: missingScopeDetails(error.missing),
ceiling: error.ceiling === null ? null : scopeDetails(error.ceiling),
};
return undefined;
};
@@ -339,33 +316,6 @@ const lifecycleErrorDetails = (
return undefined;
};
const scopeDetails = (
scope: PermissionScope,
): Readonly<Record<string, JsonValue>> => ({
capability: scope.capability,
roots: [...scope.roots],
executables: [...scope.executables],
environment_names: [...scope.environment_names],
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
network: scope.network,
mount: scope.mount,
});
const missingScopeDetails = (
scope: MissingPermissionScope,
): Readonly<Record<string, JsonValue>> => ({
...(scope.roots === undefined ? {} : { roots: [...scope.roots] }),
...(scope.executables === undefined
? {}
: { executables: [...scope.executables] }),
...(scope.environment_names === undefined
? {}
: { environment_names: [...scope.environment_names] }),
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
...(scope.network === undefined ? {} : { network: scope.network }),
...(scope.mount === undefined ? {} : { mount: scope.mount }),
});
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
"invalid_request",
"provider_timeout",
+82
View File
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
type AnalysisSnapshot,
analysisSnapshotSchema,
analysisQueryId,
parseAnalysisSnapshot,
snapshotBinding,
snapshotEvidenceForQuery,
snapshotTarget,
@@ -85,7 +87,9 @@ describe("analysis snapshot contract", () => {
expect(parsed.entries).toHaveLength(10_001);
});
});
describe("analysis snapshot Evidence binding", () => {
it("finds only Evidence committed to the exact binding and profile", () => {
const evidence = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
@@ -133,4 +137,82 @@ describe("analysis snapshot contract", () => {
}),
).toBeUndefined();
});
it("rejects cached execution data that differs from its bundled Evidence", () => {
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const parameters = { address: "0x1000", document: "main" };
const result = { name: "main" };
const rawResult = { name: "provider-main" };
const subject = {
path: ANALYSIS_SNAPSHOT_TARGET.path,
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
format: ANALYSIS_SNAPSHOT_TARGET.format,
architecture: ANALYSIS_SNAPSHOT_TARGET.architecture ?? null,
};
const entry = {
query_id: analysisQueryId(target, binding, "address_name", parameters),
operation: "address_name",
parameters,
execution: {
result,
raw_result: rawResult,
provider: binding.provider,
limitations: ["fixture limitation"],
locations: [{ kind: "address" as const, address: "0x1000" }],
subject,
},
};
const evidence = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
binding.provider,
{
operation: entry.operation,
parameters,
result,
rawResult,
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
limitations: entry.execution.limitations,
locations: entry.execution.locations,
},
);
const snapshot = {
target,
binding,
entries: [entry],
evidence_bundle: createEvidenceBundle([evidence]),
};
expect(parseAnalysisSnapshot(snapshot)).toEqual(snapshot);
const legacy = parseAnalysisSnapshot({
...snapshot,
evidence_bundle: createEvidenceBundle([]),
});
expect(legacy.entries).toEqual([]);
const alterations = [
(altered: typeof snapshot) => {
const entry = altered.entries[0];
if (entry === undefined) throw new TypeError("missing fixture entry");
entry.execution.result = { name: "tampered" };
},
(altered: typeof snapshot) => {
const entry = altered.entries[0];
if (entry === undefined) throw new TypeError("missing fixture entry");
entry.execution.raw_result = { name: "tampered" };
},
(altered: typeof snapshot) => {
const subject = altered.entries[0]?.execution.subject;
if (subject !== null && subject !== undefined)
subject.path = "/different/path";
},
];
for (const alter of alterations) {
const altered = structuredClone(snapshot);
alter(altered);
expect(() => parseAnalysisSnapshot(altered)).toThrow(
/differs from its Evidence record/u,
);
}
});
});
+118 -1
View File
@@ -284,6 +284,8 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
"Analysis snapshot evidence contains records for another target",
);
const ids = new Set<string>();
const boundEntries: AnalysisSnapshotEntry[] = [];
const index = createEvidenceIndex(parsed);
for (const entry of parsed.entries) {
if (
entry.execution.provider.id !== parsed.binding.provider.id ||
@@ -302,15 +304,130 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
if (ids.has(entry.query_id))
throw new TypeError("Analysis snapshot contains duplicate queries");
ids.add(entry.query_id);
if (!entryHasMatchingEvidence(entry, parsed, index)) {
if (entryHasCorrespondingEvidence(entry, parsed, index))
throw new TypeError(
`Analysis snapshot entry ${entry.operation} differs from its Evidence record`,
);
// Older snapshots may contain cache entries without profile-bound Evidence.
// Keep their Evidence bundle, but never replay those unbound values.
continue;
}
boundEntries.push(entry);
}
const sorted = [...parsed.entries].sort((left, right) =>
left.query_id.localeCompare(right.query_id),
);
if (JSON.stringify(parsed.entries) !== JSON.stringify(sorted))
throw new TypeError("Analysis snapshot entries are not canonical");
return parsed;
return { ...parsed, entries: boundEntries };
};
/** Check that a cached provider execution is represented by bundled Evidence. */
interface EvidenceIndex {
readonly matching: ReadonlySet<string>;
readonly corresponding: ReadonlySet<string>;
}
const createEvidenceIndex = (
snapshot: Pick<AnalysisSnapshot, "target" | "binding" | "evidence_bundle">,
): EvidenceIndex => {
const matching = new Set<string>();
const corresponding = new Set<string>();
for (const evidence of snapshot.evidence_bundle.records) {
if (!isCorrespondingEvidence(evidence, snapshot)) continue;
const query = evidenceQueryKey(evidence);
corresponding.add(query);
matching.add(
canonicalJson({
query,
normalized_result: evidence.normalized_result,
raw_result: evidence.raw_result,
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
local_path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
}),
);
}
const result = { matching, corresponding };
return result;
};
const entryHasMatchingEvidence = (
entry: AnalysisSnapshotEntry,
snapshot: Pick<AnalysisSnapshot, "target" | "binding" | "evidence_bundle">,
index: EvidenceIndex,
): boolean => index.matching.has(entryEvidenceKey(entry, snapshot.binding));
const entryHasCorrespondingEvidence = (
entry: AnalysisSnapshotEntry,
snapshot: Pick<AnalysisSnapshot, "target" | "binding" | "evidence_bundle">,
index: EvidenceIndex,
): boolean => index.corresponding.has(entryQueryKey(entry, snapshot.binding));
const isCorrespondingEvidence = (
evidence: Evidence,
snapshot: Pick<AnalysisSnapshot, "target" | "binding">,
): boolean =>
evidence.predicate_type === "rea.analysis" &&
evidence.confidence === "observed" &&
evidence.authority === "shipped-artifact" &&
evidence.subject?.digest.sha256 === snapshot.target.sha256 &&
"analysis_profile" in evidence &&
analysisProfilesEqual(
evidence.analysis_profile,
snapshot.binding.analysis_profile,
);
const evidenceQueryKey = (evidence: Evidence): string =>
canonicalJson({
operation: evidence.operation,
parameters: evidence.parameters,
provider: evidence.provider,
analysis_profile:
"analysis_profile" in evidence ? evidence.analysis_profile : null,
});
const entryQueryKey = (
entry: AnalysisSnapshotEntry,
binding: AnalysisSnapshotBinding,
): string =>
canonicalJson({
operation: entry.operation,
parameters: entry.parameters,
provider: entry.execution.provider,
analysis_profile: binding.analysis_profile,
});
const entryEvidenceKey = (
entry: AnalysisSnapshotEntry,
binding: AnalysisSnapshotBinding,
): string =>
canonicalJson({
query: entryQueryKey(entry, binding),
normalized_result: entry.execution.result,
raw_result: entry.execution.raw_result,
limitations: entry.execution.limitations,
locations: entry.execution.locations,
subject:
entry.execution.subject === null
? null
: {
local_path: entry.execution.subject.path,
sha256: entry.execution.subject.sha256,
format: entry.execution.subject.format,
architecture: entry.execution.subject.architecture,
},
});
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
+28 -6
View File
@@ -6,6 +6,7 @@ import {
inspectWebPageInputSchema,
isLiteralLoopbackHostname,
listBrowserTargetsInputSchema,
sanitizeEndpointCandidate,
sanitizeBrowserUrl,
} from "./browserObservation.js";
import { captureWebScreenshotInputSchema } from "./webScreenshot.js";
@@ -120,20 +121,28 @@ describe("browser observation sensitive surfaces and retention", () => {
expect(captureWebScreenshotInputSchema.safeParse(input).success).toBe(true);
});
it("removes credentials, query values, and fragments from observed URLs", () => {
it("removes only URL userinfo and preserves the original query and fragment", () => {
expect(
sanitizeBrowserUrl(
"https://user:pass@app.example.test/path?token=secret&mode=full#part",
"https://user:pass@app.example.test/path?token=secret&mode=full&token=again#part",
),
).toEqual({
url: "https://app.example.test/path?mode=%5BREDACTED%5D&token=%5BREDACTED%5D",
url: "https://app.example.test/path?token=secret&mode=full&token=again#part",
origin: "https://app.example.test",
query_parameter_names: ["mode", "token"],
query_parameter_names: ["token", "mode", "token"],
redacted: true,
});
const backslashAuthority = String.raw`https:\\user:pass@app.example.test/path?x=a+b&x=two#part`;
const sanitized = sanitizeBrowserUrl(backslashAuthority);
expect(sanitized.url).toBe(
"https://app.example.test/path?x=a+b&x=two#part",
);
expect(sanitized.url).not.toContain("user:pass");
expect(sanitized.redacted).toBe(true);
});
it("retains complete URL and query-name metadata while redacting values", () => {
it("retains ordinary query values and malformed URL diagnostics", () => {
const longName = `a${"x".repeat(400)}`;
const parameters = [
`${longName}=secret`,
@@ -147,7 +156,8 @@ describe("browser observation sensitive surfaces and retention", () => {
);
expect(sanitized.query_parameter_names).toHaveLength(301);
expect(sanitized.query_parameter_names).toContain(longName);
expect(sanitized.url).not.toContain("secret");
expect(sanitized.url).toContain(`${longName}=secret`);
expect(sanitized.url).toContain("k299=secret");
const oversized = sanitizeBrowserUrl(
`https://app.example.test/${"p".repeat(70_000)}`,
@@ -155,5 +165,17 @@ describe("browser observation sensitive surfaces and retention", () => {
expect(oversized.origin).toBe("https://app.example.test");
expect(oversized.url.length).toBeGreaterThan(70_000);
expect(oversized.redacted).toBe(false);
const malformed = "https://[invalid?token=diagnostic#fragment";
expect(sanitizeBrowserUrl(malformed)).toEqual({
url: malformed,
origin: null,
query_parameter_names: [],
redacted: false,
});
expect(sanitizeEndpointCandidate(malformed)).toBe(malformed);
expect(sanitizeEndpointCandidate("/api/search?q=rea#results")).toBe(
"/api/search?q=rea#results",
);
});
});
+45 -23
View File
@@ -81,15 +81,15 @@ export const browserEndpointSchema = z
export const browserAllowedOriginsSchema = z
.array(browserOriginSchema)
.min(1)
.transform((origins) => Array.from(new Set(origins)).sort());
.transform((origins) => Array.from(new Set(origins)).sort())
.default([]);
const browserInput = {
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
};
/** Public input for complete discovery of allowed page targets. */
/** Public input for complete discovery, optionally filtered by exact origin. */
export const listBrowserTargetsInputSchema = z.object({
...browserInput,
});
@@ -155,44 +155,66 @@ export const sanitizedBrowserUrlSchema = z.object({
});
export type SanitizedBrowserUrl = z.infer<typeof sanitizedBrowserUrlSchema>;
/** Remove credentials and query values before a browser URL becomes durable. */
/** Preserve local URL data while removing only URL userinfo credentials. */
export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
let parsed: URL;
try {
parsed = new URL(value);
} catch {
return {
url: "[unsupported-url]",
url: value,
origin: null,
query_parameter_names: [],
redacted: true,
redacted: false,
};
}
const hadCredentials = parsed.username !== "" || parsed.password !== "";
const hadFragment = parsed.hash !== "";
const names = [...new Set(parsed.searchParams.keys())].sort();
parsed.username = "";
parsed.password = "";
parsed.hash = "";
parsed.search = "";
for (const name of names) parsed.searchParams.append(name, "[REDACTED]");
const names = [...parsed.searchParams.keys()];
const sanitizedUrl = hadCredentials
? removeUrlUserInfo(value, parsed)
: value;
return {
url: parsed.href,
url: sanitizedUrl,
origin: parsed.origin === "null" ? null : parsed.origin,
query_parameter_names: names,
redacted: hadCredentials || hadFragment || names.length > 0,
redacted: hadCredentials,
};
};
/** Remove credentials, fragments, and query values from endpoint candidates. */
export const sanitizeEndpointCandidate = (value: string): string => {
const removeUrlUserInfo = (value: string, parsed: URL): string => {
const schemeSeparator = value.indexOf("://");
const authorityStart =
schemeSeparator < 0
? value.startsWith("//")
? 2
: -1
: schemeSeparator + 3;
if (authorityStart < 0) return credentialFreeHref(parsed);
const remaining = value.slice(authorityStart);
const delimiter = remaining.search(/[/?#]/u);
const authorityEnd =
delimiter < 0 ? value.length : authorityStart + delimiter;
const authority = value.slice(authorityStart, authorityEnd);
const userInfoEnd = authority.lastIndexOf("@");
if (userInfoEnd < 0) return credentialFreeHref(parsed);
const candidate = `${value.slice(0, authorityStart)}${authority.slice(userInfoEnd + 1)}${value.slice(authorityEnd)}`;
try {
const parsed = new URL(value, "https://rea.invalid");
const sanitized = sanitizeBrowserUrl(parsed.href).url;
return parsed.origin === "https://rea.invalid"
? sanitized.replace("https://rea.invalid", "")
: sanitized;
const candidateUrl = new URL(candidate);
return candidateUrl.username === "" && candidateUrl.password === ""
? candidate
: credentialFreeHref(parsed);
} catch {
return value.split("#", 1)[0]?.split("?", 1)[0] ?? "";
return credentialFreeHref(parsed);
}
};
const credentialFreeHref = (parsed: URL): string => {
parsed.username = "";
parsed.password = "";
return parsed.href;
};
/** Normalize endpoint candidates without discarding local query or fragment data. */
export const sanitizeEndpointCandidate = (value: string): string => {
return sanitizeBrowserUrl(value).url;
};
+17 -17
View File
@@ -12,12 +12,10 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
const secrets = Array.from({ length: actions.length }, (_, index) => ({
secret_id: `secret_${index}`,
environment_variable: `SECRET_${index}`,
purpose: "input",
redaction: "replace-with-secret-reference",
}));
const cookies = Array.from({ length: 129 }, (_, index) => ({
name: `cookie_${index}`,
value: { source: "literal", value: "value", classification: "public" },
value: { source: "literal", value: "value" },
destination: { url: "https://app.example.test/" },
http_only: false,
secure: true,
@@ -25,7 +23,7 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
}));
const storageEntries = Array.from({ length: 129 }, (_, index) => ({
name: `entry_${index}`,
value: { source: "literal", value: "value", classification: "public" },
value: { source: "literal", value: "value" },
}));
const routes = Array.from({ length: 257 }, (_, index) => ({
route_id: `route_${index}`,
@@ -38,9 +36,6 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
browser: {
mode: "launch",
executable_path: "/opt/chromium",
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
@@ -72,6 +67,21 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
).toHaveLength(257);
});
it("defaults scenario scope to the start URL origin", () => {
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
executable_path: "chrome",
},
start_url: { url: "https://app.example.test/" },
actions: [
{ step_id: "settle", action: "wait_for_timeout", duration_ms: 1 },
],
});
expect(scenario.allowed_origins).toEqual(["https://app.example.test"]);
});
it("accepts complete browser inputs beyond former string length caps", () => {
const longValue = "value".repeat(20_000);
const longToken = "a".repeat(70_000);
@@ -81,9 +91,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
browser: {
mode: "launch",
executable_path: longPath,
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: `https://app.example.test${longPath}` },
allowed_origins: ["https://app.example.test"],
@@ -91,8 +98,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
{
secret_id: longToken,
environment_variable: longEnvironmentVariable,
purpose: "input",
redaction: "replace-with-secret-reference",
},
],
actions: [
@@ -110,7 +115,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
value: {
source: "literal",
value: longValue,
classification: "public",
},
destination: { url: "https://app.example.test/" },
http_only: false,
@@ -136,7 +140,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
value: {
source: "literal",
value: longValue,
classification: "public",
},
},
],
@@ -171,9 +174,6 @@ it("accepts caller-selected viewport sizes and click counts without ceilings", (
browser: {
mode: "launch",
executable_path: "/opt/chromium",
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
+21 -73
View File
@@ -6,7 +6,6 @@ import {
browserScenarioBrowserSchema,
browserScenarioCaptureSchema,
browserScenarioEnvironmentSchema,
browserScenarioRedactionSchema,
browserScenarioRequestReplaySchema,
browserScenarioSecretSchema,
browserScenarioStorageSchema,
@@ -27,14 +26,16 @@ export {
export const browserScenarioInputSchema = z.strictObject({
browser: browserScenarioBrowserSchema.describe(
"Required launch/connect authority. Launch uses the approved executable and an owned temporary profile; connect uses one approved loopback CDP endpoint and target.",
"Required launch/connect selection. Launch uses the selected executable and an owned temporary profile; connect uses one loopback CDP endpoint and target.",
),
start_url: browserScenarioUrlSchema.describe(
"Required initial HTTP(S) URL. Query values must be declared separately as public literals or secret references.",
),
allowed_origins: browserScenarioAllowedOriginsSchema.describe(
"Required exact HTTP(S) origins for the start URL and every later navigation, storage seed, and replay route.",
),
allowed_origins: browserScenarioAllowedOriginsSchema
.default([])
.describe(
"Optional exact HTTP(S) origins for later navigation, storage seed, and replay routes. Defaults to the start URL origin.",
),
environment: browserScenarioEnvironmentSchema,
actions: z
.array(browserScenarioActionSchema)
@@ -46,9 +47,8 @@ export const browserScenarioInputSchema = z.strictObject({
.array(browserScenarioSecretSchema)
.default([])
.describe(
"Optional references to approved environment variables. Secret values are never supplied inline; declarations are required only when an action, URL, storage value, or replay route references a secret.",
"Optional environment-variable references for values used in actions, URLs, storage, or replay, and for redacting matching observed text. Secret values are never supplied inline.",
),
redaction: browserScenarioRedactionSchema,
capture: browserScenarioCaptureSchema,
});
@@ -136,12 +136,6 @@ const validateStorage = (
return references;
};
const SENSITIVE_HEADERS = new Set([
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
]);
const FORBIDDEN_REPLAY_HEADERS = new Set([
"content-length",
"location",
@@ -216,23 +210,6 @@ const validateRequestReplay = (
],
`Replay header ${header.name} must be modeled by the provider`,
);
if (
SENSITIVE_HEADERS.has(header.name) &&
header.value.source === "literal"
)
addIssue(
context,
[
"request_replay",
"routes",
routeIndex,
"response",
"headers",
headerIndex,
"value",
],
`Credential header ${header.name} requires a declared secret`,
);
references.push(...secretReferencesInValue(header.value));
});
references.push(...secretReferencesInValue(route.response.body));
@@ -253,51 +230,17 @@ const validateSecretReferences = (
["secrets"],
`Secret reference ${reference} is not declared`,
);
const used = new Set(references);
scenario.secrets.forEach(({ secret_id: id }, index) => {
if (!used.has(id))
addIssue(
context,
["secrets", index, "secret_id"],
`Secret declaration ${id} is unused`,
);
});
};
const validateRedactionCoverage = (
scenario: ScenarioShape,
context: z.RefinementCtx,
): void => {
const redactedQueries = new Set(scenario.redaction.query_parameter_names);
const destinations: BrowserScenarioUrl[] = [scenario.start_url];
for (const action of scenario.actions)
if (action.action === "goto") destinations.push(action.destination);
for (const cookie of scenario.storage.cookies)
destinations.push(cookie.destination);
if (scenario.request_replay.mode === "exact")
for (const route of scenario.request_replay.routes) {
destinations.push(route.request);
if (route.response.kind === "redirect")
destinations.push(route.response.destination);
}
for (const destination of destinations)
for (const query of destination.query)
if (
query.value.source === "secret" &&
!redactedQueries.has(query.name.toLowerCase())
)
addIssue(
context,
["redaction", "query_parameter_names"],
`Secret query parameter ${query.name} must be declared for redaction`,
);
};
const validateBrowserScenario = (
scenario: ScenarioShape,
context: z.RefinementCtx,
): void => {
const allowedOrigins = new Set(scenario.allowed_origins);
const allowedOrigins = new Set(
scenario.allowed_origins.length > 0
? scenario.allowed_origins
: [originFor(scenario.start_url)],
);
assertAllowedDestination(
scenario.start_url,
allowedOrigins,
@@ -336,11 +279,16 @@ const validateBrowserScenario = (
references.push(...validateStorage(scenario, allowedOrigins, context));
references.push(...validateRequestReplay(scenario, allowedOrigins, context));
validateSecretReferences(scenario, references, context);
validateRedactionCoverage(scenario, context);
};
/** Strict provider-neutral contract for one controlled browser scenario. */
export const browserScenarioSchema = browserScenarioInputSchema.superRefine(
validateBrowserScenario,
);
export const browserScenarioSchema = browserScenarioInputSchema
.superRefine(validateBrowserScenario)
.transform((scenario) => ({
...scenario,
allowed_origins:
scenario.allowed_origins.length > 0
? scenario.allowed_origins
: [originFor(scenario.start_url)],
}));
export type BrowserScenario = z.infer<typeof browserScenarioSchema>;
+21 -74
View File
@@ -10,16 +10,7 @@ export const scenarioIdentifierSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9._-]*$/u);
const absoluteExecutablePathSchema = z
.string()
.min(1)
.refine(
(value) =>
value.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(value) ||
value.startsWith("\\\\"),
"Expected an absolute browser executable path",
);
const browserExecutablePathSchema = z.string().trim().min(1);
const browserScenarioBaseUrlSchema = z
.string()
@@ -35,14 +26,11 @@ const browserScenarioBaseUrlSchema = z
if (
(url.protocol !== "http:" && url.protocol !== "https:") ||
url.username !== "" ||
url.password !== "" ||
url.search !== "" ||
url.hash !== ""
url.password !== ""
) {
context.addIssue({
code: "custom",
message:
"Browser URLs must be HTTP(S), omit credentials, and declare query values separately",
message: "Browser URLs must be HTTP(S) and omit credentials",
});
return z.NEVER;
}
@@ -53,7 +41,6 @@ export const browserScenarioValueSchema = z.discriminatedUnion("source", [
z.strictObject({
source: z.literal("literal"),
value: z.string(),
classification: z.literal("public"),
}),
z.strictObject({
source: z.literal("secret"),
@@ -67,7 +54,7 @@ const queryEntrySchema = z.strictObject({
value: browserScenarioValueSchema,
});
/** URL whose values remain explicit public literals or declared secret references. */
/** URL with ordinary inline details and optional structured secret query references. */
export const browserScenarioUrlSchema = z.strictObject({
url: browserScenarioBaseUrlSchema,
query: z.array(queryEntrySchema).default([]),
@@ -77,17 +64,18 @@ export type BrowserScenarioUrl = z.infer<typeof browserScenarioUrlSchema>;
export const browserScenarioBrowserSchema = z.discriminatedUnion("mode", [
z.strictObject({
mode: z.literal("launch"),
executable_path: absoluteExecutablePathSchema,
headless: z.literal(true),
user_data: z.literal("temporary-owned"),
cleanup: z.literal("close-and-delete-profile"),
executable_path: browserExecutablePathSchema,
headless: z
.boolean()
.default(true)
.describe(
"Run without a visible browser window; defaults to true and can be disabled when the host supports a display.",
),
}),
z.strictObject({
mode: z.literal("connect"),
cdp_endpoint: browserEndpointSchema,
target_id: z.string().trim().min(1),
ownership: z.literal("external"),
cleanup: z.literal("disconnect-only"),
}),
]);
@@ -112,7 +100,7 @@ export const browserScenarioEnvironmentSchema = z
.default("UTC"),
color_scheme: z.enum(["light", "dark", "no-preference"]).default("light"),
reduced_motion: z.enum(["reduce", "no-preference"]).default("reduce"),
service_workers: z.literal("block").default("block"),
service_workers: z.enum(["allow", "block"]).default("block"),
})
.default({
viewport: { width: 1_280, height: 720, device_scale_factor: 1 },
@@ -150,7 +138,6 @@ const locatorSchema = z.discriminatedUnion("kind", [
"textbox",
]),
name: z.string().min(1),
exact: z.literal(true),
}),
z.strictObject({
kind: z.literal("css"),
@@ -265,7 +252,7 @@ export const browserScenarioStorageSchema = z
})
.default({ cookies: [], local_storage: [], session_storage: [] })
.describe(
"Optional initial cookies, local storage, or session storage. Defaults to empty; every supplied value and origin must be explicitly declared and approved.",
"Optional initial cookies, local storage, or session storage. Defaults to empty; every supplied value and origin must be declared and within the allowed origins.",
);
const headerNameSchema = z
@@ -311,7 +298,7 @@ export const browserScenarioRequestReplaySchema = z
z.strictObject({ mode: z.literal("disabled") }),
z.strictObject({
mode: z.literal("exact"),
unmatched: z.enum(["abort", "passthrough-approved-origins"]),
unmatched: z.enum(["abort", "passthrough-declared-origins"]),
routes: z.array(replayRouteSchema).min(1),
}),
])
@@ -322,55 +309,15 @@ export const browserScenarioRequestReplaySchema = z
export const browserScenarioSecretSchema = z.strictObject({
secret_id: scenarioIdentifierSchema,
environment_variable: z.string().regex(/^[A-Z_][A-Z0-9_]*$/u),
purpose: z.enum(["input", "storage", "request-replay"]),
redaction: z.literal("replace-with-secret-reference"),
environment_variable: z
.string()
.min(1)
.refine(
(name) => !name.includes("=") && !name.includes("\0"),
"Environment variable names cannot contain '=' or NUL",
),
});
const REQUIRED_REDACTED_HEADERS = [
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
] as const;
const normalizedNames = () =>
z
.array(
z
.string()
.trim()
.min(1)
.transform((value) => value.toLowerCase()),
)
.transform((values) => [...new Set(values)].sort());
export const browserScenarioRedactionSchema = z
.strictObject({
secret_values: z
.literal("replace-with-secret-reference")
.default("replace-with-secret-reference"),
query_parameter_names: normalizedNames().default([]),
header_names: normalizedNames().default([...REQUIRED_REDACTED_HEADERS]),
})
.superRefine(({ header_names: names }, context) => {
for (const required of REQUIRED_REDACTED_HEADERS)
if (!names.includes(required))
context.addIssue({
code: "custom",
path: ["header_names"],
message: `Required credential header ${required} must be redacted`,
});
})
.default({
secret_values: "replace-with-secret-reference",
query_parameter_names: [],
header_names: [...REQUIRED_REDACTED_HEADERS],
})
.describe(
"Redaction policy. Secret values and credential headers are always redacted; list query parameter names when a secret is used in a URL.",
);
const snapshotKindSchema = z.enum([
"screenshot",
"dom",
+2 -2
View File
@@ -82,7 +82,7 @@ export const authFlowEventSchema = z.strictObject({
token_lifecycle: tokenLifecycleEventSchema.nullable(),
/** Correlation ID linking challenge-response pairs. */
correlation_id: z.string().nullable(),
/** Whether credentials were detected and redacted. */
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
/** Whether the authentication succeeded. */
succeeded: z.boolean().default(false),
@@ -101,7 +101,7 @@ export const customProtocolCaptureSchema = z.strictObject({
auth_events: z.array(authFlowEventSchema).default([]),
/** Whether any frame was truncated. */
has_truncated: z.boolean().default(false),
/** Whether credentials were detected. */
/** Whether the capture producer detected credential content. */
credentials_detected: z.boolean().default(false),
});
+11 -6
View File
@@ -1,11 +1,16 @@
import { isAbsolute } from "node:path";
import { z } from "zod";
const pathInputSchema = z.string().trim().min(1);
const absolutePathSchema = z
.string()
.min(1)
.refine(isAbsolute, "path must be absolute");
.refine(
(value) =>
value.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(value) ||
value.startsWith("\\\\"),
"provider path must be absolute",
);
const windowIndexSchema = z.number().int().min(0);
@@ -53,9 +58,9 @@ const actionSchema = z.discriminatedUnion("kind", [
/** Input for one explicit, provider-owned Electron runtime experiment. */
export const electronActiveObservationInputSchema = z.strictObject({
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
application_root: absolutePathSchema,
executable_path: pathInputSchema,
application_path: pathInputSchema,
application_root: pathInputSchema.optional(),
args: z.array(z.string()).default([]),
actions: z.array(actionSchema).default([]),
});
+3 -55
View File
@@ -5,11 +5,6 @@ import type {
} from "./browserObservationErrors.js";
export type { BrowserObservationOperation } from "./browserObservationErrors.js";
import type {
MissingPermissionScope,
PermissionRequest,
PermissionScope,
} from "./permissionPolicy.js";
import {
hopperStartupFailure,
type HopperStartupDiagnostic,
@@ -49,7 +44,6 @@ const ANALYSIS_ERROR_TAGS = [
"ConfigurationError",
"NoBinaryOpenError",
"BinaryTargetError",
"PermissionRequiredError",
"ReplayPlanStaleError",
] as const;
@@ -60,8 +54,7 @@ export type AnalysisErrorTag = (typeof ANALYSIS_ERROR_TAGS)[number];
export abstract class AnalysisError extends Error {
abstract readonly _tag: AnalysisErrorTag;
readonly userMessage: string | undefined = undefined;
readonly userCategory: "permission_required" | "cancelled" | undefined =
undefined;
readonly userCategory: "cancelled" | undefined = undefined;
readonly cleanupIncomplete: boolean = false;
readonly cleanupResources: readonly string[] = [];
}
@@ -285,7 +278,6 @@ export class ArtifactOperationError extends AnalysisError {
| "integrity"
| "limit"
| "path"
| "policy"
| "unavailable"
| "io",
readonly artifactDetails?: Readonly<{
@@ -490,7 +482,6 @@ export interface AnalysisErrorProjection
| "artifact_operation_failed"
| "evidence_integrity_mismatch"
| "truncated"
| "permission_required"
| "process_capture_failed"
| "cleanup_incomplete"
| "revision_conflict"
@@ -500,7 +491,6 @@ export interface AnalysisErrorProjection
| "plan_stale";
readonly category:
| "invalid_input"
| "permission_required"
| "unsupported_provider"
| "integrity_mismatch"
| "truncated"
@@ -512,58 +502,16 @@ export interface AnalysisErrorProjection
readonly retryable: boolean;
readonly remediation: Readonly<{
action: string;
restart_required: boolean;
elicitation_supported?: boolean;
}>;
readonly details?: Readonly<Record<string, JsonValue>>;
}
/** One legal recovery path for a denied permission request. */
/**
* Legal recovery path for a denied permission.
*
* `grant` is deliberately distinct from `configure`: a request can be denied
* because no grant was ever issued even though the administrator ceiling
* already covers it. Telling that caller to widen the ceiling sends them to
* edit configuration that is already correct.
*/
export type PermissionRemediation =
| "configure"
| "elicit"
| "restart"
| "grant";
/** Exact denied authority and its legal recovery path. */
export interface PermissionRequiredContext {
readonly requested: PermissionRequest;
readonly missing: MissingPermissionScope;
readonly ceiling: PermissionScope | null;
readonly remediation: PermissionRemediation;
}
/** Exact denied authority used by both CLI and MCP remediation. */
export class PermissionRequiredError extends AnalysisError {
readonly _tag = "PermissionRequiredError" as const;
readonly requested: PermissionRequest;
readonly missing: MissingPermissionScope;
readonly ceiling: PermissionScope | null;
readonly remediation: PermissionRemediation;
constructor(context: PermissionRequiredContext) {
super(`Permission required for ${context.requested.capability}`);
this.requested = context.requested;
this.missing = context.missing;
this.ceiling = context.ceiling;
this.remediation = context.remediation;
}
}
/** Approved replay commitment no longer matches the immediately rebuilt plan. */
/** Replay commitment no longer matches the immediately rebuilt plan. */
export class ReplayPlanStaleError extends AnalysisError {
readonly _tag = "ReplayPlanStaleError" as const;
constructor(
readonly approvedDigest: string,
readonly expectedDigest: string,
readonly actualDigest: string,
) {
super("Controlled replay plan changed before execution");
+1 -6
View File
@@ -1,5 +1,3 @@
import { isAbsolute } from "node:path";
import { z } from "zod";
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
@@ -11,10 +9,7 @@ const countSchema = z.number().int().min(0);
/** Public target-free request for static JavaScript application analysis. */
export const analyzeJavaScriptApplicationInputSchema = z.strictObject({
input_path: z
.string()
.min(1)
.refine(isAbsolute, "JavaScript application input path must be absolute"),
input_path: z.string().min(1),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
});
+44 -20
View File
@@ -108,11 +108,9 @@ const determinismSchema = z
})
.strict();
const controlledReplayInputShape = {
const controlledReplayCommonInputShape = {
left: replaySideSchema,
right: replaySideSchema.optional(),
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema.optional(),
determinism: determinismSchema.default({
clock_iso: "2000-01-01T00:00:00.000Z",
random_seed: 0,
@@ -144,32 +142,56 @@ const controlledReplayInputShape = {
/** Parse a replay request that can only construct a plan. */
export const controlledReplayPlanInputSchema = z.strictObject({
...controlledReplayInputShape,
...controlledReplayCommonInputShape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema.optional(),
mode: z.literal("plan"),
});
/** Parse a replay request carrying the digest for one exact plan. */
export const controlledReplayExecutionInputSchema = z.strictObject({
...controlledReplayInputShape,
...controlledReplayCommonInputShape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema.optional(),
mode: z.literal("execute"),
plan_digest: digestSchema,
});
/** Parse a controlled replay request into its legal plan or execution state. */
export const controlledReplayInputSchema = z
.discriminatedUnion("mode", [
controlledReplayPlanInputSchema,
controlledReplayExecutionInputSchema,
])
.superRefine((value, context) => {
if (value.cases.length === 0 && value.generator === undefined)
context.addIssue({
code: "custom",
path: ["cases"],
message: "At least one explicit or generated case is required",
});
const replayWithExplicitCases = <Shape extends z.ZodRawShape>(shape: Shape) =>
z.strictObject({
...shape,
cases: z.array(explicitCaseSchema).min(1),
});
const replayWithGeneratedCases = <Shape extends z.ZodRawShape>(shape: Shape) =>
z.strictObject({
...shape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema,
});
/** Parse replay requests with explicit cases or a generated case preset. */
export const controlledReplayInputSchema = z.union([
replayWithExplicitCases({
...controlledReplayCommonInputShape,
mode: z.literal("plan"),
}),
replayWithGeneratedCases({
...controlledReplayCommonInputShape,
mode: z.literal("plan"),
}),
replayWithExplicitCases({
...controlledReplayCommonInputShape,
mode: z.literal("execute"),
plan_digest: digestSchema,
}),
replayWithGeneratedCases({
...controlledReplayCommonInputShape,
mode: z.literal("execute"),
plan_digest: digestSchema,
}),
]);
const moduleCommitmentSchema = z
.object({
alias: aliasSchema,
@@ -385,8 +407,10 @@ export const controlledReplayOutputSchema = z.discriminatedUnion("phase", [
controlledReplayExecutionOutputSchema,
]);
export type ControlledReplayInput = z.infer<typeof controlledReplayInputSchema>;
export type ControlledReplayExecutionInput = z.infer<
export type ControlledReplayInput =
| z.output<typeof controlledReplayPlanInputSchema>
| z.output<typeof controlledReplayExecutionInputSchema>;
export type ControlledReplayExecutionInput = z.output<
typeof controlledReplayExecutionInputSchema
>;
export type ControlledReplayExecutionOutput = z.infer<
@@ -420,7 +420,7 @@ const assertRuntimeParameters = (
);
if (expected.sourceIncluded && !parameters.include_script_sources)
throw new TypeError(
"Runtime Evidence contains source without source-capture approval",
"Runtime Evidence contains source without source-capture selection",
);
return;
}
@@ -140,7 +140,7 @@ const sourceMapAuthority = (
0,
),
limitation:
"Source-map declarations and approved original-source reads retain separate static authority and are not used as primary runtime byte matches.",
"Source-map declarations and original-source content retain separate static authority and are not used as primary runtime byte matches.",
});
const reconciliationCoverage = (
@@ -1,5 +1,3 @@
import { isAbsolute, resolve } from "node:path";
import { z } from "zod";
import { evidenceSchema } from "./evidence.js";
@@ -27,11 +25,7 @@ const safePrefixSchema = z
const runtimeFileMappingSchema = z.strictObject({
kind: z.literal("file-root"),
root: z
.string()
.min(1)
.refine(isAbsolute, "Runtime file mapping root must be absolute")
.overwrite((value) => resolve(value)),
root: z.string().min(1),
artifact_prefix: safePrefixSchema.default(""),
});
@@ -75,7 +69,7 @@ const runtimeLocationMappingSchema = z.discriminatedUnion("kind", [
type RuntimeLocationMapping = z.infer<typeof runtimeLocationMappingSchema>;
const staticLayerSchema = z.strictObject({
role: z.enum(["application", "cache", "assets"]),
role: z.enum(["application", "cache", "assets"]).default("application"),
analysis: evidenceSchema,
runtime_mappings: z
.array(runtimeLocationMappingSchema)
@@ -1,6 +1,5 @@
import { posix, relative } from "node:path";
import { posix, relative, win32 } from "node:path";
import { isPathWithinRoot } from "./localPath.js";
import {
compareCodePoints,
type ApplicationNode,
@@ -208,14 +207,31 @@ const candidateDigests = (
};
const pathBelowRoot = (root: string, value: string): string | null => {
const remainder = relative(root, value);
const rootStyle = absoluteFilePathStyle(root);
if (rootStyle === null || rootStyle !== absoluteFilePathStyle(value))
return null;
const remainder =
rootStyle === "windows"
? win32.relative(root, value)
: relative(root, value);
const portableRemainder = remainder.replaceAll("\\", "/");
if (
remainder === "" ||
!isPathWithinRoot(root, value) ||
remainder.includes("\\")
(rootStyle === "windows" && win32.isAbsolute(remainder)) ||
portableRemainder === ".." ||
portableRemainder.startsWith("../")
)
return null;
return normalizeArtifactPath(remainder);
return normalizeArtifactPath(portableRemainder);
};
const absoluteFilePathStyle = (path: string): "posix" | "windows" | null => {
if (
/^[a-z]:[\\/]/iu.test(path) ||
/^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/u.test(path)
)
return "windows";
return path.startsWith("/") ? "posix" : null;
};
const pathBelowUrlPrefix = (prefix: string, value: string): string | null => {
@@ -22,6 +22,16 @@ it("accepts long selectors and complete relation and class selections", () => {
expect(result.expected?.classes).toHaveLength(25);
});
it("rejects the inert source-map authority setting", () => {
expect(
javaScriptSemanticQueryInputSchema.safeParse({
seed: { kind: "endpoint", value: "/api" },
direction: "forward-influence",
source_map_authority: { authority: "none" },
}).success,
).toBe(false);
});
it("accepts every reported limitation without a count ceiling", () => {
const limitations = Array.from(
{ length: 1_001 },
@@ -12,7 +12,6 @@ import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const semanticNodeIdSchema = prefixedDigestSchema("jsrg_node");
const literalSeedSchema = z.strictObject({
kind: z.literal("literal"),
value: jsonValueSchema.refine(
@@ -58,10 +57,6 @@ export const javaScriptSemanticQuerySeedSchema = z.discriminatedUnion("kind", [
}),
]);
const sourceMapAuthoritySchema = z.strictObject({
authority: z.literal("none"),
});
/** Parsed pure-domain query over one authenticated companion graph. */
export const javaScriptSemanticQueryInputSchema = z.strictObject({
seed: javaScriptSemanticQuerySeedSchema,
@@ -83,7 +78,6 @@ export const javaScriptSemanticQueryInputSchema = z.strictObject({
})
.nullable()
.default(null),
source_map_authority: sourceMapAuthoritySchema.default({ authority: "none" }),
});
/** Deterministic semantic trace result. */
+2 -3
View File
@@ -100,8 +100,7 @@ export const collectNativeSymbols = (
return { symbols, accepted, unsupported };
};
const normalizeSymbol = (value: string): string =>
value.replace(/^_+/u, "").replace(/@\d+$/u, "").toLowerCase();
const normalizeSymbol = (value: string): string => value.replace(/^_+/u, "");
const sameSymbolName = (left: string, right: string): boolean =>
normalizeSymbol(left) === normalizeSymbol(right);
@@ -185,7 +184,7 @@ const matchPinvoke = (
const candidates: [NativeSymbol, ...NativeSymbol[]] = [first, ...remaining];
const exact = candidates.find(
(symbol) =>
sameSymbolName(managed.import_name, symbol.name) &&
managed.import_name === symbol.name &&
moduleCompatible(managed.import_scope_name, symbol),
);
const decorated = candidates.find((symbol) =>
+4 -2
View File
@@ -29,9 +29,7 @@ describe("managed reconstruction import input", () => {
static_members: evidence,
decompiler: {
name: "Fixture decompiler",
version: null,
family: "other",
executable_sha256: null,
options: Array.from({ length: 51 }, (_, index) => `option-${index}`),
},
methods: Array.from({ length: 51 }, (_, index) => ({
@@ -44,6 +42,10 @@ describe("managed reconstruction import input", () => {
expect(parsed.methods).toHaveLength(51);
expect(parsed.decompiler.options).toHaveLength(51);
expect(parsed.decompiler).toMatchObject({
version: null,
executable_sha256: null,
});
expect(parsed.notes).toHaveLength(101);
});
+2 -2
View File
@@ -19,9 +19,9 @@ const textSchema = z.string().min(1);
const decompilerSchema = z.strictObject({
name: textSchema,
version: textSchema.nullable(),
version: textSchema.nullable().default(null),
family: z.enum(["ilspy", "dnspy", "dnlib", "mono-cecil", "other"]),
executable_sha256: digestSchema.nullable(),
executable_sha256: digestSchema.nullable().default(null),
options: z.array(z.string()).default([]),
});
+12 -22
View File
@@ -34,8 +34,8 @@ const managedRuntimeBoundsSchema = z.strictObject({
timeout_ms: z.number().int().min(1).default(5_000),
max_threads: z.number().int().min(1).default(32),
max_output_bytes: z.number().int().min(0).default(65_536),
allow_network: z.literal(false).default(false),
allow_ui: z.literal(false).default(false),
allow_network: z.boolean().default(false),
allow_ui: z.boolean().default(false),
});
export const managedRuntimeCorrelationInputSchema = z.strictObject({
@@ -58,14 +58,8 @@ export const managedRuntimeCorrelationInputSchema = z.strictObject({
export const managedRuntimeCorrelationResultSchema = z.strictObject({
correlation_id: prefixedDigestSchema("mrc"),
phase: z.literal("admission-plan"),
phase: z.literal("correlation-plan"),
executed: z.literal(false),
authority_model: z.strictObject({
capability: z.literal("managed_runtime"),
permission_grant_id: z.string().min(1),
default_enabled: z.literal(false),
per_call_approval_required: z.literal(true),
}),
static_observation: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
@@ -96,8 +90,8 @@ export const managedRuntimeCorrelationResultSchema = z.strictObject({
effect: managedRuntimeEffectSchema,
host: managedRuntimeHostSchema,
executable_path: z.string().min(1),
network: z.literal("none"),
filesystem: z.literal("owned-artifacts-only"),
network: z.enum(["none", "host"]),
confinement: z.literal("not-established"),
}),
effect_taxonomy: z.strictObject({
attaches_process: z.boolean(),
@@ -131,7 +125,6 @@ const sha256 = (value: JsonValue): string => {
export const planManagedRuntimeCorrelation = (
input: ManagedRuntimeCorrelationInput,
executablePath: string,
permissionGrantId: string,
): ManagedRuntimeCorrelationResult => {
const staticEvidence = parseEvidence(input.static_members);
if (staticEvidence.operation !== "inspect_managed_members")
@@ -153,14 +146,8 @@ export const planManagedRuntimeCorrelation = (
"Requested method lock does not match a static managed member observation",
);
const withoutId = {
phase: "admission-plan" as const,
phase: "correlation-plan" as const,
executed: false as const,
authority_model: {
capability: "managed_runtime" as const,
permission_grant_id: permissionGrantId,
default_enabled: false as const,
per_call_approval_required: true as const,
},
static_observation: {
evidence_id: staticEvidence.evidence_id,
artifact_sha256: members.artifact.sha256,
@@ -185,8 +172,10 @@ export const planManagedRuntimeCorrelation = (
effect: input.requested_effect,
host: input.host,
executable_path: executablePath,
network: "none" as const,
filesystem: "owned-artifacts-only" as const,
network: input.bounds.allow_network
? ("host" as const)
: ("none" as const),
confinement: "not-established" as const,
},
effect_taxonomy: effectTaxonomy(input.requested_effect),
bounds: input.bounds,
@@ -196,7 +185,8 @@ export const planManagedRuntimeCorrelation = (
"This operation admits and records a runtime-correlation plan only; it did not attach, load, debug, reflect, instrument, invoke, or execute target code.",
"Runtime agreement would be a separate runtime observation and would not retroactively turn static inference into a byte observation.",
"The exact artifact SHA-256, MVID, method signature, and normalized IL shape must match before any future executor can run.",
"Network and UI effects are not admitted by this contract.",
"The selected runtime executable and host prerequisites are unverified because planning does not launch the runtime.",
"No filesystem, network, or UI confinement was established; the requested bounds describe a future executor configuration only.",
],
};
return managedRuntimeCorrelationResultSchema.parse({
+70 -18
View File
@@ -1,20 +1,29 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { decodeCanonicalBase64 } from "./webScreenshot.js";
const scope = {
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
observation_approved: z.literal(true),
screenshot: z.boolean().default(true),
accessibility: z.boolean().default(true),
max_nodes: z.number().int().min(1).max(2_000).default(500),
max_nodes: z
.number()
.int()
.positive()
.safe()
.default(500)
.describe(
"Maximum accessibility nodes per capture; increase for large windows.",
),
};
/** Opt-in passive observation binds one already-running process and window. */
export const nativeUiObservationInputSchema = z.strictObject(scope);
/** Active scenarios require independent action approval and an explicit restore choice. */
/** Active scenarios use explicit actions and leave application state as-is. */
export const nativeUiScenarioInputSchema = z.strictObject({
...scope,
actions_approved: z.literal(true),
restore: z.literal("leave-as-is"),
steps: z
.array(
z.discriminatedUnion("kind", [
@@ -30,18 +39,69 @@ export const nativeUiScenarioInputSchema = z.strictObject({
z.strictObject({
kind: z.literal("key-entry"),
path: z.array(z.number().int().nonnegative()).max(32),
text: z.string().max(4_096),
text: z.string(),
}),
z.strictObject({
kind: z.literal("wait"),
milliseconds: z.number().int().min(0).max(10_000),
milliseconds: z
.number()
.int()
.min(0)
.max(180_000)
.describe(
"Wait duration in milliseconds, within the 180-second operation deadline.",
),
}),
]),
)
.min(1)
.max(16),
.min(1),
});
/** Ordered captures and failures distinguish missing observation from a failed action. */
const nativeUiScreenshotSchema = z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string().min(4),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
width: z.number().int().positive(),
height: z.number().int().positive(),
})
.superRefine((screenshot, context) => {
const bytes = decodeCanonicalBase64(screenshot.base64);
if (bytes === undefined) {
context.addIssue({
code: "custom",
message: "Invalid canonical PNG base64",
});
return;
}
if (createHash("sha256").update(bytes).digest("hex") !== screenshot.sha256)
context.addIssue({
code: "custom",
message: "PNG screenshot digest mismatch",
});
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
) {
context.addIssue({
code: "custom",
message: "Screenshot bytes are not a PNG image",
});
return;
}
if (
bytes.readUInt32BE(16) !== screenshot.width ||
bytes.readUInt32BE(20) !== screenshot.height
)
context.addIssue({
code: "custom",
message: "PNG screenshot dimensions mismatch",
});
});
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
export const nativeUiSnapshotSchema = z.strictObject({
window: z.strictObject({
pid: z.number().int().positive(),
@@ -61,15 +121,7 @@ export const nativeUiSnapshotSchema = z.strictObject({
}),
),
truncated: z.boolean(),
screenshot: z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string(),
sha256: z.string(),
width: z.number().int().positive(),
height: z.number().int().positive(),
})
.nullable(),
screenshot: nativeUiScreenshotSchema.nullable(),
gaps: z.array(z.string()),
});
export const nativeUiResultSchema = z.strictObject({
+3 -1
View File
@@ -62,7 +62,9 @@ export const nodeCharacterizationPreparationInputSchema = z
});
export const nodeCharacterizationExecutionInputSchema = z.strictObject({
approved_plan_sha256: digestSchema,
plan_sha256: digestSchema.describe(
"SHA-256 content identity of the prepared plan; execution rejects a mismatch.",
),
preparation: nodeCharacterizationPreparationInputSchema,
});
-283
View File
@@ -1,283 +0,0 @@
import { describe, expect, it } from "vitest";
import { win32 } from "node:path";
import {
consumePermission,
clearSessionPermissions,
createPermissionPolicy,
evaluatePermission,
grantPermission,
isPathContained,
reloadPermissionCeilings,
revokePermission,
} from "./permissionPolicy.js";
describe("permission policy", () => {
it("rejects sibling escapes for both POSIX and Windows path separators", () => {
expect(isPathContained("/allowed", "/secret")).toBe(false);
expect(
isPathContained("C:\\allowed", "C:\\secret", {
relative: win32.relative,
isAbsolute: win32.isAbsolute,
sep: win32.sep,
}),
).toBe(false);
expect(
isPathContained("C:\\allowed", "C:\\allowed\\nested", {
relative: win32.relative,
isAbsolute: win32.isAbsolute,
sep: win32.sep,
}),
).toBe(true);
});
it("never lets a session grant exceed the administrator ceiling", () => {
const policy = createPermissionPolicy([
{
capability: "process_capture",
roots: ["/workspace/project"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
},
]);
const granted = grantPermission(policy, {
grant_id: "grant_session_1",
capability: "process_capture",
roots: ["/workspace/project"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
lifetime: "session",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(granted.value, {
capability: "process_capture",
roots: ["/workspace/project/data"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
operation_identity: "capture-1",
}),
).toMatchObject({ allowed: true });
expect(
evaluatePermission(granted.value, {
capability: "process_capture",
roots: ["/workspace/project/data"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG", "TOKEN"],
network: "external",
mount: false,
operation_identity: "capture-2",
}),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
missing: {
environment_names: ["TOKEN"],
network: "external",
},
});
});
it("authorizes browser observation only for exact declared origins", () => {
const scope = {
capability: "browser_observe" as const,
roots: [],
executables: [],
environment_names: [],
origins: ["http://127.0.0.1:9222", "https://app.example.test"],
network: "external" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([scope]), {
...scope,
grant_id: "browser-session",
lifetime: "session",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(granted.value, {
...scope,
operation_identity: "inspect:page-1",
}),
).toMatchObject({ allowed: true });
expect(
evaluatePermission(granted.value, {
...scope,
origins: ["http://127.0.0.1:9222", "https://cdn.example.test"],
operation_identity: "inspect:page-2",
}),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
missing: { origins: ["https://cdn.example.test"] },
});
});
});
describe("permission policy lifecycle", () => {
it("consumes once grants and applies revocation and ceiling reload immediately", () => {
const ceiling = {
capability: "process_capture" as const,
roots: ["/workspace/evidence"],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([ceiling]), {
...ceiling,
grant_id: "grant_once_1",
lifetime: "once",
operation_identity: "write:report.json",
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
const request = {
...ceiling,
roots: ["/workspace/evidence/report.json"],
operation_identity: "write:report.json",
};
const decision = evaluatePermission(granted.value, request);
expect(decision).toMatchObject({ allowed: true });
if (!decision.allowed) return;
const consumed = consumePermission(granted.value, decision);
expect(evaluatePermission(consumed, request)).toMatchObject({
allowed: false,
reason: "grant_revoked_or_consumed",
});
expect(
evaluatePermission(
revokePermission(granted.value, "grant_once_1"),
request,
),
).toMatchObject({
allowed: false,
reason: "grant_revoked_or_consumed",
});
expect(
evaluatePermission(reloadPermissionCeilings(granted.value, []), request),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
});
});
it("reports a missing scope when revoked grants cover a different root", () => {
const ceiling = {
capability: "process_capture" as const,
roots: ["/workspace"],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([ceiling]), {
...ceiling,
roots: ["/workspace/first"],
grant_id: "revoked-other-root",
lifetime: "project",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(
revokePermission(granted.value, "revoked-other-root"),
{
...ceiling,
roots: ["/workspace/second"],
operation_identity: "write:report.json",
},
),
).toMatchObject({
allowed: false,
reason: "grant_required",
missing: { roots: ["/workspace/second"] },
});
});
it("expires grants, removes session authority on disconnect, and never combines partial grants", () => {
const ceiling = {
capability: "process_capture" as const,
roots: ["/workspace"],
executables: ["/bin/tool"],
environment_names: ["LANG"],
network: "loopback" as const,
mount: false,
};
const base = createPermissionPolicy([ceiling]);
const rootOnly = grantPermission(base, {
...ceiling,
executables: [],
environment_names: [],
network: "none",
grant_id: "root-only",
lifetime: "project",
operation_identity: null,
expires_at: null,
});
expect(rootOnly.ok).toBe(true);
if (!rootOnly.ok) return;
const executableOnly = grantPermission(rootOnly.value, {
...ceiling,
roots: [],
grant_id: "exec-only",
lifetime: "session",
operation_identity: null,
expires_at: "2026-07-14T00:00:00.000Z",
});
expect(executableOnly.ok).toBe(true);
if (!executableOnly.ok) return;
const request = {
...ceiling,
operation_identity: "capture",
};
expect(
evaluatePermission(
executableOnly.value,
request,
new Date("2026-07-13T00:00:00.000Z"),
),
).toMatchObject({ allowed: false, reason: "grant_required" });
const expiring = grantPermission(base, {
...ceiling,
grant_id: "expiring",
lifetime: "session",
operation_identity: null,
expires_at: "2026-07-14T00:00:00.000Z",
});
expect(expiring.ok).toBe(true);
if (!expiring.ok) return;
expect(
evaluatePermission(
expiring.value,
request,
new Date("2026-07-15T00:00:00.000Z"),
),
).toMatchObject({ allowed: false, reason: "grant_expired" });
expect(
clearSessionPermissions(executableOnly.value).grants.map(
({ grant_id }) => grant_id,
),
).toEqual(["root-only"]);
});
});
-339
View File
@@ -1,339 +0,0 @@
import { isAbsolute, relative, resolve, sep } from "node:path";
import { err, ok, type Result } from "./result.js";
/** Canonical local capabilities governed by the shared REA permission policy. */
export const PERMISSION_CAPABILITIES = [
"process_capture",
"browser_observe",
"browser_automate",
"electron_observe",
"electron_automate",
"v8_inspector_observe",
"artifact_extract",
"native_mount",
"javascript_replay",
"managed_runtime",
] as const;
/** One capability from the canonical local permission inventory. */
export type PermissionCapability = (typeof PERMISSION_CAPABILITIES)[number];
/** Ordered network authority; each mode includes the modes before it. */
type PermissionNetwork = "none" | "loopback" | "external";
/** Exact normalized scope requested by one local operation. */
export interface PermissionScope {
readonly capability: PermissionCapability;
readonly roots: readonly string[];
readonly executables: readonly string[];
readonly environment_names: readonly string[];
readonly origins?: readonly string[] | undefined;
readonly network: PermissionNetwork;
readonly mount: boolean;
}
/** A request identity associates one-shot grants with exactly one operation. */
export interface PermissionRequest extends PermissionScope {
readonly operation_identity: string;
}
/** Administrator-owned maximum authority for one capability. */
export type PermissionCeiling = PermissionScope;
/** Authority issued beneath the administrator ceiling. */
export interface PermissionGrant extends PermissionScope {
readonly grant_id: string;
readonly lifetime: "once" | "session" | "project" | "administrator";
readonly operation_identity: string | null;
readonly expires_at: string | null;
}
/** Missing requested authority, containing names and paths but never values. */
export interface MissingPermissionScope {
readonly roots?: readonly string[];
readonly executables?: readonly string[];
readonly environment_names?: readonly string[];
readonly origins?: readonly string[];
readonly network?: PermissionNetwork;
readonly mount?: true;
}
/** Immutable shared policy state. */
export interface PermissionPolicy {
readonly ceilings: readonly PermissionCeiling[];
readonly grants: readonly PermissionGrant[];
readonly revoked_grant_ids: ReadonlySet<string>;
readonly consumed_grant_ids: ReadonlySet<string>;
}
/** A proposed grant exceeds the administrator-owned maximum authority. */
export class PermissionGrantError extends Error {
readonly _tag = "PermissionGrantError" as const;
constructor(
readonly reason: "outside_administrator_ceiling" | "invalid_once_scope",
readonly missing: MissingPermissionScope,
) {
super(`Permission grant rejected: ${reason}`);
}
}
/** Observable decision returned before any governed side effect. */
export type PermissionDecision =
| {
readonly allowed: true;
readonly grant_id: string;
readonly lifetime: PermissionGrant["lifetime"];
}
| {
readonly allowed: false;
readonly reason:
| "outside_administrator_ceiling"
| "grant_required"
| "grant_revoked_or_consumed"
| "grant_expired";
readonly missing: MissingPermissionScope;
};
/** Create a fail-closed policy with no implicit grants. */
export const createPermissionPolicy = (
ceilings: readonly PermissionCeiling[],
grants: readonly PermissionGrant[] = [],
): PermissionPolicy => ({
ceilings: ceilings.map(normalizeScope),
grants: grants.map(normalizeGrant),
revoked_grant_ids: new Set(),
consumed_grant_ids: new Set(),
});
/** Add one grant only when it is a subset of its administrator ceiling. */
export const grantPermission = (
policy: PermissionPolicy,
grant: PermissionGrant,
): Result<PermissionPolicy, PermissionGrantError> => {
const normalized = normalizeGrant(grant);
if (normalized.lifetime === "once" && normalized.operation_identity === null)
return err(new PermissionGrantError("invalid_once_scope", {}));
const missing = missingFromScopes(normalized, policy.ceilings);
if (hasMissing(missing))
return err(
new PermissionGrantError("outside_administrator_ceiling", missing),
);
return ok({ ...policy, grants: [...policy.grants, normalized] });
};
/** Evaluate exact requested authority against the ceiling and active grants. */
export const evaluatePermission = (
policy: PermissionPolicy,
request: PermissionRequest,
now: Date = new Date(),
): PermissionDecision => {
const normalized = normalizeRequest(request);
const outsideCeiling = missingFromScopes(normalized, policy.ceilings);
if (hasMissing(outsideCeiling))
return {
allowed: false,
reason: "outside_administrator_ceiling",
missing: outsideCeiling,
};
const candidates = policy.grants.filter(
(grant) =>
grant.capability === normalized.capability &&
!policy.revoked_grant_ids.has(grant.grant_id) &&
!policy.consumed_grant_ids.has(grant.grant_id) &&
!isExpired(grant, now) &&
(grant.lifetime !== "once" ||
grant.operation_identity === normalized.operation_identity),
);
const selected = candidates.find(
(grant) => !hasMissing(missingFromScopes(normalized, [grant])),
);
if (selected !== undefined)
return {
allowed: true,
grant_id: selected.grant_id,
lifetime: selected.lifetime,
};
const coveringGrant = policy.grants.find(
(grant) =>
grant.capability === normalized.capability &&
(grant.lifetime !== "once" ||
grant.operation_identity === normalized.operation_identity) &&
!hasMissing(missingFromScopes(normalized, [grant])),
);
return {
allowed: false,
reason:
coveringGrant !== undefined && isExpired(coveringGrant, now)
? "grant_expired"
: coveringGrant !== undefined
? "grant_revoked_or_consumed"
: "grant_required",
missing: missingFromScopes(normalized, candidates),
};
};
/** Test whether one exact request is wholly contained by one ceiling. */
export const isPermissionRequestWithinCeiling = (
request: PermissionRequest,
ceiling: PermissionCeiling,
): boolean =>
!hasMissing(missingFromScopes(normalizeRequest(request), [ceiling]));
/** Consume an allowed one-shot decision; longer-lived grants are unchanged. */
export const consumePermission = (
policy: PermissionPolicy,
decision: Extract<PermissionDecision, { readonly allowed: true }>,
): PermissionPolicy =>
decision.lifetime === "once"
? {
...policy,
consumed_grant_ids: new Set([
...policy.consumed_grant_ids,
decision.grant_id,
]),
}
: policy;
/** Revoke one grant for every future evaluation. */
export const revokePermission = (
policy: PermissionPolicy,
grantId: string,
): PermissionPolicy => ({
...policy,
revoked_grant_ids: new Set([...policy.revoked_grant_ids, grantId]),
});
/** Drop connection-bound authority when an MCP or CLI session ends. */
export const clearSessionPermissions = (
policy: PermissionPolicy,
): PermissionPolicy => ({
...policy,
grants: policy.grants.filter(
({ lifetime }) => lifetime !== "once" && lifetime !== "session",
),
});
/** Atomically replace administrator ceilings while retaining auditable grants. */
export const reloadPermissionCeilings = (
policy: PermissionPolicy,
ceilings: readonly PermissionCeiling[],
): PermissionPolicy => ({
...policy,
ceilings: ceilings.map(normalizeScope),
});
const normalizeScope = (scope: PermissionScope): PermissionScope => ({
capability: scope.capability,
roots: uniqueSorted(scope.roots.map((path) => resolve(path))),
executables: uniqueSorted(scope.executables.map((path) => resolve(path))),
environment_names: uniqueSorted(scope.environment_names),
...(scope.origins === undefined
? {}
: { origins: uniqueSorted(scope.origins) }),
network: scope.network,
mount: scope.mount,
});
const normalizeGrant = (grant: PermissionGrant): PermissionGrant => ({
...normalizeScope(grant),
grant_id: grant.grant_id,
lifetime: grant.lifetime,
operation_identity: grant.operation_identity,
expires_at: grant.expires_at,
});
const normalizeRequest = (request: PermissionRequest): PermissionRequest => ({
...normalizeScope(request),
operation_identity: request.operation_identity,
});
const missingFromScopes = (
request: PermissionScope,
scopes: readonly PermissionScope[],
): MissingPermissionScope => {
const relevant = scopes.filter(
({ capability }) => capability === request.capability,
);
const roots = request.roots.filter(
(path) => !relevant.some((scope) => containsAny(scope.roots, path)),
);
const executables = request.executables.filter(
(path) => !relevant.some((scope) => containsAny(scope.executables, path)),
);
const environmentNames = request.environment_names.filter(
(name) => !relevant.some((scope) => scope.environment_names.includes(name)),
);
const origins = (request.origins ?? []).filter(
(origin) =>
!relevant.some((scope) => (scope.origins ?? []).includes(origin)),
);
const network =
request.network === "none" ||
relevant.some(
(scope) => networkRank(scope.network) >= networkRank(request.network),
)
? undefined
: request.network;
const mount =
!request.mount || relevant.some((scope) => scope.mount)
? undefined
: (true as const);
return {
...(roots.length === 0 ? {} : { roots }),
...(executables.length === 0 ? {} : { executables }),
...(environmentNames.length === 0
? {}
: { environment_names: environmentNames }),
...(origins.length === 0 ? {} : { origins }),
...(network === undefined ? {} : { network }),
...(mount === undefined ? {} : { mount }),
};
};
interface PathOperations {
readonly relative: typeof relative;
readonly isAbsolute: typeof isAbsolute;
readonly sep: string;
}
const HOST_PATH_OPERATIONS: PathOperations = { relative, isAbsolute, sep };
/** Test whether a candidate is inside a root using one platform path flavor. */
export const isPathContained = (
root: string,
candidate: string,
operations: PathOperations = HOST_PATH_OPERATIONS,
): boolean => {
const relation = operations.relative(root, candidate);
return (
relation === "" ||
(relation !== ".." &&
!relation.startsWith(`..${operations.sep}`) &&
!operations.isAbsolute(relation))
);
};
const containsAny = (roots: readonly string[], candidate: string): boolean =>
roots.some((root) => isPathContained(root, candidate));
const networkRank = (network: PermissionNetwork): number => {
switch (network) {
case "none":
return 0;
case "loopback":
return 1;
case "external":
return 2;
}
};
const isExpired = (grant: PermissionGrant, now: Date): boolean =>
grant.expires_at !== null && Date.parse(grant.expires_at) <= now.getTime();
const hasMissing = (missing: MissingPermissionScope): boolean =>
Object.keys(missing).length > 0;
const uniqueSorted = (values: readonly string[]): readonly string[] =>
[...new Set(values)].sort((left, right) => left.localeCompare(right));
+3 -1
View File
@@ -268,7 +268,8 @@ export interface UnverifiedProcessCapture {
| "protocol"
| "shim"
| "cleanup"
| "network";
| "network"
| "environment";
readonly reason: string;
}[];
readonly cleanup: {
@@ -487,6 +488,7 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
"shim",
"cleanup",
"network",
"environment",
]),
reason: z.string(),
}),
@@ -68,8 +68,7 @@ const validateTransitionDeclaration = (
if (declared !== undefined) {
const stateAfter =
declared.target.kind === "goto" ? declared.target.state : null;
const outcome =
declared.target.kind === "finish" ? declared.target.outcome : null;
const outcome = declared.target.kind === "finish" ? "passed" : null;
require(transition.state_after === stateAfter &&
transition.outcome ===
outcome, path, "reactive transition target or outcome differs from the committed graph");
+4 -3
View File
@@ -459,10 +459,11 @@ export const compareProcessCaptures = (
"Residual unknowns prevent proving that no divergence occurred.",
} as const)
: observedFirstDivergence;
const observedStatus = deriveProcessComparisonStatus(
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => dimensions[dimension]),
);
return {
status: deriveProcessComparisonStatus(
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => dimensions[dimension]),
),
status: observedStatus,
...dimensions,
first_divergence: firstDivergence,
...(trace === undefined ? {} : { trace }),
+1 -5
View File
@@ -15,11 +15,7 @@ import {
export const terminalTrigger = (literal = "Ready") => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal,
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: false,
@@ -50,7 +46,7 @@ export const finish = (
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
target: { kind: "finish" },
});
export const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
+16 -35
View File
@@ -7,14 +7,7 @@ import {
const terminalTrigger = () => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal: "Ready",
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: false,
});
const finishTransition = () => ({
@@ -23,7 +16,7 @@ const finishTransition = () => ({
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "checkpoint" as const, name: "ready" }],
target: { kind: "finish" as const, outcome: "passed" as const },
target: { kind: "finish" as const },
});
const baseScenario = () => ({
@@ -58,7 +51,6 @@ const buildLargeCallerScenario = () => {
const sendInputs = Array.from({ length: 300 }, () => ({
type: "send_input",
data: "x",
sensitive: false,
}));
states[0]!.on = Array.from({ length: 130 }, (_, index) => ({
id: `transition_${String(index)}`,
@@ -69,7 +61,7 @@ const buildLargeCallerScenario = () => {
target:
index > 0 && index <= 39
? { kind: "goto", state: `state_${String(index)}` }
: { kind: "finish", outcome: "passed" },
: { kind: "finish" },
}));
for (let index = 1; index < states.length; index += 1) {
const state = states[index]!;
@@ -118,16 +110,25 @@ const REJECTION_FIELD: Readonly<
path: ["states", 0, "on", 0, "when", "cardinality", "min"],
code: "too_small",
},
"unsupported terminal interpretation": {
path: ["states", 0, "on", 0, "when", "control_sequences"],
code: "invalid_value",
},
};
describe("process reactive scenario schema", () => {
it("parses a terminal scenario", () => {
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
initial_state: "starting",
states: [
{
on: [
{
when: {
occurrence: 1,
since: { kind: "scenario_start" },
consume: false,
},
},
],
},
],
});
});
@@ -159,7 +160,7 @@ describe("process reactive scenario schema", () => {
when: { ...terminalTrigger(), literal },
actions: [
{ type: "checkpoint", name: checkpoint },
{ type: "send_input", data, sensitive: false },
{ type: "send_input", data },
],
},
],
@@ -239,26 +240,6 @@ describe("process reactive scenario schema", () => {
],
},
],
[
"unsupported terminal interpretation",
{
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [
{
...finishTransition(),
when: {
...terminalTrigger(),
control_sequences: "strip_ansi",
},
},
],
},
],
},
],
])("rejects %s at the expected field", (_name, input) => {
const expected = REJECTION_FIELD[_name];
expect(expected, `no expected rejection field for ${_name}`).toBeDefined();
+12 -15
View File
@@ -30,6 +30,9 @@ const ignoredFieldSchema = z.enum([
"scheduled_at_ms",
"dispatched_at_ms",
"elapsed_ms",
"files",
"effects",
"truncated",
]);
interface EventTrigger {
@@ -44,11 +47,7 @@ interface EventTrigger {
interface TerminalTextTrigger {
readonly kind: "terminal_text";
readonly view: "decoded";
readonly encoding: "utf8";
readonly literal: string;
readonly case_sensitive: true;
readonly control_sequences: "include";
readonly occurrence: number;
readonly since: ProcessReactiveFrontier;
readonly consume: boolean;
@@ -91,30 +90,28 @@ const processReactiveTriggerSchema: z.ZodType<ProcessReactiveTrigger> = z.lazy(
exact: jsonValueSchema,
ignore_fields: z
.array(ignoredFieldSchema)
.default([])
.refine((values) => new Set(values).size === values.length, {
message: "ignored event fields must be unique",
}),
since: frontierSchema,
consume: z.boolean(),
since: frontierSchema.default({ kind: "scenario_start" }),
consume: z.boolean().default(false),
cardinality: z
.strictObject({
min: z.number().int().safe().positive(),
max: z.number().int().safe().positive(),
})
.default({ min: 1, max: 1 })
.refine(({ min, max }) => min <= max, {
message: "cardinality min must not exceed max",
}),
}),
z.strictObject({
kind: z.literal("terminal_text"),
view: z.literal("decoded"),
encoding: z.literal("utf8"),
literal: z.string().min(1),
case_sensitive: z.literal(true),
control_sequences: z.literal("include"),
occurrence: z.number().int().safe().positive(),
since: frontierSchema,
consume: z.boolean(),
occurrence: z.number().int().safe().positive().default(1),
since: frontierSchema.default({ kind: "scenario_start" }),
consume: z.boolean().default(false),
}),
z.strictObject({
kind: z.literal("all"),
@@ -154,7 +151,7 @@ const processReactiveActionSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("send_input"),
data: z.string(),
sensitive: z.boolean(),
sensitive: z.boolean().default(false),
}),
z.strictObject({
type: z.literal("resize"),
@@ -173,7 +170,7 @@ export type ProcessReactiveAction = z.infer<typeof processReactiveActionSchema>;
const transitionTargetSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("goto"), state: identifierSchema }),
z.strictObject({ kind: z.literal("finish"), outcome: z.literal("passed") }),
z.strictObject({ kind: z.literal("finish") }),
]);
const transitionSchema = z.strictObject({
+1 -1
View File
@@ -36,7 +36,7 @@ const createTransitionRecord = (input: {
? {
...state,
state_after: null,
outcome: input.transition.target.outcome,
outcome: "passed",
}
: {
...state,
+39 -57
View File
@@ -3,6 +3,21 @@ import { describe, expect, it } from "vitest";
import { processScenarioSchema } from "./processScenario.js";
describe("process scenario collection inputs", () => {
it("accepts OS environment names without imposing shell identifier syntax", () => {
const environment = { "app.setting": "value", "1": "numbered" };
expect(
processScenarioSchema.parse({ executable: "node", environment })
.environment,
).toEqual(environment);
for (const name of ["", "KEY=VALUE", "KEY\0VALUE"])
expect(
processScenarioSchema.safeParse({
executable: "node",
environment: { [name]: "value" },
}).success,
).toBe(false);
});
it("accepts more than 64 named filesystem checkpoints", () => {
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
@@ -177,16 +192,11 @@ describe("process scenario large interaction inputs", () => {
executable: "/bin/echo",
arguments: Array.from({ length: 257 }, (_, index) => String(index)),
working_directory: "/tmp",
filesystem_roots: Array.from(
filesystem_observation_paths: Array.from(
{ length: 17 },
(_, index) => `/tmp/root-${index}`,
),
environment,
inherit_environment: Array.from(
{ length: 65 },
(_, index) => `INHERITED_${index}`,
),
secret_aliases: Object.keys(environment),
command_shims: commandShims,
events: Array.from({ length: 1_001 }, () => ({
type: "input" as const,
@@ -220,12 +230,11 @@ describe("process scenario large interaction inputs", () => {
});
expect(scenario.arguments).toHaveLength(257);
expect(scenario.inherit_environment).toHaveLength(65);
expect(scenario.command_shims).toHaveLength(33);
expect(scenario.command_shims[0]?.routes).toHaveLength(101);
expect(scenario.command_shims[0]?.routes[0]?.outputs).toHaveLength(1_001);
expect(scenario.events).toHaveLength(1_001);
expect(scenario.filesystem_roots).toHaveLength(17);
expect(scenario.filesystem_observation_paths).toHaveLength(17);
expect(scenario.checkpoints[0]?.trigger).toMatchObject({
occurrence: 1_001,
});
@@ -236,63 +245,36 @@ describe("process scenario large interaction inputs", () => {
});
});
describe("process scenario path portability", () => {
const base = { arguments: [], environment: {}, filesystem_roots: [] };
describe("minimal process scenario inputs", () => {
const scenario = {
arguments: [],
environment: {},
filesystem_observation_paths: [],
};
it("defaults working directory at execution and accepts command names", () => {
const parsed = processScenarioSchema.parse({
...scenario,
executable: "node",
});
expect(parsed.working_directory).toBe(".");
expect(parsed.executable).toBe("node");
expect(parsed.filesystem_observation_paths).toEqual([]);
});
});
describe("process scenario path portability", () => {
it.each([
["posix", "/usr/bin/node", "/tmp"],
["windows drive with backslashes", "C:\\tools\\node.exe", "C:\\work"],
["windows drive with forward slashes", "c:/tools/node.exe", "c:/work"],
["unc share", "\\\\server\\share\\node.exe", "\\\\server\\share"],
])(
"accepts a %s path on any host",
"preserves a %s scenario on any host",
(_label, executable, working_directory) => {
const parsed = processScenarioSchema.safeParse({
...base,
executable,
working_directory,
});
expect(parsed.success).toBe(true);
expect(
processScenarioSchema.parse({ executable, working_directory }),
).toMatchObject({ executable, working_directory });
},
);
it("accepts Windows filesystem roots", () => {
const parsed = processScenarioSchema.safeParse({
...base,
executable: "C:\\tools\\node.exe",
working_directory: "C:\\work",
filesystem_roots: ["C:\\data", "D:\\more"],
});
expect(parsed.success).toBe(true);
});
it.each([
["relative", "tools/node.exe"],
["dot relative", "./node.exe"],
["parent relative", "../node.exe"],
["bare filename", "node.exe"],
["empty", ""],
])("still rejects a %s path", (_label, executable) => {
const parsed = processScenarioSchema.safeParse({
...base,
executable,
working_directory: "/tmp",
});
expect(parsed.success).toBe(false);
});
it("names the constraint so a rejected path is actionable", () => {
const parsed = processScenarioSchema.safeParse({
...base,
executable: "tools/node.exe",
working_directory: "/tmp",
});
expect(parsed.success).toBe(false);
if (parsed.success) return;
const messages = parsed.error.issues
.map(({ message }) => message)
.join("\n");
expect(messages).toContain("must be absolute");
expect(messages).toContain("C:\\tools\\node.exe");
});
});
+34 -152
View File
@@ -1,5 +1,4 @@
import { createHash } from "node:crypto";
import { isPathWithinRoot } from "./localPath.js";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
@@ -10,10 +9,10 @@ import { replayMachineSchema } from "./replayMachine.js";
const positiveBudget = z.number().int().safe().positive();
const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
const environmentName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
const environmentName = z
.string()
.regex(/^[^=\0]+$/u, "Environment names cannot contain '=' or NUL");
const reservedEnvironment = new Set([
"HOME",
"TERM",
"REA_PROCESS_RUN_ID",
"REA_REPLAY_HTTP_URL",
"REA_REPLAY_WEBSOCKET_URL",
@@ -70,34 +69,46 @@ const reactiveScenarioCommitment = (
})),
};
/** Build the secret-safe scenario projection committed by process-capture Evidence. */
const committedScenarioEvents = (
events: ProcessScenario["events"],
includeSensitiveInputLength: boolean,
): ProcessScenario["events"] =>
events.map((event) =>
event.type === "input" && event.sensitive
? {
...event,
data: includeSensitiveInputLength
? `<redacted-input:${String(Buffer.byteLength(event.data))}-bytes>`
: "<redacted-input>",
}
: event,
);
/** Build the caller-selected scenario projection committed by process-capture Evidence. */
export const processScenarioCommitment = (
scenario: ProcessScenario,
executableSha256?: string,
): Readonly<Record<string, unknown>> => ({
...scenario,
environment: Object.fromEntries(
Object.entries(scenario.environment).map(([name, value]) => [
name,
scenario.secret_aliases.includes(name) ? "<redacted-secret>" : value,
]),
),
events: committedScenarioEvents(scenario.events, true),
reactive: reactiveScenarioCommitment(scenario.reactive),
executable_sha256: executableSha256 ?? null,
});
/** Project observation settings shared by authority and reconstruction. */
/** Project observation settings shared by capture and reconstruction. */
export const processComparisonContract = (
scenario: ProcessScenario,
): Readonly<Record<string, unknown>> => ({
working_directory: scenario.working_directory,
inherit_environment: scenario.inherit_environment,
secret_aliases: scenario.secret_aliases,
network_access: scenario.network_access,
filesystem_roots: scenario.filesystem_roots,
environment: scenario.environment,
ambient_environment: "unknown",
filesystem_observation_paths: scenario.filesystem_observation_paths,
terminal: scenario.terminal,
checkpoints: scenario.checkpoints,
events: scenario.events,
// Input bytes are intentionally absent from compatibility identity. Their
// redacted observations remain unknown, so equal commitments never imply
// that two secret values were the same.
events: committedScenarioEvents(scenario.events, false),
timeout_ms: scenario.timeout_ms,
idle_timeout_ms: scenario.idle_timeout_ms,
settle_ms: scenario.settle_ms,
@@ -108,44 +119,17 @@ export const processComparisonContract = (
reactive: reactiveScenarioCommitment(scenario.reactive),
});
/**
* True when `value` is an absolute path for *any* supported host.
*
* `node:path`'s `isAbsolute` answers for the machine running it: on Linux
* `C:\tools` is not absolute. A boundary schema must not vary with the host
* that evaluates it — a scenario captured on Windows has to stay valid when it
* is replayed, compared, or validated by a test on Linux. So this accepts the
* POSIX form, a Windows drive path, and a UNC share, on every host.
*/
export const isAbsoluteScenarioPath = (value: string): boolean =>
value.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(value) ||
value.startsWith("\\\\");
/**
* An absolute path for the host that will run the scenario. The message names
* the constraint so a rejected path is actionable, instead of leaving the
* caller to infer it from a generic "invalid request".
*/
const absoluteScenarioPath = z.string().refine(isAbsoluteScenarioPath, {
message:
"Path must be absolute: a POSIX path such as /usr/bin/node, a Windows path such as C:\\tools\\node.exe, or a UNC path such as \\\\server\\share",
});
/**
* Boundary schema for one bounded process experiment.
* Defaults are part of the evidence contract and must remain deterministic.
*/
export const processScenarioSchema = z
.object({
executable: absoluteScenarioPath,
executable: z.string().min(1),
arguments: z.array(z.string()).default([]),
working_directory: absoluteScenarioPath,
working_directory: z.string().default("."),
environment: z.record(environmentName, z.string()).default({}),
inherit_environment: z.array(environmentName).default([]),
secret_aliases: z.array(environmentName).default([]),
network_access: z.literal("host").default("host"),
filesystem_roots: z.array(absoluteScenarioPath).default([]),
filesystem_observation_paths: z.array(z.string().min(1)).default([]),
terminal: z
.object({
columns: z.number().int().min(1).max(65_535).default(80),
@@ -249,7 +233,7 @@ export const processScenarioSchema = z
}),
normalization: z
.object({
paths: z.boolean().default(true),
paths: z.boolean().default(false),
pids: z.boolean().default(true),
ports: z.boolean().default(true),
time_bucket_ms: positiveBudget.default(10),
@@ -263,7 +247,7 @@ export const processScenarioSchema = z
.default([]),
})
.default({
paths: true,
paths: false,
pids: true,
ports: true,
time_bucket_ms: 10,
@@ -324,18 +308,8 @@ export const processScenarioSchema = z
});
}
}
const secrets = new Set(scenario.secret_aliases);
for (const alias of secrets) {
if (!(alias in scenario.environment)) {
context.addIssue({
code: "custom",
message: "secret alias has no environment value",
path: ["secret_aliases"],
});
}
}
const explicit = new Set(Object.keys(scenario.environment));
for (const name of [...explicit, ...scenario.inherit_environment]) {
for (const name of explicit) {
if (reservedEnvironment.has(name)) {
context.addIssue({
code: "custom",
@@ -344,15 +318,6 @@ export const processScenarioSchema = z
});
}
}
for (const name of scenario.inherit_environment) {
if (explicit.has(name)) {
context.addIssue({
code: "custom",
message: "an environment name cannot be explicit and inherited",
path: ["inherit_environment"],
});
}
}
for (const event of scenario.events) {
if (event.at_ms > scenario.timeout_ms) {
context.addIssue({
@@ -410,86 +375,3 @@ export type ProcessScenario = z.infer<typeof processScenarioSchema>;
/** Parse untrusted process scenario input and apply safe default budgets. */
export const parseProcessScenario = (input: unknown): ProcessScenario =>
processScenarioSchema.parse(input);
/** Complete operator-owned ceiling for enabled process capture. */
export interface EnabledProcessExecutionPolicy {
readonly status: "enabled";
readonly executableRoots: readonly [string, ...string[]];
readonly workingRoots: readonly [string, ...string[]];
readonly allowedEnvironment: readonly string[];
readonly networkAccess: "none" | "external";
}
/** Parsed operator-owned process-capture policy. */
export type ProcessExecutionPolicy =
| { readonly status: "disabled" }
| EnabledProcessExecutionPolicy;
/** Explicit authorization result; denial reasons are safe to show callers. */
export type ProcessPolicyDecision =
| { readonly allowed: true }
| {
readonly allowed: false;
readonly reason:
| "process capture is disabled"
| "host network access is not approved by operator policy"
| "executable is outside approved roots"
| "working directory is outside approved roots"
| "scenario requests an environment variable not allowed by policy"
| "filesystem root is outside approved roots";
};
/** Evaluate scenario authority before any process or filesystem side effect occurs. */
export const authorizeProcessScenario = (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): ProcessPolicyDecision => {
if (policy.status === "disabled")
return { allowed: false, reason: "process capture is disabled" };
if (scenario.network_access === "host" && policy.networkAccess === "none")
return {
allowed: false,
reason: "host network access is not approved by operator policy",
};
if (
!policy.executableRoots.some((root) =>
isPathWithinRoot(root, scenario.executable),
)
) {
return { allowed: false, reason: "executable is outside approved roots" };
}
if (
!policy.workingRoots.some((root) =>
isPathWithinRoot(root, scenario.working_directory),
)
) {
return {
allowed: false,
reason: "working directory is outside approved roots",
};
}
const requestedNames = [
...Object.keys(scenario.environment),
...scenario.inherit_environment,
];
if (
requestedNames.some((name) => !policy.allowedEnvironment.includes(name))
) {
return {
allowed: false,
reason: "scenario requests an environment variable not allowed by policy",
};
}
if (
scenario.filesystem_roots.some(
(path) =>
!policy.workingRoots.some((root) => isPathWithinRoot(root, path)),
)
) {
return {
allowed: false,
reason: "filesystem root is outside approved roots",
};
}
return { allowed: true };
};
+23 -18
View File
@@ -7,7 +7,6 @@ import {
decodeJsonRpc,
decodeMessagePack,
inferMessageSchema,
looksLikeCredential,
protocolCaptureSchema,
type ProtocolMessage,
} from "./protocolCapture.js";
@@ -70,13 +69,6 @@ describe("protocol capture", () => {
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
expect(classifyProtocolFamily(null, null)).toBeNull();
});
it("detects credential-like field names", () => {
expect(looksLikeCredential("password")).toBe(true);
expect(looksLikeCredential("api_key")).toBe(true);
expect(looksLikeCredential("authorization")).toBe(true);
expect(looksLikeCredential("username")).toBe(false);
});
});
describe("JSON-RPC decoding", () => {
@@ -112,22 +104,35 @@ describe("JSON-RPC decoding", () => {
});
});
it("redacts credential-like fields", () => {
it("preserves decoded fields whose names resemble credentials", () => {
const payload = new TextEncoder().encode(
JSON.stringify({
password: "secret123",
password: "observed-value",
authorization: { scheme: "custom", value: "observed-header" },
username: "admin",
}),
);
const result = decodeJsonRpc(payload);
const passwordField = result.decoded_fields.find(
(f) => f.path === "password",
);
expect(passwordField?.value).toBe("[REDACTED]");
const usernameField = result.decoded_fields.find(
(f) => f.path === "username",
);
expect(usernameField?.value).toBe("admin");
expect(result.decoded_fields).toEqual([
{
path: "password",
wire_type: "json",
value: "observed-value",
inferred: false,
},
{
path: "authorization",
wire_type: "json",
value: { scheme: "custom", value: "observed-header" },
inferred: false,
},
{
path: "username",
wire_type: "json",
value: "admin",
inferred: false,
},
]);
});
});
+8 -37
View File
@@ -59,7 +59,7 @@ export const protocolMessageSchema = z.strictObject({
schema_hypotheses: z.array(schemaHypothesisSchema).default([]),
/** Whether decoding was truncated. */
truncated: z.boolean().default(false),
/** Whether credentials were detected and redacted. */
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
});
export type ProtocolMessage = z.infer<typeof protocolMessageSchema>;
@@ -74,7 +74,7 @@ export const protocolCaptureSchema = z.strictObject({
inferred_schema: z.array(schemaHypothesisSchema).default([]),
/** Whether any message was truncated. */
has_truncated: z.boolean().default(false),
/** Whether credentials were detected and redacted. */
/** Whether the capture producer marked credential content as redacted. */
credentials_detected: z.boolean().default(false),
});
@@ -101,26 +101,6 @@ export function classifyProtocolFamily(
return null;
}
/** Credential-like field names that should be redacted. */
const CREDENTIAL_PATTERNS = [
"password",
"passwd",
"secret",
"token",
"api_key",
"apikey",
"authorization",
"auth",
"credential",
"private_key",
];
/** Check if a field path looks like it may contain credentials. */
export function looksLikeCredential(path: string): boolean {
const lower = path.toLowerCase();
return CREDENTIAL_PATTERNS.some((p) => lower.includes(p));
}
/** Decode a JSON-RPC message from raw payload bytes. */
export function decodeJsonRpc(rawPayload: Uint8Array): {
decoded_fields: DecodedField[];
@@ -132,21 +112,12 @@ export function decodeJsonRpc(rawPayload: Uint8Array): {
if (typeof parsed === "object" && parsed !== null) {
for (const [key, value] of Object.entries(parsed)) {
if (looksLikeCredential(key)) {
fields.push({
path: key,
wire_type: "json",
value: "[REDACTED]",
inferred: false,
});
} else {
fields.push({
path: key,
wire_type: "json",
value,
inferred: false,
});
}
fields.push({
path: key,
wire_type: "json",
value,
inferred: false,
});
}
}
-111
View File
@@ -280,79 +280,6 @@ const DOCUMENTATION_DIRECTORY_NAMES = new Set([
"man",
]);
const SECRET_BASENAMES = new Set([
"id_rsa",
"id_ed25519",
"pgpass",
".netrc",
".npmrc",
".pypirc",
".envrc",
".env.local",
".env.production",
".env.development",
".env.test",
".env.staging",
".env.example",
"auth.json",
"auth.yaml",
"auth.yml",
"token.json",
"tokens.json",
"credentials.json",
"secrets.json",
"google-services.json",
"service-account.json",
".htpasswd",
]);
const SECRET_BASENAME_PREFIXES = [
".env",
".env.",
"private",
"secret",
"secrets",
"credential",
"credentials",
"token",
"tokens",
"password",
"passwords",
"auth",
"apikey",
"api-key",
"api_key",
"service-account",
"kubeconfig",
];
const SECRET_BASENAME_SUFFIXES = [
".pem",
".key",
".p12",
".gpg",
".pgp",
".keystore",
];
const SECRET_PATH_SEGMENTS = new Set([
".ssh",
".aws",
".gnupg",
".pki",
".docker",
".secrets",
"secrets",
"secret",
"private",
"credentials",
"tokens",
"passwords",
"passphrase",
"kubernetes",
"k8s",
]);
const filenameIsTest = (filename: string): boolean => {
const lower = filename.toLowerCase();
if (lower.includes(".test.") || lower.includes(".spec.")) return true;
@@ -391,44 +318,6 @@ const isPathUnderAny = (path: string, names: ReadonlySet<string>): boolean => {
return false;
};
const secretPrefixMatches = (filename: string): boolean => {
const lower = filename.toLowerCase();
for (const prefix of SECRET_BASENAME_PREFIXES) {
const prefixLower = prefix.toLowerCase();
if (!lower.startsWith(prefixLower)) continue;
const nextIndex = prefixLower.length;
if (nextIndex < lower.length) {
const next = lower[nextIndex];
if (next !== "." && next !== "_" && next !== "-") continue;
}
const extension = basenameParts(filename).ext.toLowerCase();
if (CODE_EXTENSIONS.has(extension)) continue;
return true;
}
return false;
};
/** Return true when a path or any parent segment matches common secret patterns. */
export const isSecretLikePath = (path: string): boolean => {
const parts = path.split("/").filter((segment) => segment !== "");
for (const segment of parts) {
const lower = segment.toLowerCase();
if (SECRET_PATH_SEGMENTS.has(lower)) return true;
}
const filename = parts[parts.length - 1];
if (filename === undefined) return false;
const lower = filename.toLowerCase();
if (SECRET_BASENAMES.has(lower)) return true;
if (secretPrefixMatches(filename)) return true;
for (const suffix of SECRET_BASENAME_SUFFIXES) {
if (lower.endsWith(suffix.toLowerCase())) return true;
}
return false;
};
/** Detect a source language from a POSIX path. */
export const detectReferenceSourceLanguage = (path: string): string | null => {
const filename = posix.basename(path);
+25 -1
View File
@@ -184,6 +184,30 @@ describe("historical source graph", () => {
}
});
it("retains actual external targets and accepts legacy markers", () => {
const input = { ...graphInput(), inventory_state: "partial" as const };
input.entries[2] = symlinkEntry({
target: "/private/shared/target.js",
target_state: "external",
});
const graph = createHistoricalSourceGraph(input);
expect(graph.entries[2]).toMatchObject({
kind: "symlink",
target: "/private/shared/target.js",
target_state: "external",
});
expect(() =>
createHistoricalSourceGraph({
...input,
entries: input.entries.map((entry) =>
entry.kind === "symlink"
? { ...entry, target: "<outside-root>" }
: entry,
),
}),
).not.toThrow();
});
it("derives language and manifest indexes and enforces code-point order", () => {
const input = graphInput();
input.entries[1] = fileEntry({ classifications: ["source", "test"] });
@@ -298,7 +322,7 @@ describe("historical source graph validation", () => {
: entry,
),
}),
).toThrow();
).not.toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
+14 -4
View File
@@ -82,12 +82,18 @@ const symlinkTargetSchema = z
.refine(
(target) =>
target === "<outside-root>" ||
isPortableAbsoluteSymlinkTarget(target) ||
(!target.startsWith("/") &&
!target.includes("\\") &&
posix.normalize(target) === target),
"Expected a normalized POSIX symlink target",
);
const isPortableAbsoluteSymlinkTarget = (target: string): boolean =>
target.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(target) ||
/^\\\\[^\\/]+[\\/][^\\/]+/u.test(target);
const sourceSymlinkSchema = z.strictObject({
...entryBaseShape,
kind: z.literal("symlink"),
@@ -320,14 +326,18 @@ const checkSymlinks = (
): void => {
for (const [index, entry] of graph.entries.entries()) {
if (entry.kind !== "symlink") continue;
const absolute = isPortableAbsoluteSymlinkTarget(entry.target);
if (
(entry.target_state === "external") !==
(entry.target === "<outside-root>")
(entry.target_state === "external" &&
entry.target !== "<outside-root>" &&
!absolute) ||
(entry.target_state === "internal" &&
(entry.target === "<outside-root>" || absolute)) ||
(entry.target_state === "missing" && entry.target === "<outside-root>")
)
context.addIssue({
code: "custom",
message:
"External symlink targets must use the sanitized <outside-root> sentinel",
message: "Symlink target path does not match its target state",
path: ["entries", index, "target"],
});
if (entry.target_state !== "internal") continue;
+1 -8
View File
@@ -8,7 +8,7 @@ import {
const digest = (character: string): string => character.repeat(64);
describe("provider-neutral runtime characterization plan", () => {
it("commits preparation separately from execution approval", () => {
it("commits the selected preparation inputs", () => {
const plan = createRuntimeCharacterizationPlan({
preparation_sha256: digest("5"),
artifact: {
@@ -50,16 +50,9 @@ describe("provider-neutral runtime characterization plan", () => {
identifiers: "deterministic",
seed: 7,
},
authority: {
preparation_approved: true,
execution_approved: false,
network: "none",
provider_owned_process_only: true,
},
});
expect(parseRuntimeCharacterizationPlan(plan)).toEqual(plan);
expect(plan.authority.execution_approved).toBe(false);
expect(() =>
parseRuntimeCharacterizationPlan({
...plan,
+1 -7
View File
@@ -57,19 +57,13 @@ export const runtimeCharacterizationPlanSchema = z.strictObject({
identifiers: z.enum(["deterministic", "runtime"]),
seed: z.number().int().min(0).max(0xffff_ffff),
}),
authority: z.strictObject({
preparation_approved: z.literal(true),
execution_approved: z.literal(false),
network: z.enum(["none", "loopback"]),
provider_owned_process_only: z.literal(true),
}),
});
export type RuntimeCharacterizationPlan = z.infer<
typeof runtimeCharacterizationPlanSchema
>;
/** Commit a provider-neutral preparation plan; execution requires a later approval. */
/** Commit a provider-neutral preparation plan; execution checks the resulting content identity. */
export const createRuntimeCharacterizationPlan = (
input: Omit<z.input<typeof runtimeCharacterizationPlanSchema>, "plan_sha256">,
): RuntimeCharacterizationPlan => {
+11
View File
@@ -0,0 +1,11 @@
/** Validate optional source-map content against its source inventory. */
export const hasValidSourceMapContents = (
sourceCount: number,
contents: unknown,
): boolean =>
contents === undefined ||
(Array.isArray(contents) &&
contents.length === sourceCount &&
contents.every(
(content: unknown) => content === null || typeof content === "string",
));
+4 -4
View File
@@ -34,7 +34,7 @@ describe("web bundle analyzer", () => {
expect.objectContaining({
kind: "static_import",
specifier: "./chunk.js?token=secret",
resolved_url: `${origin}/assets/chunk.js?token=%5BREDACTED%5D`,
resolved_url: `${origin}/assets/chunk.js?token=secret`,
}),
expect.objectContaining({
kind: "dynamic_import",
@@ -43,11 +43,11 @@ describe("web bundle analyzer", () => {
]),
);
expect(result.observations.routes).toEqual([
expect.objectContaining({ value: "/users/:id?token=%5BREDACTED%5D" }),
expect.objectContaining({ value: "/users/:id?token=secret" }),
]);
expect(result.observations.endpoints).toEqual([
expect.objectContaining({
value: "/api/users?authorization=%5BREDACTED%5D",
value: "/api/users?authorization=secret",
}),
]);
expect(result.observations.webmcp_declarations).toEqual([
@@ -63,7 +63,7 @@ describe("web bundle analyzer", () => {
expect.objectContaining({ value: "Vue" }),
]),
);
expect(JSON.stringify(result)).not.toContain("authorization=secret");
expect(JSON.stringify(result)).toContain("authorization=secret");
expect(result.completeness.status).toBe("complete");
});
+1 -1
View File
@@ -7,7 +7,7 @@ import {
import { buildWebBundleAnalysis } from "./webBundleAnalyzerResult.js";
import type { WebBundleAnalysis } from "./webBundleAnalysis.js";
/** Analyze captured, explicitly approved JavaScript source without execution. */
/** Analyze selected captured JavaScript source without execution. */
export const analyzeCapturedWebBundle = (
inspection: WebPageInspection,
sourceMaps: WebBundleAnalysis["observations"]["source_maps"] = {
+2 -2
View File
@@ -48,8 +48,8 @@ export const compareWebCaptures = (
limitations: [
"A changed status proves an observed difference; an unknown status means absence could not be established from capture completeness.",
"Network comparison covers only activity observed after each CDP attachment.",
"Accessibility roles, ignored state, text, and hierarchy are compared only when the accessibility tree was fully captured and text capture was approved and not truncated.",
"Storage key inventories are compared only when approved and complete; usage and quota are compared only when reported. Redacted content is compared through complete SHA-256 fingerprints.",
"Accessibility roles, ignored state, text, and hierarchy are compared only when the accessibility tree was fully captured and text capture was selected and not truncated.",
"Storage key inventories are compared only when selected and complete; usage and quota are compared only when reported. Redacted content is compared through complete SHA-256 fingerprints.",
],
});
};