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:
@@ -7,16 +7,12 @@ const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
source: "literal",
|
||||
value,
|
||||
classification: "public",
|
||||
});
|
||||
|
||||
const baseScenario = () => ({
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium/chrome",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: {
|
||||
url: "https://app.example.test/",
|
||||
@@ -37,7 +33,6 @@ const baseScenario = () => ({
|
||||
kind: "role",
|
||||
role: "button",
|
||||
name: "Sign in",
|
||||
exact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -91,26 +86,16 @@ const baseScenario = () => ({
|
||||
{
|
||||
secret_id: "session",
|
||||
environment_variable: "REA_TEST_SESSION",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "login_input",
|
||||
environment_variable: "REA_TEST_PASSWORD",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "cookie",
|
||||
environment_variable: "REA_TEST_COOKIE",
|
||||
purpose: "storage",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: ["token"],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: ["screenshot", "url", "accessibility"],
|
||||
at_end: ["dom", "storage"],
|
||||
@@ -125,6 +110,7 @@ describe("browserScenarioSchema", () => {
|
||||
"https://api.example.test",
|
||||
"https://app.example.test",
|
||||
]);
|
||||
expect(parsed.browser).toMatchObject({ mode: "launch", headless: true });
|
||||
expect(parsed.environment).toMatchObject({
|
||||
viewport: { width: 1_280, height: 720, device_scale_factor: 1 },
|
||||
locale: "en-US",
|
||||
@@ -143,15 +129,19 @@ describe("browserScenarioSchema", () => {
|
||||
at_end: ["dom", "storage"],
|
||||
events: ["console", "page-errors", "network", "websockets"],
|
||||
});
|
||||
expect(parsed.redaction.header_names).toEqual([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
expect(parsed).not.toHaveProperty("limits");
|
||||
});
|
||||
|
||||
it("allows callers to choose visible browsers and service workers", () => {
|
||||
const parsed = browserScenarioSchema.parse({
|
||||
...baseScenario(),
|
||||
browser: { ...baseScenario().browser, headless: false },
|
||||
environment: { service_workers: "allow" },
|
||||
});
|
||||
expect(parsed.browser).toMatchObject({ headless: false });
|
||||
expect(parsed.environment.service_workers).toBe("allow");
|
||||
});
|
||||
|
||||
it("accepts caller selected action timeouts without a fixed ceiling", () => {
|
||||
const input = baseScenario();
|
||||
input.actions[0] = { ...input.actions[0], timeout_ms: 120_000 } as never;
|
||||
@@ -184,6 +174,17 @@ describe("browserScenarioSchema", () => {
|
||||
expect(secrets?.redact("prefix-suffix")).toBe("[REDACTED:login_input]");
|
||||
});
|
||||
|
||||
it("does not resolve inherited environment properties as secret values", () => {
|
||||
const scenario = browserScenarioSchema.parse(baseScenario());
|
||||
const environment = Object.assign(
|
||||
{ REA_TEST_PASSWORD: "password", REA_TEST_COOKIE: "cookie" },
|
||||
Object.create({ REA_TEST_SESSION: "session" }) as object,
|
||||
);
|
||||
expect(
|
||||
BrowserScenarioSecrets.resolve(scenario, environment),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects unsupported actions", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions = [
|
||||
@@ -234,7 +235,7 @@ describe("browserScenarioSchema credential handling", () => {
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects missing, duplicate, and unused secret declarations", () => {
|
||||
it("rejects missing and duplicate secret declarations but accepts redaction-only declarations", () => {
|
||||
const missing = baseScenario();
|
||||
missing.secrets = missing.secrets.filter(
|
||||
({ secret_id }) => secret_id !== "login_input",
|
||||
@@ -246,23 +247,35 @@ describe("browserScenarioSchema credential handling", () => {
|
||||
expect(browserScenarioSchema.safeParse(duplicate).success).toBe(false);
|
||||
|
||||
const unused = baseScenario();
|
||||
unused.secrets.push({
|
||||
const redactionOnly = {
|
||||
secret_id: "unused",
|
||||
environment_variable: "REA_TEST_UNUSED",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
});
|
||||
environment_variable: "rea.test-unused",
|
||||
};
|
||||
unused.secrets.push(redactionOnly);
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(true);
|
||||
|
||||
redactionOnly.environment_variable = "INVALID=NAME";
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(false);
|
||||
redactionOnly.environment_variable = "INVALID\0NAME";
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects secret query values without named redaction", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.redaction.query_parameter_names = [];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
it("accepts literal credential headers and rejects provider-owned headers", () => {
|
||||
const credentialHeaders = baseScenario();
|
||||
credentialHeaders.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [
|
||||
{ name: "authorization", value: literal("Bearer caller-value") },
|
||||
{ name: "cookie", value: literal("session=caller-value") },
|
||||
{ name: "set-cookie", value: literal("session=caller-value") },
|
||||
],
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(credentialHeaders).success).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
it("rejects literal credential headers and provider-owned headers", () => {
|
||||
for (const name of ["authorization", "content-length"]) {
|
||||
for (const name of ["content-length", "location", "transfer-encoding"]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
@@ -294,31 +307,41 @@ describe("browserScenarioSchema credential handling", () => {
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects embedded URL credentials and query values", () => {
|
||||
it("preserves inline URL queries and fragments but rejects userinfo", () => {
|
||||
const credentialedUrl = new URL("https://app.example.test/");
|
||||
credentialedUrl.username = String.fromCodePoint(120);
|
||||
for (const url of [
|
||||
credentialedUrl.href,
|
||||
"https://app.example.test/?token=raw",
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.start_url.url = url;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
const invalid = baseScenario();
|
||||
invalid.start_url.url = credentialedUrl.href;
|
||||
expect(browserScenarioSchema.safeParse(invalid).success).toBe(false);
|
||||
|
||||
const scenario = baseScenario();
|
||||
scenario.start_url.url = "https://app.example.test/?q=one&q=two#section";
|
||||
scenario.start_url.query = [];
|
||||
scenario.secrets = scenario.secrets.filter(
|
||||
({ secret_id }) => secret_id !== "session",
|
||||
);
|
||||
const parsed = browserScenarioSchema.parse(scenario);
|
||||
expect(parsed.start_url.url).toBe(
|
||||
"https://app.example.test/?q=one&q=two#section",
|
||||
);
|
||||
});
|
||||
|
||||
it("requires explicit external ownership for CDP connections", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.browser = {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
} as never;
|
||||
it("derives external ownership from CDP connection mode", () => {
|
||||
const scenario = {
|
||||
...baseScenario(),
|
||||
browser: {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
},
|
||||
};
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(true);
|
||||
|
||||
scenario.browser.cleanup = "close-browser" as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
expect(
|
||||
browserScenarioSchema.safeParse({
|
||||
...scenario,
|
||||
browser: { ...scenario.browser, cleanup: "close-browser" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,10 @@ import type {
|
||||
BrowserScenarioUrl,
|
||||
BrowserScenarioValue,
|
||||
} from "../domain/browserScenario.js";
|
||||
import {
|
||||
sanitizeBrowserUrl,
|
||||
type SanitizedBrowserUrl,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { BrowserStorageValueFingerprint } from "../domain/browserScenarioCaptureValues.js";
|
||||
|
||||
const REDACTION_PREFIX = "[REDACTED:";
|
||||
@@ -20,7 +24,11 @@ export class BrowserScenarioSecrets {
|
||||
const values = new Map<string, string>();
|
||||
for (const declaration of scenario.secrets) {
|
||||
const value = environment[declaration.environment_variable];
|
||||
if (value === undefined) return undefined;
|
||||
if (
|
||||
!Object.hasOwn(environment, declaration.environment_variable) ||
|
||||
typeof value !== "string"
|
||||
)
|
||||
return undefined;
|
||||
values.set(declaration.secret_id, value);
|
||||
}
|
||||
return new BrowserScenarioSecrets(values);
|
||||
@@ -54,6 +62,34 @@ export class BrowserScenarioSecrets {
|
||||
return output;
|
||||
}
|
||||
|
||||
/** Remove only declared secret values from one URL and report that action. */
|
||||
sanitizeUrl(value: string): SanitizedBrowserUrl {
|
||||
let output = value;
|
||||
const replacements = [...this.values].sort(
|
||||
([leftId, left], [rightId, right]) =>
|
||||
right.length - left.length ||
|
||||
(leftId < rightId ? -1 : leftId > rightId ? 1 : 0),
|
||||
);
|
||||
for (const [id, secret] of replacements) {
|
||||
if (secret === "") continue;
|
||||
const marker = `${REDACTION_PREFIX}${id}]`;
|
||||
const searchParamsValue = new URLSearchParams([["value", secret]])
|
||||
.toString()
|
||||
.slice("value=".length);
|
||||
for (const candidate of new Set([
|
||||
secret,
|
||||
encodeURIComponent(secret),
|
||||
searchParamsValue,
|
||||
]))
|
||||
output = output.replaceAll(candidate, marker);
|
||||
}
|
||||
const sanitized = sanitizeBrowserUrl(output);
|
||||
return {
|
||||
...sanitized,
|
||||
redacted: sanitized.redacted || output !== value,
|
||||
};
|
||||
}
|
||||
|
||||
fingerprint(value: string): BrowserStorageValueFingerprint {
|
||||
for (const secret of this.values.values())
|
||||
if (secret !== "" && value.includes(secret))
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
BrowserScenarioEvent,
|
||||
BrowserStepArtifacts,
|
||||
} from "../domain/browserScenarioCapture.js";
|
||||
import type { SanitizedBrowserUrl } from "../domain/browserObservation.js";
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
|
||||
@@ -16,6 +17,7 @@ export interface BrowserScenarioSessionPort {
|
||||
readonly version: string;
|
||||
readonly initialUrl: string;
|
||||
currentUrl(): string;
|
||||
sanitizeUrl(value: string): SanitizedBrowserUrl;
|
||||
setStep(index: number): void;
|
||||
nextEventSequence(): number;
|
||||
lastEventSequence(): number;
|
||||
|
||||
@@ -74,7 +74,7 @@ export const CDP_BROWSER_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
const IDENTITY = CDP_BROWSER_PROVIDER_IDENTITY;
|
||||
const CLEANUP_DOMAINS = ["Network", "Debugger", "Runtime", "Page"] as const;
|
||||
|
||||
/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
|
||||
/** Passive browser observation through a selected user-owned CDP endpoint. */
|
||||
export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
@@ -90,15 +90,21 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
"list_browser_targets",
|
||||
options.signal,
|
||||
);
|
||||
const allowedOrigins = new Set(input.allowed_origins);
|
||||
const selected = selectTargets(discovery, allowedOrigins);
|
||||
const selected = selectTargets(
|
||||
discovery,
|
||||
input.allowed_origins.length === 0
|
||||
? undefined
|
||||
: new Set(input.allowed_origins),
|
||||
);
|
||||
return ok(
|
||||
browserTargetListSchema.parse({
|
||||
browser: discovery.version,
|
||||
targets: selected.allowed,
|
||||
excluded: selected.excluded,
|
||||
limitations: [
|
||||
"Only page targets whose current URL matches an approved exact origin are listed.",
|
||||
input.allowed_origins.length === 0
|
||||
? "All page targets with supported HTTP(S) URLs are listed."
|
||||
: "Only page targets whose current URL matches an explicitly requested exact origin are listed.",
|
||||
...(selected.unconnectable === 0
|
||||
? []
|
||||
: [
|
||||
@@ -137,7 +143,13 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
const sourceMaps = input.fetch_source_maps
|
||||
? await fetchWebSourceMaps(
|
||||
captured.sourceMapRequests,
|
||||
input,
|
||||
{
|
||||
...input,
|
||||
allowed_origins:
|
||||
input.allowed_origins.length > 0
|
||||
? input.allowed_origins
|
||||
: [captured.inspection.target.origin],
|
||||
},
|
||||
options.signal,
|
||||
)
|
||||
: undefined;
|
||||
@@ -163,6 +175,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
@@ -176,7 +189,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
@@ -208,6 +221,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
@@ -221,7 +235,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
@@ -265,6 +279,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
@@ -278,7 +293,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
@@ -321,6 +336,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
@@ -333,7 +349,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
operation,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
@@ -352,7 +368,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
|
||||
const selectTargets = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
allowedOrigins: ReadonlySet<string> | undefined,
|
||||
): {
|
||||
readonly allowed: readonly BrowserTargetList["targets"][number][];
|
||||
readonly excluded: BrowserTargetList["excluded"];
|
||||
@@ -373,7 +389,7 @@ const selectTargets = (
|
||||
unsupportedUrl += 1;
|
||||
continue;
|
||||
}
|
||||
if (!allowedOrigins.has(url.origin)) {
|
||||
if (allowedOrigins !== undefined && !allowedOrigins.has(url.origin)) {
|
||||
disallowedOrigin += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -415,12 +431,24 @@ const authorizeTarget = (
|
||||
if (
|
||||
target.type !== "page" ||
|
||||
origin === null ||
|
||||
!input.allowed_origins.includes(origin)
|
||||
(input.allowed_origins.length > 0 &&
|
||||
!input.allowed_origins.includes(origin))
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
return target;
|
||||
};
|
||||
|
||||
const scopeToTargetOrigin = <T extends { allowed_origins: readonly string[] }>(
|
||||
input: T,
|
||||
target: CdpEndpointTarget,
|
||||
): T => {
|
||||
if (input.allowed_origins.length > 0) return input;
|
||||
const origin = sanitizeBrowserUrl(target.url).origin;
|
||||
if (origin === null)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
return { ...input, allowed_origins: [origin] };
|
||||
};
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: BrowserObservationOperation,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import { inferJsonShape } from "../domain/jsonShape.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { redactSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
isHttpUrl,
|
||||
@@ -265,7 +264,7 @@ const captureConsoleText = (
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const text = redactSensitiveText(primitive.text);
|
||||
const text = primitive.text;
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
|
||||
@@ -55,7 +55,7 @@ export const inspectCdpElectronPage = async (
|
||||
limitations: [
|
||||
"Local file paths exposed by the selected CDP target are retained in the observation.",
|
||||
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
|
||||
"Script contents require separate source-capture approval.",
|
||||
"Select include_script_sources to retain script contents.",
|
||||
],
|
||||
mainFrameId: undefined,
|
||||
navigationDuringCapture: false,
|
||||
|
||||
@@ -144,11 +144,11 @@ export class CdpElectronProvider implements ElectronObservationPort {
|
||||
return err(providerError(cause, "inspect_electron_page"));
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(targetSession, [
|
||||
"Debugger",
|
||||
"Runtime",
|
||||
"Page",
|
||||
]);
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
["Debugger", "Runtime", "Page"],
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ const captureScriptSource = async (
|
||||
return {
|
||||
source: {
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
reason: "source capture was not selected",
|
||||
},
|
||||
};
|
||||
const result = requiredRecord(
|
||||
|
||||
@@ -154,8 +154,9 @@ const sanitizeSameOriginTitleUrl = (candidate: string, target: URL): string => {
|
||||
} catch {
|
||||
return candidate;
|
||||
}
|
||||
return parsed.origin === target.origin && parsed.search !== ""
|
||||
? sanitizeBrowserUrl(parsed.href).url
|
||||
return parsed.origin === target.origin &&
|
||||
(parsed.username !== "" || parsed.password !== "")
|
||||
? sanitizeBrowserUrl(candidate).url
|
||||
: candidate;
|
||||
};
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ export const observeCdpSession = async (
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message:
|
||||
"Browser observation armed; perform the approved user action now",
|
||||
"Browser observation armed; perform the requested user action now",
|
||||
});
|
||||
let endReason = await waitForWindow(
|
||||
context.input.observation_ms,
|
||||
|
||||
@@ -84,7 +84,7 @@ export const capturePage = async (
|
||||
allowedOrigins,
|
||||
limitations: [
|
||||
"Observation starts when REA attaches; prior network and console activity is unavailable.",
|
||||
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; separately approved captures retain only redacted text or value-free shapes.",
|
||||
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; explicitly requested primitive console text is retained verbatim, while payload captures retain value-free shapes.",
|
||||
"Source maps are reported only as declarative URLs and are not fetched.",
|
||||
"URL-less scripts and console events without an allowed source URL are excluded because their origin cannot be proven.",
|
||||
],
|
||||
|
||||
@@ -77,7 +77,7 @@ const buildScriptDraft = async (
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] = state
|
||||
.context.input.include_script_sources
|
||||
? await captureScriptSource(script, state)
|
||||
: sourceExcluded("source capture was not approved");
|
||||
: sourceExcluded("source capture was not selected");
|
||||
const inventoryScript = {
|
||||
frame_id: state.events.frameForScript(script, state.frameIds),
|
||||
url: script.url,
|
||||
|
||||
@@ -204,13 +204,14 @@ const safeDestination = (
|
||||
} => {
|
||||
try {
|
||||
const parsed = new URL(value, baseUrl);
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
||||
return { url: null, scope: "unsupported" };
|
||||
return { url: sanitized, scope: "unsupported" };
|
||||
if (!allowedOrigins.has(parsed.origin))
|
||||
return { url: null, scope: "outside_policy" };
|
||||
return { url: sanitizeBrowserUrl(parsed.href).url, scope: "approved" };
|
||||
return { url: sanitized, scope: "outside_policy" };
|
||||
return { url: sanitized, scope: "approved" };
|
||||
} catch {
|
||||
return { url: null, scope: "unsupported" };
|
||||
return { url: value, scope: "unsupported" };
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -114,7 +114,7 @@ export const captureCdpScreenshot = async (
|
||||
artifact: createWebScreenshotArtifact(bytes),
|
||||
completeness: new CdpCaptureCompleteness().snapshot(),
|
||||
limitations: [
|
||||
"The screenshot contains the visible viewport and may include sensitive on-screen content; capture requires separate approval.",
|
||||
"The screenshot contains the visible viewport, including on-screen content.",
|
||||
"REA does not scroll, evaluate JavaScript, or capture beyond the current viewport.",
|
||||
],
|
||||
};
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { captureFrames, mainFrameUrl } from "./CdpCaptureDocuments.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import { redactSensitiveText } from "./SensitiveTextCapture.js";
|
||||
|
||||
interface DiscoveryContext {
|
||||
readonly connection: CdpConnection;
|
||||
@@ -293,11 +292,11 @@ const normalizeTool = (
|
||||
completeness.exclude("webmcp_tools", "out_of_target_scope");
|
||||
return undefined;
|
||||
}
|
||||
const description = redactSensitiveText(stringValue(value.description) ?? "");
|
||||
const description = stringValue(value.description) ?? "";
|
||||
const annotations = recordValue(value.annotations);
|
||||
return {
|
||||
tool_key: toolKey(frame.url, name),
|
||||
name: redactSensitiveText(name),
|
||||
name,
|
||||
description,
|
||||
frame_id: frameId,
|
||||
frame_url: frame.url,
|
||||
|
||||
@@ -45,15 +45,10 @@ const scenario = (
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
}
|
||||
: {
|
||||
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"],
|
||||
@@ -65,10 +60,6 @@ const scenario = (
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
at_end: [],
|
||||
@@ -123,6 +114,10 @@ class FakeSession implements BrowserScenarioSessionPort {
|
||||
return "https://app.example.test/current";
|
||||
}
|
||||
|
||||
sanitizeUrl(value: string) {
|
||||
return sanitizeBrowserUrl(value);
|
||||
}
|
||||
|
||||
setStep(index: number) {
|
||||
this.step = index;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import type {
|
||||
BrowserScenario,
|
||||
BrowserScenarioAction,
|
||||
@@ -108,8 +107,8 @@ const createStep = (
|
||||
readonly stepId: string;
|
||||
readonly action: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly beforeUrl: string;
|
||||
readonly afterUrl: string;
|
||||
readonly beforeUrl: ReturnType<BrowserScenarioSessionPort["sanitizeUrl"]>;
|
||||
readonly afterUrl: ReturnType<BrowserScenarioSessionPort["sanitizeUrl"]>;
|
||||
readonly eventStart: number;
|
||||
readonly eventEnd: number;
|
||||
readonly artifacts: BrowserStepArtifacts;
|
||||
@@ -121,8 +120,8 @@ const createStep = (
|
||||
action: input.action,
|
||||
status: input.status,
|
||||
elapsed_ms: input.elapsedMs,
|
||||
before_url: sanitizeBrowserUrl(input.beforeUrl),
|
||||
after_url: sanitizeBrowserUrl(input.afterUrl),
|
||||
before_url: input.beforeUrl,
|
||||
after_url: input.afterUrl,
|
||||
error: input.error,
|
||||
event_sequence_start: input.eventStart,
|
||||
event_sequence_end: input.eventEnd,
|
||||
@@ -147,8 +146,8 @@ const initialStep = async (input: {
|
||||
action: "goto_start",
|
||||
status: "completed",
|
||||
elapsedMs,
|
||||
beforeUrl: session.initialUrl,
|
||||
afterUrl: session.currentUrl(),
|
||||
beforeUrl: session.sanitizeUrl(session.initialUrl),
|
||||
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
||||
error: null,
|
||||
eventStart: 1,
|
||||
eventEnd: session.lastEventSequence(),
|
||||
@@ -165,7 +164,7 @@ const executeStep = async (input: {
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<BrowserScenarioStep> => {
|
||||
const { session, scenario, action, stepIndex, priorFailure, signal } = input;
|
||||
const beforeUrl = session.currentUrl();
|
||||
const beforeUrl = session.sanitizeUrl(session.currentUrl());
|
||||
const eventStart = session.nextEventSequence();
|
||||
const requested = requestedForStep(scenario, stepIndex);
|
||||
if (priorFailure)
|
||||
@@ -216,7 +215,7 @@ const executeStep = async (input: {
|
||||
...outcome,
|
||||
elapsedMs: Date.now() - actionStartedAt,
|
||||
beforeUrl,
|
||||
afterUrl: session.currentUrl(),
|
||||
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
||||
eventStart,
|
||||
eventEnd: session.lastEventSequence(),
|
||||
artifacts,
|
||||
|
||||
@@ -103,7 +103,7 @@ it("keeps long Electron arguments and deep-link URLs intact", () => {
|
||||
).toBe(longStepId);
|
||||
});
|
||||
|
||||
it("redacts action inputs from Playwright failures", async () => {
|
||||
it("preserves local Playwright action diagnostics", async () => {
|
||||
const selector = "#secret-selector";
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: "/opt/electron",
|
||||
@@ -126,10 +126,10 @@ it("redacts action inputs from Playwright failures", async () => {
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
status: "failed",
|
||||
error: "locator <redacted-input> failed with token=[REDACTED]",
|
||||
error: `locator ${selector} failed with token=raw-secret`,
|
||||
});
|
||||
expect(result[0]?.error).not.toContain(selector);
|
||||
expect(result[0]?.error).not.toContain("raw-secret");
|
||||
expect(result[0]?.error).toContain(selector);
|
||||
expect(result[0]?.error).toContain("raw-secret");
|
||||
});
|
||||
|
||||
it("retains complete action errors and Electron window text", async () => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { z } from "zod";
|
||||
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import { redactSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import type {
|
||||
ElectronActiveObservationInput,
|
||||
ElectronActiveObservationResult,
|
||||
@@ -157,7 +156,7 @@ export const runElectronActions = async (
|
||||
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
|
||||
status: options.signal?.aborted ? "cancelled" : "failed",
|
||||
elapsed_ms: Date.now() - actionStartedAt,
|
||||
error: safeActionErrorMessage(cause, action),
|
||||
error: safeActionErrorMessage(cause),
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -440,18 +439,6 @@ export const runWithExecutionLimits = async <Value>(
|
||||
}
|
||||
};
|
||||
|
||||
const safeActionErrorMessage = (
|
||||
cause: unknown,
|
||||
action: ElectronAction,
|
||||
): string => {
|
||||
let message =
|
||||
cause instanceof Error ? cause.message : "Electron action failed";
|
||||
const inputValues = Object.values(action)
|
||||
.filter(
|
||||
(value): value is string => typeof value === "string" && value.length > 0,
|
||||
)
|
||||
.sort((left, right) => right.length - left.length);
|
||||
for (const value of inputValues)
|
||||
message = message.split(value).join("<redacted-input>");
|
||||
return redactSensitiveText(message);
|
||||
const safeActionErrorMessage = (cause: unknown): string => {
|
||||
return cause instanceof Error ? cause.message : "Electron action failed";
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -19,7 +20,6 @@ import {
|
||||
BrowserObservationError,
|
||||
ProviderAdapterError,
|
||||
} from "../domain/errors.js";
|
||||
import { isPathContained } from "../domain/permissionPolicy.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
@@ -351,13 +351,14 @@ const createResult = (
|
||||
const canonicalPaths = async (
|
||||
input: ElectronActiveObservationInput,
|
||||
): Promise<ElectronPaths> => {
|
||||
const [executable, application, root] = await Promise.all([
|
||||
const [executable, application] = await Promise.all([
|
||||
realpath(input.executable_path),
|
||||
realpath(input.application_path),
|
||||
realpath(input.application_root),
|
||||
]);
|
||||
if (!isPathContained(root, application))
|
||||
throw new BrowserObservationError(OPERATION, "target_not_allowed");
|
||||
const root =
|
||||
input.application_root === undefined
|
||||
? dirname(application)
|
||||
: await realpath(input.application_root);
|
||||
return { executable, application, root };
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, it } from "vitest";
|
||||
import type { Page } from "playwright-core";
|
||||
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
|
||||
it("uses exact accessible-name matching without a caller confirmation field", async () => {
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "chrome" },
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
actions: [
|
||||
{
|
||||
step_id: "submit",
|
||||
action: "click",
|
||||
locator: { kind: "role", role: "button", name: "Submit" },
|
||||
},
|
||||
],
|
||||
});
|
||||
const calls: unknown[][] = [];
|
||||
const page = {
|
||||
getByRole: (...args: unknown[]) => {
|
||||
calls.push(args);
|
||||
return { click: async () => undefined };
|
||||
},
|
||||
} as unknown as Page;
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
if (secrets === undefined) throw new Error("No secret declarations expected");
|
||||
const action = scenario.actions.at(0);
|
||||
if (action === undefined) throw new Error("Expected one scenario action");
|
||||
|
||||
await performPlaywrightScenarioAction({
|
||||
page,
|
||||
action,
|
||||
secrets,
|
||||
});
|
||||
|
||||
expect(calls).toEqual([["button", { name: "Submit", exact: true }]]);
|
||||
});
|
||||
@@ -18,7 +18,7 @@ const resolveLocator = (page: Page, locator: ScenarioLocator): Locator => {
|
||||
case "role":
|
||||
return page.getByRole(locator.role, {
|
||||
name: locator.name,
|
||||
exact: locator.exact,
|
||||
exact: true,
|
||||
});
|
||||
case "css":
|
||||
return page.locator(locator.selector);
|
||||
|
||||
@@ -9,9 +9,6 @@ const scenario = browserScenarioSchema.parse({
|
||||
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"],
|
||||
@@ -39,3 +36,80 @@ it("returns a complete requested text artifact beyond the former inline ceiling"
|
||||
value: { bytes: 16 * 1_024 * 1_024 + 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("redacts declared secrets from current and historical URL artifacts", async () => {
|
||||
const secretValue = "rea browser+verifier";
|
||||
const scenarioWithSecretUrl = browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "/opt/chromium" },
|
||||
start_url: {
|
||||
url: "https://app.example.test/",
|
||||
query: [
|
||||
{
|
||||
name: "token",
|
||||
value: { source: "secret", secret_id: "url_token" },
|
||||
},
|
||||
],
|
||||
},
|
||||
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
|
||||
secrets: [
|
||||
{
|
||||
secret_id: "url_token",
|
||||
environment_variable: "REA_URL_TOKEN",
|
||||
},
|
||||
],
|
||||
capture: { at_end: ["url", "history"] },
|
||||
});
|
||||
const scenarioSecrets = BrowserScenarioSecrets.resolve(
|
||||
scenarioWithSecretUrl,
|
||||
{
|
||||
REA_URL_TOKEN: secretValue,
|
||||
},
|
||||
);
|
||||
if (scenarioSecrets === undefined)
|
||||
throw new Error("Expected resolved URL secret");
|
||||
const query = new URLSearchParams([["token", secretValue]]).toString();
|
||||
const url = `https://app.example.test/?${query}#${encodeURIComponent(secretValue)}`;
|
||||
const page = {
|
||||
url: () => url,
|
||||
evaluate: async () => ({
|
||||
length: 1,
|
||||
navigation_entries: [{ type: "navigate", name: url }],
|
||||
}),
|
||||
} as unknown as Page;
|
||||
|
||||
const result = await capturePlaywrightStepArtifacts({
|
||||
context: {} as BrowserContext,
|
||||
page,
|
||||
scenario: scenarioWithSecretUrl,
|
||||
secrets: scenarioSecrets,
|
||||
requested: new Set(["url", "history"]),
|
||||
});
|
||||
|
||||
expect(
|
||||
JSON.stringify({ url: result.url, history: result.history }),
|
||||
).not.toContain(secretValue);
|
||||
expect(result.url).toMatchObject({
|
||||
state: "captured",
|
||||
value: {
|
||||
redacted: true,
|
||||
url: "https://app.example.test/?token=[REDACTED:url_token]#[REDACTED:url_token]",
|
||||
},
|
||||
});
|
||||
expect(result.history).toMatchObject({
|
||||
state: "captured",
|
||||
value: {
|
||||
current_url: {
|
||||
redacted: true,
|
||||
url: "https://app.example.test/?token=[REDACTED:url_token]#[REDACTED:url_token]",
|
||||
},
|
||||
navigation_entries: [
|
||||
{
|
||||
name: {
|
||||
redacted: true,
|
||||
url: "https://app.example.test/?token=[REDACTED:url_token]#[REDACTED:url_token]",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import type { BrowserContext, Page } from "playwright-core";
|
||||
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import type { BrowserScenario } from "../domain/browserScenario.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
@@ -105,7 +104,7 @@ const navigationType = (
|
||||
}
|
||||
};
|
||||
|
||||
const captureHistory = async (page: Page) => {
|
||||
const captureHistory = async (page: Page, secrets: BrowserScenarioSecrets) => {
|
||||
try {
|
||||
const raw = historyValueSchema.parse(
|
||||
await page.evaluate(`(() => ({
|
||||
@@ -120,10 +119,10 @@ const captureHistory = async (page: Page) => {
|
||||
);
|
||||
const value = {
|
||||
length: raw.length,
|
||||
current_url: sanitizeBrowserUrl(page.url()),
|
||||
current_url: secrets.sanitizeUrl(page.url()),
|
||||
navigation_entries: raw.navigation_entries.map(({ type, name }) => ({
|
||||
type: navigationType(type),
|
||||
name: sanitizeBrowserUrl(name),
|
||||
name: secrets.sanitizeUrl(name),
|
||||
})),
|
||||
};
|
||||
return { state: "captured" as const, value };
|
||||
@@ -213,9 +212,9 @@ export const capturePlaywrightStepArtifacts = async (input: {
|
||||
),
|
||||
url: await state("url", async () => ({
|
||||
state: "captured" as const,
|
||||
value: sanitizeBrowserUrl(page.url()),
|
||||
value: secrets.sanitizeUrl(page.url()),
|
||||
})),
|
||||
history: await state("history", () => captureHistory(page)),
|
||||
history: await state("history", () => captureHistory(page, secrets)),
|
||||
storage: await state("storage", () =>
|
||||
captureStorage({ context, page, scenario, secrets }),
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { chmod, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import {
|
||||
chromium,
|
||||
@@ -142,8 +142,8 @@ export const openPlaywrightScenarioBrowser = async (
|
||||
await chmod(profilePath, 0o700);
|
||||
try {
|
||||
const context = await chromium.launchPersistentContext(profilePath, {
|
||||
executablePath: scenario.browser.executable_path,
|
||||
headless: true,
|
||||
executablePath: resolve(scenario.browser.executable_path),
|
||||
headless: scenario.browser.headless,
|
||||
acceptDownloads: false,
|
||||
viewport: {
|
||||
width: scenario.environment.viewport.width,
|
||||
@@ -154,7 +154,7 @@ export const openPlaywrightScenarioBrowser = async (
|
||||
timezoneId: scenario.environment.timezone,
|
||||
colorScheme: scenario.environment.color_scheme,
|
||||
reducedMotion: scenario.environment.reduced_motion,
|
||||
serviceWorkers: "block",
|
||||
serviceWorkers: scenario.environment.service_workers,
|
||||
env: allowedBrowserEnvironment(environment),
|
||||
handleSIGHUP: false,
|
||||
handleSIGINT: false,
|
||||
|
||||
@@ -18,9 +18,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
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"],
|
||||
@@ -30,7 +27,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
@@ -42,10 +38,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: [],
|
||||
at_end: [],
|
||||
@@ -85,9 +77,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
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"],
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
Worker,
|
||||
} from "playwright-core";
|
||||
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import type { SanitizedBrowserUrl } from "../domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioEventSchema,
|
||||
type BrowserScenarioEvent,
|
||||
@@ -155,7 +155,7 @@ export class PlaywrightScenarioEvents {
|
||||
}
|
||||
|
||||
private safeUrl(value: string) {
|
||||
return sanitizeBrowserUrl(this.secrets.redact(value));
|
||||
return this.secrets.sanitizeUrl(value);
|
||||
}
|
||||
|
||||
private console(message: ConsoleMessage): void {
|
||||
@@ -227,7 +227,7 @@ export class PlaywrightScenarioEvents {
|
||||
|
||||
private webSocketFrame(
|
||||
kind: "websocket-frame-sent" | "websocket-frame-received",
|
||||
url: ReturnType<typeof sanitizeBrowserUrl>,
|
||||
url: SanitizedBrowserUrl,
|
||||
payload: string | Buffer,
|
||||
): void {
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
|
||||
@@ -331,6 +331,10 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
return this.opened.page.url();
|
||||
}
|
||||
|
||||
sanitizeUrl(value: string) {
|
||||
return this.secrets.sanitizeUrl(value);
|
||||
}
|
||||
|
||||
setStep(index: number): void {
|
||||
this.eventCapture.setStep(index);
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { redactSensitiveText } from "./SensitiveTextCapture.js";
|
||||
|
||||
describe("sensitive console text", () => {
|
||||
it("redacts assignments, bearer credentials, and JWT-shaped values", () => {
|
||||
const jwt = "eyJabcdefghijk.abcdefghijkl.abcdefghijk";
|
||||
expect(
|
||||
redactSensitiveText(
|
||||
`authorization=Bearer abc.def password='hunter2' api_key=key ${jwt}`,
|
||||
),
|
||||
).toBe(
|
||||
"authorization=[REDACTED] password=[REDACTED] api_key=[REDACTED] [REDACTED_JWT]",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
const SECRET_ASSIGNMENT =
|
||||
/\b(authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|passwd|secret|cookie|session)\b\s*[:=]\s*(?:Bearer\s+[A-Za-z0-9._~+/=-]+|"[^"]*"|'[^']*'|[^\s,;]+)/giu;
|
||||
const BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
|
||||
const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu;
|
||||
|
||||
/** Redact credential-shaped substrings before approved console text is retained. */
|
||||
export const redactSensitiveText = (value: string): string =>
|
||||
value
|
||||
.replace(SECRET_ASSIGNMENT, (_match, name: string) => `${name}=[REDACTED]`)
|
||||
.replace(BEARER, "Bearer [REDACTED]")
|
||||
.replace(JWT, "[REDACTED_JWT]");
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AnyMap, eachMapping } from "@jridgewell/trace-mapping";
|
||||
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import { hasValidSourceMapContents } from "../domain/sourceMapContents.js";
|
||||
import type {
|
||||
AnalyzeWebBundleInput,
|
||||
WebSourceMapItem,
|
||||
@@ -222,8 +223,7 @@ const validSourceMapEnvelope = (text: string): boolean => {
|
||||
return false;
|
||||
}
|
||||
if (!isRecord(parsed) || parsed.version !== 3) return false;
|
||||
if (typeof parsed.mappings === "string")
|
||||
return Array.isArray(parsed.sources) && Array.isArray(parsed.names);
|
||||
if (typeof parsed.mappings === "string") return validSourceMapLeaf(parsed);
|
||||
if (!Array.isArray(parsed.sections)) return false;
|
||||
const pending: unknown[] = [...parsed.sections];
|
||||
while (pending.length > 0) {
|
||||
@@ -234,16 +234,17 @@ const validSourceMapEnvelope = (text: string): boolean => {
|
||||
if (!isRecord(map) || map.version !== 3) return false;
|
||||
if (Array.isArray(map.sections))
|
||||
for (const child of map.sections) pending.push(child);
|
||||
else if (
|
||||
typeof map.mappings !== "string" ||
|
||||
!Array.isArray(map.sources) ||
|
||||
!Array.isArray(map.names)
|
||||
)
|
||||
return false;
|
||||
else if (!validSourceMapLeaf(map)) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const validSourceMapLeaf = (map: Readonly<Record<string, unknown>>): boolean =>
|
||||
typeof map.mappings === "string" &&
|
||||
Array.isArray(map.sources) &&
|
||||
Array.isArray(map.names) &&
|
||||
hasValidSourceMapContents(map.sources.length, map.sourcesContent);
|
||||
|
||||
const approvedUrl = (
|
||||
value: string,
|
||||
allowedOrigins: readonly string[],
|
||||
@@ -282,12 +283,9 @@ const emptySourceMapItem = (
|
||||
|
||||
const sanitizeSource = (value: string): string => {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:"
|
||||
? sanitizeBrowserUrl(parsed.href).url
|
||||
: `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
|
||||
return sanitizeBrowserUrl(new URL(value).href).url;
|
||||
} catch {
|
||||
return value.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user