Skip to content

Commit 966f7cc

Browse files
committed
fix(browser): preserve body API provenance through script export
Label new captured response bytes as Playwright body API results and retain the possibility of a credentialed follow-up load. Preserve legacy representations and source limitations through export without treating body-origin uncertainty as missing event coverage. Validated source and filesystem boundary tests plus real Chrome CLI and MCP network workflows covering binary, compressed, empty, unfinished, and same-URL responses and profile cleanup.
1 parent 6bae774 commit 966f7cc

15 files changed

Lines changed: 270 additions & 92 deletions

‎docs/browser-scenario-contract.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,13 @@ Capturing more data alone does not establish a website change.
262262
states. Captured bodies retain base64 bytes, byte count, media type, and SHA-256
263263
of the retained bytes. Request bytes are those exposed by Playwright; a
264264
`not_exposed` request body does not prove absence or complete multipart file
265-
coverage. Response bytes are decoded by the browser, not the compressed wire
266-
representation. No later fetch is substituted for the original response.
265+
coverage. Response bytes are the result of Playwright's `Response.body()` API.
266+
Playwright may satisfy that API with a credentialed follow-up load of the
267+
request URL when CDP has no response body. Event and transaction references
268+
identify the associated Playwright response object, but do not verify that the
269+
retained bytes came from the original network transaction. Successful selected
270+
response bodies include this limitation in the capture. These bytes are not
271+
the compressed wire representation.
267272
Headers preserve producer order and duplicates. Authorization,
268273
Proxy-Authorization, Cookie, and Set-Cookie values are null with
269274
`redacted: true`; ordinary values remain intact. Declared UTF-8 secret values

‎docs/website-script-export.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,14 @@ its own descriptor. It does not duplicate script bytes.
4848
- Passive sources are the Debugger-exposed text encoded as UTF-8, with the
4949
verified source digest and source-map declaration retained. Unavailable or
5050
explicitly non-JavaScript sources remain unavailable.
51-
- Scenario sources use observed requests classified as `script`, matched to
52-
completed response bytes by transaction and event identity. URLs never select
53-
the response. Binary and empty retained bytes are written exactly.
51+
- Scenario sources use observed requests classified as `script`, associated
52+
with one response event and the bytes returned by Playwright's
53+
`Response.body()` API for its response object. URLs never select the response.
54+
Playwright may load the request URL again with credentials when CDP has no
55+
response body, so transaction and event references do not verify that
56+
exported bytes came from the original network transaction. The capture and
57+
export manifest retain this limitation. Binary and empty retained bytes are
58+
written exactly.
5459
- Ordinary query-free `.js`, `.mjs`, and `.cjs` URL paths are arranged under a
5560
directory for each origin, preserving their relative module layout when it
5661
is unambiguous.
@@ -62,8 +67,9 @@ its own descriptor. It does not duplicate script bytes.
6267
## Interpretation and limits
6368

6469
Export does not fetch URLs or execute JavaScript. Retained Debugger sources and
65-
response bytes do not establish execution or a complete website. Response bytes
66-
are browser-decoded bytes; they do not represent transfer encoding. Declared
70+
response bytes do not establish execution or a complete website. Scenario
71+
response bytes preserve Playwright's body API result; see the source-body
72+
identity limitation above. Declared
6773
redaction is preserved and can change JavaScript syntax; passive captures do
6874
not report a byte-redaction flag, so that value remains unknown.
6975

