refactor(test): colocate pure-domain tests and reduce test debt (#471)
* refactor(test): colocate pure-domain tests and reduce test debt Move focused immutable domain/contracts/adapter tests from tests/composition/** beside their production owners under src/** as colocated *.test.ts/*.fixture.ts, and relocate persistence-shaped composition tests under tests/boundary/filesystem/**. Update import paths, the Vitest project topology (shared worker context for pure domain/contracts and recording-port service projects), the test migration ledger, testing docs, and AGENTS.md to match. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: remove test migration ledger The cutover is complete and the ledger is no longer referenced anywhere in source, scripts, or the docs gate. Drop the standalone artifact. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: clean up stale migration artifacts Remove empty directories left by the test migration and replace the "final cutover" language in docs/testing.md with standing PR guidance that no longer references the completed migration. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: repair CI failures from schema, knip, and stale generated artifacts Three root causes fixed: 1. catalog-schemas.mjs: valuesAt only traversed anyOf from Zod's toJSONSchema, not oneOf. The webScreenshotDiffSchema change to a discriminated union produces oneOf, so the product catalog generator could not derive the web_screenshot_diff schema version. Add oneOf traversal. 2. conformancePackage.ts: the test rewrite removed the only imports of ScenarioManifest, ReplayPlan, ShimPlan, and ExpectedEvidence, making them unused exports that knip flags. Remove the dead type aliases. 3. Regenerate stale artifacts (product catalog, MCP tool catalog, skill metadata, conformance manifest) that drifted from the source changes. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
344b9b6dff
commit
e91c8c39c2
@@ -0,0 +1,308 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
|
||||
const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
source: "literal",
|
||||
value,
|
||||
classification: "public",
|
||||
});
|
||||
|
||||
const baseScenario = () => ({
|
||||
schema_version: 1,
|
||||
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/",
|
||||
query: [{ name: "token", value: secret("session") }],
|
||||
},
|
||||
allowed_origins: ["https://api.example.test", "https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "dark",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "login",
|
||||
action: "fill",
|
||||
locator: { kind: "test_id", value: "password" },
|
||||
value: secret("login_input"),
|
||||
},
|
||||
{
|
||||
step_id: "submit",
|
||||
action: "click",
|
||||
locator: {
|
||||
kind: "role",
|
||||
role: "button",
|
||||
name: "Sign in",
|
||||
exact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
step_id: "dashboard",
|
||||
action: "goto",
|
||||
destination: { url: "https://app.example.test/dashboard" },
|
||||
wait_until: "load",
|
||||
},
|
||||
],
|
||||
storage: {
|
||||
cookies: [
|
||||
{
|
||||
name: "sid",
|
||||
value: secret("cookie"),
|
||||
destination: { url: "https://app.example.test/" },
|
||||
http_only: true,
|
||||
secure: true,
|
||||
same_site: "Lax",
|
||||
},
|
||||
],
|
||||
local_storage: [
|
||||
{
|
||||
origin: "https://app.example.test",
|
||||
entries: [{ name: "theme", value: literal("dark") }],
|
||||
},
|
||||
],
|
||||
},
|
||||
request_replay: {
|
||||
mode: "exact",
|
||||
unmatched: "abort",
|
||||
routes: [
|
||||
{
|
||||
route_id: "profile",
|
||||
method: "GET",
|
||||
request: { url: "https://api.example.test/profile" },
|
||||
response: {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [
|
||||
{
|
||||
name: "content-type",
|
||||
value: literal("application/json"),
|
||||
},
|
||||
],
|
||||
body: literal('{"name":"Ada"}'),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
secrets: [
|
||||
{
|
||||
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"],
|
||||
events: ["console", "page-errors", "network", "websockets"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 60_000,
|
||||
action_timeout_ms: 5_000,
|
||||
navigation_timeout_ms: 10_000,
|
||||
max_events: 2_000,
|
||||
max_frames: 100,
|
||||
max_workers: 20,
|
||||
max_popups: 10,
|
||||
max_websockets: 100,
|
||||
max_dom_nodes: 10_000,
|
||||
max_accessibility_nodes: 10_000,
|
||||
max_screenshots: 16,
|
||||
max_screenshot_bytes: 4 * 1_024 * 1_024,
|
||||
max_storage_entries: 256,
|
||||
max_total_metadata_bytes: 4 * 1_024 * 1_024,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a bounded declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
expect(parsed.allowed_origins).toEqual([
|
||||
"https://api.example.test",
|
||||
"https://app.example.test",
|
||||
]);
|
||||
expect(parsed.environment.viewport.device_scale_factor).toBe(1);
|
||||
expect(parsed.redaction.header_names).toEqual([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
});
|
||||
|
||||
it("redacts overlapping secrets longest-first", () => {
|
||||
const scenario = browserScenarioSchema.parse(baseScenario());
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {
|
||||
REA_TEST_SESSION: "prefix",
|
||||
REA_TEST_PASSWORD: "prefix-suffix",
|
||||
REA_TEST_COOKIE: "cookie",
|
||||
});
|
||||
expect(secrets?.redact("prefix-suffix")).toBe("[REDACTED:login_input]");
|
||||
});
|
||||
|
||||
it("rejects unsupported actions", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions = [
|
||||
{
|
||||
step_id: "script",
|
||||
action: "evaluate",
|
||||
expression: "document.cookie",
|
||||
} as never,
|
||||
];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects every undeclared navigation, storage, and replay origin", () => {
|
||||
for (const mutate of [
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.start_url.url = "https://other.example.test/";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.actions[2] = {
|
||||
...scenario.actions[2],
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.storage.local_storage[0]!.origin =
|
||||
"https://other.example.test";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.request_replay.routes[0]!.request.url =
|
||||
"https://other.example.test/data";
|
||||
},
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
mutate(scenario);
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects redirects outside declared origins", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "redirect",
|
||||
status: 302,
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects missing, duplicate, and unused secret declarations", () => {
|
||||
const missing = baseScenario();
|
||||
missing.secrets = missing.secrets.filter(
|
||||
({ secret_id }) => secret_id !== "login_input",
|
||||
);
|
||||
expect(browserScenarioSchema.safeParse(missing).success).toBe(false);
|
||||
|
||||
const duplicate = baseScenario();
|
||||
duplicate.secrets.push({ ...duplicate.secrets[0]! });
|
||||
expect(browserScenarioSchema.safeParse(duplicate).success).toBe(false);
|
||||
|
||||
const unused = baseScenario();
|
||||
unused.secrets.push({
|
||||
secret_id: "unused",
|
||||
environment_variable: "REA_TEST_UNUSED",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
});
|
||||
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("rejects literal credential headers and provider-owned headers", () => {
|
||||
for (const name of ["authorization", "content-length"]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [{ name, value: literal("raw") }],
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects duplicate replay response headers case-insensitively", () => {
|
||||
const scenario = baseScenario();
|
||||
const response = scenario.request_replay.routes[0]!.response;
|
||||
if (response.kind !== "response")
|
||||
throw new Error("Expected replay response fixture");
|
||||
response.headers.push({
|
||||
name: "Content-Type",
|
||||
value: literal("text/plain"),
|
||||
});
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects raw secret-shaped action values", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions[0] = {
|
||||
...scenario.actions[0],
|
||||
value: "literal-input",
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects embedded URL credentials and query values", () => {
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(true);
|
||||
|
||||
scenario.browser.cleanup = "close-browser" as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
BrowserScenarioUrl,
|
||||
BrowserScenarioValue,
|
||||
} from "../domain/browserScenario.js";
|
||||
import type { BrowserStorageValueFingerprint } from "../domain/browserScenarioCaptureValues.js";
|
||||
|
||||
const REDACTION_PREFIX = "[REDACTED:";
|
||||
|
||||
@@ -53,10 +54,7 @@ export class BrowserScenarioSecrets {
|
||||
return output;
|
||||
}
|
||||
|
||||
fingerprint(value: string): {
|
||||
readonly value_state: "hashed" | "redacted-secret";
|
||||
readonly value_sha256: string | null;
|
||||
} {
|
||||
fingerprint(value: string): BrowserStorageValueFingerprint {
|
||||
for (const secret of this.values.values())
|
||||
if (secret !== "" && value.includes(secret))
|
||||
return { value_state: "redacted-secret", value_sha256: null };
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import { ingestElectronScriptEvent } from "./CdpElectronScriptEvents.js";
|
||||
|
||||
describe("CDP execution-context retention", () => {
|
||||
it("removes stale frame attribution when execution contexts are destroyed", () => {
|
||||
const request = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const browser = new CdpCaptureEvents(
|
||||
request,
|
||||
new Set(["https://app.example.test"]),
|
||||
);
|
||||
browser.beginAuthorizedFrame("frame-old");
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextDestroyed",
|
||||
params: { executionContextId: 7 },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Debugger.scriptParsed",
|
||||
params: {
|
||||
scriptId: "script-1",
|
||||
url: "https://app.example.test/app.js",
|
||||
executionContextId: 7,
|
||||
},
|
||||
});
|
||||
const script = browser.scripts.get("script-1");
|
||||
if (script === undefined) throw new TypeError("Expected captured script");
|
||||
expect(browser.frameForScript(script, new Set(["frame-old"]))).toBeNull();
|
||||
|
||||
const electronFrames = new Map<string, string>();
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
ingestElectronScriptEvent({
|
||||
event: {
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
},
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
ingestElectronScriptEvent({
|
||||
event: { method: "Runtime.executionContextsCleared", params: {} },
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
expect(electronFrames.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,12 +10,14 @@ import type {
|
||||
} from "../domain/browserScenario.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
browserScenarioCompletenessSchema,
|
||||
classifyBrowserScenarioCompleteness,
|
||||
browserScenarioStepSchema,
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioCapture,
|
||||
type BrowserScenarioCompleteness,
|
||||
type BrowserScenarioCompletenessSection,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserScenarioStepOutcome,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../domain/browserScenarioCapture.js";
|
||||
import {
|
||||
@@ -51,6 +53,14 @@ export const PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY: ProviderIdentity =
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
const SNAPSHOT_KINDS = [
|
||||
"screenshot",
|
||||
"dom",
|
||||
"accessibility",
|
||||
"url",
|
||||
"history",
|
||||
"storage",
|
||||
] as const satisfies readonly SnapshotKind[];
|
||||
|
||||
const requestedForStep = (
|
||||
scenario: BrowserScenario,
|
||||
@@ -83,40 +93,29 @@ const stepCompleteness = (
|
||||
artifacts: BrowserStepArtifacts,
|
||||
status: BrowserScenarioStep["status"],
|
||||
): BrowserScenarioCompleteness => {
|
||||
const missing = Object.entries(artifacts)
|
||||
.filter(([, state]) => state.state === "missing")
|
||||
.map(([section]) => section);
|
||||
const truncated = Object.entries(artifacts)
|
||||
.filter(([, state]) => state.state === "truncated")
|
||||
.map(([section]) => section);
|
||||
const missing: BrowserScenarioCompletenessSection[] = SNAPSHOT_KINDS.filter(
|
||||
(section) => artifacts[section].state === "missing",
|
||||
);
|
||||
const truncated = SNAPSHOT_KINDS.filter(
|
||||
(section) => artifacts[section].state === "truncated",
|
||||
);
|
||||
if (status !== "completed") missing.push("action");
|
||||
const condition =
|
||||
truncated.length > 0
|
||||
? "truncated"
|
||||
: missing.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: condition,
|
||||
equality_eligible: condition === "complete",
|
||||
missing_sections: [...new Set(missing)].sort(),
|
||||
truncated_sections: [...new Set(truncated)].sort(),
|
||||
});
|
||||
return classifyBrowserScenarioCompleteness(missing, truncated);
|
||||
};
|
||||
|
||||
const createStep = (input: {
|
||||
readonly stepIndex: number;
|
||||
readonly stepId: string;
|
||||
readonly action: string;
|
||||
readonly status: BrowserScenarioStep["status"];
|
||||
readonly elapsedMs: number;
|
||||
readonly beforeUrl: string;
|
||||
readonly afterUrl: string;
|
||||
readonly error: string | null;
|
||||
readonly eventStart: number;
|
||||
readonly eventEnd: number;
|
||||
readonly artifacts: BrowserStepArtifacts;
|
||||
}): BrowserScenarioStep =>
|
||||
const createStep = (
|
||||
input: {
|
||||
readonly stepIndex: number;
|
||||
readonly stepId: string;
|
||||
readonly action: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly beforeUrl: string;
|
||||
readonly afterUrl: string;
|
||||
readonly eventStart: number;
|
||||
readonly eventEnd: number;
|
||||
readonly artifacts: BrowserStepArtifacts;
|
||||
} & BrowserScenarioStepOutcome,
|
||||
): BrowserScenarioStep =>
|
||||
browserScenarioStepSchema.parse({
|
||||
step_index: input.stepIndex,
|
||||
step_id: input.stepId,
|
||||
@@ -207,11 +206,12 @@ const executeStep = async (input: {
|
||||
const actionStartedAt = Date.now();
|
||||
session.setStep(stepIndex);
|
||||
const requestCancelled = (): boolean => signal?.aborted === true;
|
||||
let status: BrowserScenarioStep["status"] = "completed";
|
||||
let error: string | null = null;
|
||||
let outcome: BrowserScenarioStepOutcome = {
|
||||
status: "completed",
|
||||
error: null,
|
||||
};
|
||||
if (requestCancelled()) {
|
||||
status = "cancelled";
|
||||
error = "scenario request cancelled";
|
||||
outcome = { status: "cancelled", error: "scenario request cancelled" };
|
||||
} else {
|
||||
try {
|
||||
const elapsed = Date.now() - startedAt;
|
||||
@@ -219,16 +219,18 @@ const executeStep = async (input: {
|
||||
if (remaining <= 0) throw new Error("Scenario duration limit reached");
|
||||
await session.perform(action, remaining, signal);
|
||||
} catch (cause: unknown) {
|
||||
status = requestCancelled() ? "cancelled" : "failed";
|
||||
error = session.redactError(cause);
|
||||
outcome = {
|
||||
status: requestCancelled() ? "cancelled" : "failed",
|
||||
error: session.redactError(cause),
|
||||
};
|
||||
}
|
||||
}
|
||||
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
|
||||
const artifacts =
|
||||
status === "cancelled" || remaining <= 0
|
||||
outcome.status === "cancelled" || remaining <= 0
|
||||
? unavailableArtifacts(
|
||||
requested,
|
||||
status === "cancelled"
|
||||
outcome.status === "cancelled"
|
||||
? "scenario request cancelled"
|
||||
: "scenario duration limit reached",
|
||||
)
|
||||
@@ -237,11 +239,10 @@ const executeStep = async (input: {
|
||||
stepIndex,
|
||||
stepId: action.step_id,
|
||||
action: action.action,
|
||||
status,
|
||||
...outcome,
|
||||
elapsedMs: Date.now() - actionStartedAt,
|
||||
beforeUrl,
|
||||
afterUrl: session.currentUrl(),
|
||||
error,
|
||||
eventStart,
|
||||
eventEnd: session.lastEventSequence(),
|
||||
artifacts,
|
||||
@@ -261,18 +262,7 @@ const globalCompleteness = (
|
||||
);
|
||||
truncated.push(...session.eventTruncationSections());
|
||||
if (session.mode === "connect") missing.push("events");
|
||||
const status =
|
||||
truncated.length > 0
|
||||
? "truncated"
|
||||
: missing.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status,
|
||||
equality_eligible: status === "complete",
|
||||
missing_sections: [...new Set(missing)].sort(),
|
||||
truncated_sections: [...new Set(truncated)].sort(),
|
||||
});
|
||||
return classifyBrowserScenarioCompleteness(missing, truncated);
|
||||
};
|
||||
|
||||
const runScenario = async (
|
||||
|
||||
@@ -241,22 +241,31 @@ export class PlaywrightScenarioEvents {
|
||||
}
|
||||
|
||||
private request(kind: "request" | "request-failed", request: Request): void {
|
||||
this.push({
|
||||
kind,
|
||||
const observation = {
|
||||
method: this.secrets.redact(request.method()).slice(0, 32),
|
||||
url: this.safeUrl(request.url()),
|
||||
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
|
||||
status: null,
|
||||
header_names: Object.keys(request.headers())
|
||||
.map((name) => this.secrets.redact(name).slice(0, 256))
|
||||
.sort()
|
||||
.slice(0, 256),
|
||||
failure:
|
||||
kind === "request-failed"
|
||||
? this.secrets
|
||||
.redact(request.failure()?.errorText ?? "unknown")
|
||||
.slice(0, 1_024)
|
||||
: null,
|
||||
};
|
||||
if (kind === "request-failed") {
|
||||
this.push({
|
||||
...observation,
|
||||
kind,
|
||||
status: null,
|
||||
failure: this.secrets
|
||||
.redact(request.failure()?.errorText ?? "unknown")
|
||||
.slice(0, 1_024),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.push({
|
||||
...observation,
|
||||
kind,
|
||||
status: null,
|
||||
failure: null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -300,14 +309,25 @@ export class PlaywrightScenarioEvents {
|
||||
): void {
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const isText = typeof payload === "string";
|
||||
const text = isText ? this.secrets.redact(payload).slice(0, 65_536) : null;
|
||||
if (!isText) {
|
||||
this.push({
|
||||
kind,
|
||||
url,
|
||||
payload_type: "binary",
|
||||
payload_bytes: bytes,
|
||||
payload_text: null,
|
||||
truncated: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const text = this.secrets.redact(payload).slice(0, 65_536);
|
||||
this.push({
|
||||
kind,
|
||||
url,
|
||||
payload_type: isText ? "text" : "binary",
|
||||
payload_type: "text",
|
||||
payload_bytes: bytes,
|
||||
payload_text: text,
|
||||
truncated: isText && text !== null && text.length < payload.length,
|
||||
truncated: text.length < payload.length,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { comparePngScreenshots } from "./PngVisualDiff.js";
|
||||
import {
|
||||
compareWebScreenshotsInputSchema,
|
||||
createWebScreenshotArtifact,
|
||||
webScreenshotDiffSchema,
|
||||
} from "../domain/webScreenshot.js";
|
||||
|
||||
describe("PNG visual diff", () => {
|
||||
it("reports exact changed-pixel and channel metrics", () => {
|
||||
const before = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const after = artifact(1, 1, [10, 0, 0, 255]);
|
||||
const result = comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({ before, after }),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "different",
|
||||
compared_pixels: 1,
|
||||
changed_pixels: 1,
|
||||
changed_ratio: 1,
|
||||
maximum_channel_delta: 10,
|
||||
mean_absolute_channel_delta: 2.5,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies a channel threshold and reports dimension mismatch", () => {
|
||||
const one = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const near = artifact(1, 1, [2, 0, 0, 255]);
|
||||
expect(
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: one,
|
||||
after: near,
|
||||
channel_threshold: 2,
|
||||
}),
|
||||
).status,
|
||||
).toBe("identical");
|
||||
expect(
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: one,
|
||||
after: artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]),
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ status: "dimension_mismatch", compared_pixels: 0 });
|
||||
});
|
||||
|
||||
it("rejects images above the caller's decoded pixel limit", () => {
|
||||
const image = artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]);
|
||||
expect(() =>
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: image,
|
||||
after: image,
|
||||
maximum_pixels: 1,
|
||||
}),
|
||||
),
|
||||
).toThrow("oversized PNG");
|
||||
});
|
||||
|
||||
it("rejects metrics that cannot represent their comparison status", () => {
|
||||
const image = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const result = comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({ before: image, after: image }),
|
||||
);
|
||||
|
||||
expect(
|
||||
webScreenshotDiffSchema.safeParse({
|
||||
...result,
|
||||
status: "dimension_mismatch",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
webScreenshotDiffSchema.safeParse({
|
||||
...result,
|
||||
compared_pixels: 2,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const artifact = (width: number, height: number, pixels: readonly number[]) =>
|
||||
createWebScreenshotArtifact(png(width, height, pixels));
|
||||
|
||||
const png = (
|
||||
width: number,
|
||||
height: number,
|
||||
pixels: readonly number[],
|
||||
): Buffer => {
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(width, 0);
|
||||
header.writeUInt32BE(height, 4);
|
||||
header[8] = 8;
|
||||
header[9] = 6;
|
||||
const rows: number[] = [];
|
||||
for (let row = 0; row < height; row += 1)
|
||||
rows.push(0, ...pixels.slice(row * width * 4, (row + 1) * width * 4));
|
||||
return Buffer.concat([
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
|
||||
chunk("IHDR", header),
|
||||
chunk("IDAT", deflateSync(Buffer.from(rows))),
|
||||
chunk("IEND", Buffer.alloc(0)),
|
||||
]);
|
||||
};
|
||||
|
||||
const chunk = (type: string, data: Buffer): Buffer => {
|
||||
const result = Buffer.alloc(12 + data.byteLength);
|
||||
result.writeUInt32BE(data.byteLength, 0);
|
||||
result.write(type, 4, 4, "ascii");
|
||||
data.copy(result, 8);
|
||||
return result;
|
||||
};
|
||||
@@ -50,19 +50,29 @@ export const comparePngScreenshots = (
|
||||
if (changed) changedPixels += 1;
|
||||
}
|
||||
const pixels = before.width * before.height;
|
||||
return {
|
||||
schema_version: 1,
|
||||
status: changedPixels === 0 ? "identical" : "different",
|
||||
const context = {
|
||||
schema_version: 1 as const,
|
||||
before: dimensions(before),
|
||||
after: dimensions(after),
|
||||
channel_threshold: input.channel_threshold,
|
||||
compared_pixels: pixels,
|
||||
changed_pixels: changedPixels,
|
||||
changed_ratio: changedPixels / pixels,
|
||||
maximum_channel_delta: maximumDelta,
|
||||
mean_absolute_channel_delta: totalDelta / (pixels * 4),
|
||||
limitations: limitations(),
|
||||
};
|
||||
if (changedPixels === 0)
|
||||
return {
|
||||
...context,
|
||||
status: "identical",
|
||||
changed_pixels: 0,
|
||||
changed_ratio: 0,
|
||||
};
|
||||
return {
|
||||
...context,
|
||||
status: "different",
|
||||
changed_pixels: changedPixels,
|
||||
changed_ratio: changedPixels / pixels,
|
||||
};
|
||||
};
|
||||
|
||||
const decodePng = (
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
boundedSensitiveText,
|
||||
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]",
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds UTF-8 after redaction without splitting a code point", () => {
|
||||
expect(boundedSensitiveText("password=secret 你好", 22)).toEqual({
|
||||
text: "password=[REDACTED] ",
|
||||
bytes: 20,
|
||||
truncated: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user