‎scripts/lib/browser-network-assertions.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export function assertBrowserNetworkEvidence(
117117
assert.deepEqual(retained(responseFor("/compressed")), networkFixtureDecoded);
118118
assert.equal(
119119
responseFor("/compressed").body.representation,
120-
"browser-decoded-response-bytes",
120+
"playwright-response-body-bytes",
121121
);
122122
const formRequest = requestEvents.find(
123123
(event) => event.url.url === `${origin}/form`,
@@ -149,7 +149,7 @@ export function assertBrowserNetworkEvidence(
149149
return {
150150
same_url_markers: markers,
151151
binary_bytes: networkFixtureBinary.length,
152-
compressed_representation: "browser-decoded-response-bytes",
152+
compressed_representation: "playwright-response-body-bytes",
153153
unfinished_stream: "response-unfinished",
154154
empty_response_state: responseFor("/empty").body.state,
155155
};

‎src/browser/BrowserScenarioPartialObservation.ts‎

Lines changed: 72 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
import type { BrowserScenario } from "../domain/browserScenario.js";
2+
import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../domain/browserNetworkEvidence.js";
23
import type {
34
BrowserScenarioCaptureData,
45
BrowserScenarioPartialObservation,
56
} from "../domain/browserScenarioCapture.js";
6-
import type { BrowserScenarioStep } from "../domain/browserScenarioCaptureValues.js";
7+
import type {
8+
BrowserScenarioEvent,
9+
BrowserScenarioStep,
10+
} from "../domain/browserScenarioCaptureValues.js";
711
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
812
import { AnalysisError } from "../domain/analysisErrorBase.js";
913
import {
@@ -20,26 +24,42 @@ const OPERATION = "capture_browser_scenario" as const;
2024
const browserScenarioLimitations = (
2125
session: BrowserScenarioSessionPort,
2226
scenario: BrowserScenario,
23-
): string[] => [
24-
"Event sequence records provider receipt order; simultaneous browser causality is not inferred.",
25-
"Network content is retained only when selected; response bytes are browser-decoded, not compressed wire bytes.",
26-
"Request bytes are limited to what Playwright exposes; not_exposed does not establish body absence or multipart file coverage.",
27-
"Network content reads settle within 5 seconds each and never wait for unfinished responses or refetch them.",
28-
"Playwright scenario events do not expose request initiator stacks; receipt order does not prove causality.",
29-
"Storage values are hashed only after declared-secret redaction.",
30-
...(scenario.storage.local_storage.length === 0 &&
31-
scenario.storage.session_storage.length === 0
32-
? []
33-
: [
34-
"Non-cookie storage seeds use CDP pre-script instrumentation; only pauses in the scenario's private seed script are resumed by this observer.",
35-
]),
36-
...(session.eventLimitations?.() ?? []),
37-
...(session.mode === "connect"
38-
? [
39-
"CDP attachment cannot recover pre-attach events or guarantee launch-time context options.",
40-
]
41-
: []),
42-
];
27+
events: readonly BrowserScenarioEvent[],
28+
): string[] => {
29+
const capturedResponseBody =
30+
scenario.capture.network.response_body &&
31+
events.some(
32+
(event) =>
33+
event.kind === "network-content" &&
34+
event.phase === "response" &&
35+
event.body.state === "captured" &&
36+
(event.body.representation === "playwright-response-body-bytes" ||
37+
event.body.representation === "browser-decoded-response-bytes"),
38+
);
39+
return [
40+
"Event sequence records provider receipt order; simultaneous browser causality is not inferred.",
41+
"Network content is retained only when selected; Playwright response-body bytes are API results and are not guaranteed to match wire bytes.",
42+
"Request bytes are limited to what Playwright exposes; not_exposed does not establish body absence or multipart file coverage.",
43+
"Network content reads settle within 5 seconds each and the observer does not request bodies from unfinished responses.",
44+
...(capturedResponseBody
45+
? [PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION]
46+
: []),
47+
"Playwright scenario events do not expose request initiator stacks; receipt order does not prove causality.",
48+
"Storage values are hashed only after declared-secret redaction.",
49+
...(scenario.storage.local_storage.length === 0 &&
50+
scenario.storage.session_storage.length === 0
51+
? []
52+
: [
53+
"Non-cookie storage seeds use CDP pre-script instrumentation; only pauses in the scenario's private seed script are resumed by this observer.",
54+
]),
55+
...(session.eventLimitations?.() ?? []),
56+
...(session.mode === "connect"
57+
? [
58+
"CDP attachment cannot recover pre-attach events or guarantee launch-time context options.",
59+
]
60+
: []),
61+
];
62+
};
4363

4464
/** Project one session into the common capture fields used by success and failure. */
4565
export const browserScenarioCaptureData = (input: {
@@ -52,30 +72,37 @@ export const browserScenarioCaptureData = (input: {
5272
| "disconnected-external"
5373
| "incomplete";
5474
readonly limitations?: readonly string[];
55-
}): BrowserScenarioCaptureData => ({
56-
browser: {
57-
mode: input.session.mode,
58-
process_ownership: input.session.processOwnership,
59-
cleanup: input.cleanup,
60-
product: input.session.product,
61-
version: input.session.version,
62-
},
63-
scenario: {
64-
start_origin: new URL(input.scenario.start_url.url).origin,
65-
action_count: input.scenario.actions.length,
66-
secret_references: input.scenario.secrets
67-
.map(({ secret_id: id }) => id)
68-
.sort(),
69-
network_content: input.scenario.capture.network,
70-
},
71-
duration_ms: Date.now() - input.startedAt,
72-
steps: [...input.steps],
73-
events: input.session.events(),
74-
limitations: [
75-
...browserScenarioLimitations(input.session, input.scenario),
76-
...(input.limitations ?? []),
77-
],
78-
});
75+
}): BrowserScenarioCaptureData => {
76+
const events = input.session.events();
77+
return {
78+
browser: {
79+
mode: input.session.mode,
80+
process_ownership: input.session.processOwnership,
81+
cleanup: input.cleanup,
82+
product: input.session.product,
83+
version: input.session.version,
84+
},
85+
scenario: {
86+
start_origin: new URL(input.scenario.start_url.url).origin,
87+
action_count: input.scenario.actions.length,
88+
secret_references: input.scenario.secrets
89+
.map(({ secret_id: id }) => id)
90+
.sort(),
91+
network_content: input.scenario.capture.network,
92+
},
93+
duration_ms: Date.now() - input.startedAt,
94+
steps: [...input.steps],
95+
events,
96+
limitations: [
97+
...browserScenarioLimitations(
98+
input.session,
99+
input.scenario,
100+
events.items,
101+
),
102+
...(input.limitations ?? []),
103+
],
104+
};
105+
};
79106

80107
/** Describe the cleanup failure without discarding its resource evidence. */
81108
export const browserScenarioCleanupObservation = (

‎src/browser/PlaywrightBrowserScenarioProvider.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
type BrowserScenarioEvent,
1717
type BrowserStepArtifacts,
1818
} from "../domain/browserScenarioCaptureValues.js";
19+
import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../domain/browserNetworkEvidence.js";
1920
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
2021
import {
2122
AnalysisCancelledError,
@@ -218,6 +219,70 @@ class FakeSession implements BrowserScenarioSessionPort {
218219
}
219220

220221
describe("PlaywrightBrowserScenarioProvider", () => {
222+
it("reports response-body provenance uncertainty without marking event coverage missing", async () => {
223+
const session = new FakeSession("launch");
224+
const selected = scenario();
225+
session.eventItems = [
226+
{
227+
sequence: 1,
228+
step_index: 0,
229+
kind: "response",
230+
transaction_id: "request-1",
231+
redirected_from_transaction_id: null,
232+
method: "GET",
233+
url: sanitizeBrowserUrl("https://app.example.test/main.js"),
234+
resource_type: "script",
235+
header_names: [],
236+
status: 200,
237+
failure: null,
238+
},
239+
{
240+
sequence: 2,
241+
step_index: 0,
242+
kind: "network-content",
243+
transaction_id: "request-1",
244+
source_event_sequence: 1,
245+
phase: "response",
246+
headers: { state: "not_requested" },
247+
body: {
248+
state: "captured",
249+
representation: "playwright-response-body-bytes",
250+
encoding: "base64",
251+
content: "",
252+
bytes: 0,
253+
sha256:
254+
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
255+
media_type: "text/javascript",
256+
redacted: false,
257+
},
258+
},
259+
];
260+
const input = browserScenarioSchema.parse({
261+
...selected,
262+
capture: {
263+
...selected.capture,
264+
network: { ...selected.capture.network, response_body: true },
265+
},
266+
});
267+
const provider = new PlaywrightBrowserScenarioProvider(() =>
268+
Promise.resolve(session),
269+
);
270+
271+
const result = await provider.captureScenario(input);
272+
if (!result.ok) throw result.error;
273+
expect(result.value.limitations).toContain(
274+
PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION,
275+
);
276+
expect(result.value.completeness.missing_sections).not.toContain("events");
277+
expect(result.value.events.items[1]).toMatchObject({
278+
kind: "network-content",
279+
body: {
280+
state: "captured",
281+
representation: "playwright-response-body-bytes",
282+
},
283+
});
284+
});
285+
221286
it("makes reported event gaps ineligible for equality even in launch mode", async () => {
222287
const session = new FakeSession("launch");
223288
session.eventGaps = ["Popup frames before discovery are unavailable"];

‎src/browser/assets/PublishWebScripts.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js"
77
import { DESTINATION_CASE_COLLISION_PREFIX } from "../../artifacts/ArtifactPaths.js";
88
import { SafeOutputTree } from "../../artifacts/SafeOutputTree.js";
99
import { SafeOutputTreeCreationFailure } from "../../artifacts/SafeOutputTreeCreationFailure.js";
10+
import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../../domain/browserNetworkEvidence.js";
1011
import {
1112
webScriptExportManifestSchema,
1213
webScriptExportResultSchema,
@@ -26,7 +27,7 @@ const LIMITATIONS = [
2627
"Ordinary unambiguous URL paths preserve relative module layouts by origin, including case-distinct spellings. Query variants, exact path collisions, file/directory prefixes, inline sources, and unrepresentable paths are isolated. A case-distinct pair is isolated only when the destination filesystem cannot store both spellings; the record names that pair. Browser module relationships of isolated paths remain unknown.",
2728
"Local JavaScript analysis does not implement browser import maps, root-relative URL resolution, remote URL loading, or browser runtime behavior. It may strip import queries and fragments; isolated variants are not canonical targets.",
2829
"Source-map declarations are retained as metadata. No source maps or missing dependencies are fetched or reconstructed.",
29-
"Captured response bytes are browser-decoded bytes; Debugger sources are the exposed text encoded as UTF-8. Redacted bytes are exported exactly as retained, and may no longer parse as JavaScript.",
30+
"Scenario response bytes preserve the output of Playwright's Response.body() API; any source-body provenance caveat from the capture is retained in this manifest. Debugger sources are the exposed text encoded as UTF-8. Redacted bytes are exported exactly as retained, and may no longer parse as JavaScript.",
3031
];
3132

3233
interface PublishWebScriptsOptions {
@@ -43,6 +44,22 @@ export const publishWebScripts = async (
4344
): Promise<WebScriptExportResult> =>
4445
options.resources.run(async () => {
4546
const planned = planWebScriptExport(capture.scripts);
47+
const scenarioResponseBodyCaptured =
48+
capture.kind === "browser-scenario" &&
49+
capture.scripts.some(
50+
(script) =>
51+
script.source.kind === "scenario-response" &&
52+
script.content.state === "captured" &&
53+
(script.content.representation === "playwright-response-body-bytes" ||
54+
script.content.representation === "browser-decoded-response-bytes"),
55+
);
56+
const responseBodyProvenanceLimitations =
57+
scenarioResponseBodyCaptured &&
58+
!capture.limitations.includes(
59+
PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION,
60+
)
61+
? [PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION]
62+
: [];
4663
let tree: SafeOutputTree | undefined;
4764
let result: WebScriptExportResult | undefined;
4865
try {
@@ -70,6 +87,7 @@ export const publishWebScripts = async (
7087
scripts: records,
7188
limitations: [
7289
...capture.limitations,
90+
...responseBodyProvenanceLimitations,
7391
...LIMITATIONS,
7492
...(records.some(({ content }) => content.state === "exported")
7593
? []

‎src/browser/assets/ScenarioScriptCapture.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ const projectBody = (
9898
body.state,
9999
"No selected, completed script response bytes were retained for this request.",
100100
);
101-
if (body.representation !== "browser-decoded-response-bytes")
101+
if (
102+
body.representation !== "playwright-response-body-bytes" &&
103+
body.representation !== "browser-decoded-response-bytes"
104+
)
102105
return unavailable(
103106
"unsupported-body-representation",
104107
`Captured representation ${body.representation} is not script response bytes.`,

‎src/browser/assets/ScriptCaptureAdapters.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,11 @@ describe("script capture identity and response projection", () => {
152152
)
153153
throw new Error("Missing response bytes");
154154
content.body.redacted = true;
155+
content.body.representation = "playwright-response-body-bytes";
155156
expect(selectScriptCapture(capture).scripts[0]?.content).toMatchObject({
156157
state: "captured",
157158
redacted: true,
159+
representation: "playwright-response-body-bytes",
158160
});
159161
content.body.representation = "browser-exposed-request-bytes";
160162
expect(selectScriptCapture(capture).scripts[0]?.content).toMatchObject({

‎src/browser/network/PlaywrightNetworkContent.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export const captureNetworkHeaders = async (
7272
}
7373
};
7474

75-
/** Retain only bytes exposed by the browser; no fetch or wire-byte reconstruction occurs. */
75+
/** Retain bytes returned by Playwright's body API, after declared-secret redaction. */
7676
export const captureNetworkBody = async (
7777
read: () => Promise<Buffer | null>,
7878
phase: "request" | "response",
@@ -94,7 +94,7 @@ export const captureNetworkBody = async (
9494
representation:
9595
phase === "request"
9696
? "browser-exposed-request-bytes"
97-
: "browser-decoded-response-bytes",
97+
: "playwright-response-body-bytes",
9898
encoding: "base64",
9999
content: retained.toString("base64"),
100100
bytes: retained.length,

‎src/browser/network/PlaywrightScenarioNetwork.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,9 @@ it("associates out-of-order same-URL responses by request identity", async () =>
178178
(event) =>
179179
event.phase === "response" && bodyText(event) === `reply:${marker}`,
180180
);
181+
expect(response).toMatchObject({
182+
body: { representation: "playwright-response-body-bytes" },
183+
});
181184
expect(request?.transaction_id).toBe(response?.transaction_id);
182185
expect(request?.source_event_sequence).not.toBe(
183186
response?.source_event_sequence,

0 commit comments

Comments
 (0)