@full-self-browsing/phantom-stream 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +48 -2
  2. package/dist/types/adapters/extension.d.ts.map +1 -1
  3. package/dist/types/adapters/playwright.d.ts.map +1 -1
  4. package/dist/types/capture/index.d.ts +150 -0
  5. package/dist/types/capture/index.d.ts.map +1 -1
  6. package/dist/types/index.d.ts +2 -0
  7. package/dist/types/player/index.d.ts +136 -0
  8. package/dist/types/player/index.d.ts.map +1 -0
  9. package/dist/types/protocol/constants.d.ts +22 -0
  10. package/dist/types/protocol/constants.d.ts.map +1 -1
  11. package/dist/types/protocol/index.d.ts +1 -0
  12. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  13. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  14. package/dist/types/protocol/messages.d.ts +326 -4
  15. package/dist/types/protocol/messages.d.ts.map +1 -1
  16. package/dist/types/recorder/index.d.ts +207 -0
  17. package/dist/types/recorder/index.d.ts.map +1 -0
  18. package/dist/types/renderer/asset-policy.d.ts +72 -0
  19. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  20. package/dist/types/renderer/diff.d.ts.map +1 -1
  21. package/dist/types/renderer/index.d.ts +61 -8
  22. package/dist/types/renderer/index.d.ts.map +1 -1
  23. package/dist/types/renderer/media-player.d.ts +114 -0
  24. package/dist/types/renderer/media-player.d.ts.map +1 -0
  25. package/dist/types/renderer/overlays.d.ts +12 -0
  26. package/dist/types/renderer/overlays.d.ts.map +1 -1
  27. package/dist/types/renderer/parser-safe.d.ts +26 -0
  28. package/dist/types/renderer/parser-safe.d.ts.map +1 -0
  29. package/dist/types/renderer/sanitize.d.ts +22 -0
  30. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  31. package/dist/types/renderer/snapshot.d.ts +38 -0
  32. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  33. package/dist/types/transport/websocket.d.ts.map +1 -1
  34. package/docs/ARCHITECTURE.md +83 -4
  35. package/docs/QUICKSTARTS.md +64 -0
  36. package/docs/SECURITY.md +279 -2
  37. package/docs/paper/OUTLINE.md +24 -91
  38. package/examples/bookmarklet-demo/viewer.html +12 -3
  39. package/examples/extension-mv3/viewer.html +10 -3
  40. package/package.json +25 -1
  41. package/src/adapters/extension.js +202 -7
  42. package/src/adapters/playwright-inject.js +645 -28
  43. package/src/adapters/playwright.js +176 -2
  44. package/src/capture/README.md +96 -1
  45. package/src/capture/index.js +1672 -40
  46. package/src/index.js +2 -0
  47. package/src/player/README.md +175 -0
  48. package/src/player/index.js +627 -0
  49. package/src/protocol/constants.js +24 -0
  50. package/src/protocol/index.js +1 -0
  51. package/src/protocol/media-reconcile.js +188 -0
  52. package/src/protocol/messages.js +195 -4
  53. package/src/recorder/README.md +225 -0
  54. package/src/recorder/index.js +487 -0
  55. package/src/renderer/README.md +111 -8
  56. package/src/renderer/asset-policy.js +172 -0
  57. package/src/renderer/diff.js +158 -15
  58. package/src/renderer/index.js +978 -21
  59. package/src/renderer/media-player.js +367 -0
  60. package/src/renderer/overlays.js +324 -0
  61. package/src/renderer/parser-safe.js +111 -0
  62. package/src/renderer/sanitize.js +25 -3
  63. package/src/renderer/snapshot.js +534 -3
  64. package/src/transport/websocket.js +36 -0
package/docs/SECURITY.md CHANGED
@@ -26,6 +26,7 @@ while ensuring configured private content never leaves the captured page.
26
26
  | Shadow root, same-origin frame, or subtree recovery HTML | New HTML insertion surface in the mirror | Same `sanitizeForWire` capture chokepoint, render-side `sanitizeFragment`, CSP meta, and no-`allow-scripts` sandbox |
27
27
  | Cross-origin iframe content | Browser-origin data leakage | Capture never reads cross-origin iframe content; renderer shows content-free placeholders only |
28
28
  | Live value diffs | Typed values bypass snapshot masking | `DIFF_OP.VALUE` payloads route through capture-side value masking before transport |
29
+ | Stored recordings replayed later | Page content at rest; hostile recording replay | Capture-side masking before recording; playback only through `createViewer`; inert playback mirror (section 8) |
29
30
  | Future serialization path bypass | A new writer skips sanitization or masking | Static scan in `tests/security-chokepoint-purity.test.js` |
30
31
  | New renderer `innerHTML` sink or sandbox weakening | Render-side defense bypass | InnerHTML allowlist and `allow-scripts` forbidden scan |
31
32
  | Security contract rot | Docs stop matching shipped controls | `docs/SECURITY.md` marker guard in the purity test |
@@ -100,6 +101,21 @@ must mirror arbitrary real pages without breaking benign markup.
100
101
  serialized and reparsed. String scrub/reparse is the mXSS anti-pattern this pipeline avoids.
101
102
  - Strips and scrubs are counted and logged. They are never silent health events.
102
103
 
104
+ Parser-safe placeholders. Capture renames elements whose nesting HTML text cannot express (for
105
+ example a button inside a button) to `<ps-node data-ps-tag="original-tag">` in the detached wire
106
+ clone, after masking and the capture-side strips, and removes `data-ps-tag` from every page-owned
107
+ `<ps-node>`, so a page cannot ask the viewer to create a tag. The viewer restores a placeholder only
108
+ when its tag is on an allowlist: button, a, form, nobr, p, h1-h6, li, dd, dt, option, optgroup,
109
+ select, textarea, xmp, plaintext, img, input, br, hr, wbr, area, col, source, track, table, tbody,
110
+ thead, tfoot, tr, td, th, caption and colgroup. `script`, `iframe`, `object`, `embed`, `style`,
111
+ `link`, `meta`, `base`, `html`, `head`, `body` and `frameset` are never restored and stay inert
112
+ generic elements. The restore runs right after each parse and before the post-parse scrub and the
113
+ asset gate, so restored elements get the same `on*`, URL-scheme and fetch treatment as any other
114
+ element. In the live snapshot and frame documents, where a restored `<img>` would fetch as soon as
115
+ its `src` is set, `src`, `srcset` and `data-ps-currentsrc` on restored img, input, source and track
116
+ are passed through the viewer's asset gate first and dropped when blocked. Template parses are inert
117
+ and are gated before `importNode`. No new `innerHTML` sink exists for this.
118
+
103
119
  ## 4. Masking Guarantees
104
120
 
105
121
  Masking is capture-side only. Masked content is transformed before transport and never appears
@@ -109,7 +125,9 @@ on the wire in raw form.
109
125
  - `maskInputs: true` masks input, textarea, and related form value surfaces.
110
126
  - `maskTextSelector` masks text owned by matching elements and descendants. The default transform
111
127
  replaces each non-whitespace character with `*`, preserving whitespace and length.
112
- - `blockSelector` emits a placeholder box with only `data-fsb-nid`, `rr_width`, and `rr_height`.
128
+ - `blockSelector` emits a placeholder box carrying only the `rr_width` and `rr_height` dimension
129
+ attributes -- no `data-fsb-nid`, no other attributes, no children, no text. Identity travels
130
+ positionally in the `nodeIds` sidecar, never as a page-visible attribute on the placeholder.
113
131
  Attributes, children, and text from the blocked subtree are not serialized.
114
132
  - Invalid selectors fail at factory time with `invalid-mask-selector` instead of silently falling
115
133
  back to an unsafe state.
@@ -121,6 +139,96 @@ on the wire in raw form.
121
139
  - `select` / `option` display text remains a known privacy boundary: value masking does not make
122
140
  option labels private unless they are also covered by `maskTextSelector` or `blockSelector`.
123
141
 
142
+ ### Asset and media URL masking (MSEC-03)
143
+
144
+ v2.0 mirrors images and `<video>` / `<audio>` **by reference** -- the wire carries URL strings and
145
+ small playback state, and the viewer fetches the bytes (see §6). A signed-CDN URL can therefore
146
+ carry credential/PII query params, and a media element's URL plus playback timeline can itself be
147
+ private. Three host masking options, all validated at factory time alongside the existing
148
+ selector family, redact or block those URLs **capture-side, before transport** -- the wire is
149
+ already clean and the renderer never un-masks. URL masking lives in one place: a dedicated
150
+ `'asset-url'` / `'media-url'` dispatch in `sanitizeForWire`, so every **single-URL** attribute
151
+ (the `src`, `href`, `action`, `poster`, `data` set) across the snapshot, iframe, and added-node
152
+ serialization paths plus the mutation attr path routes through the same testable helper.
153
+
154
+ The built-in `maskAssetUrls` token-param strip applies to those single-URL attributes only.
155
+ **`srcset` candidate lists are NOT token-masked by the boolean.** A `srcset` value is
156
+ scheme-scrubbed per candidate (`scrubSrcset` neutralizes a hostile `javascript:` / `data:text/html`
157
+ candidate) and absolutified, but its candidate URLs do not flow through the token-param strip, so a
158
+ token in a responsive candidate (`srcset="https://cdn/x.jpg?X-Amz-Signature=... 2x"`) would survive
159
+ `maskAssetUrls: true`. To redact srcset tokens, either match the element with `maskMediaSelector`
160
+ (which omits the whole element's URLs and degrades it to the dimensioned placeholder) or use
161
+ `maskAssetUrlFn` per element; the boolean's name-keyed query strip is single-URL-attribute scoped
162
+ by design.
163
+
164
+ - `maskMediaSelector` -- a CSS selector. A matched media/asset element **omits its URL from the
165
+ wire and degrades to the dimensioned placeholder** (the `blockSelector` path: a dimension-only
166
+ box carrying just `rr_width` + `rr_height`, with no `data-fsb-nid`, no other attributes, no
167
+ children, and no text -- identity travels in the `nodeIds` sidecar). It also reuses the
168
+ media-tracker skip predicates, so a masked `<video>` / `<audio>` emits **no `STREAM.MEDIA`**
169
+ baseline and **no `STREAM.MEDIA`** events -- neither its URL nor its playback timeline is
170
+ mirrored.
171
+ - `maskAssetUrls` -- a boolean. When `true`, every asset/media URL is parsed and its **token / PII
172
+ query params are stripped** before it goes on the wire; functional params are **preserved (not
173
+ stripped)**. It is **off by default**, so with masking disabled asset/media URLs stay
174
+ **byte-identical** on the wire (the differential oracle is preserved, no new ledger entry).
175
+ Byte-identity is guaranteed only on the no-strip path: when a URL has no denied param the
176
+ original string is returned **unchanged** (no `URL.toString()`, so no normalization), which is
177
+ also what keeps the off-by-default oracle intact. When a denied param **is** removed the URL is
178
+ re-serialized via `URL.toString()`, so the surviving functional params are preserved
179
+ *semantically* but the string may be normalized equivalently (`%20` -> `+`, host lowercased,
180
+ a default `:443` / `:80` dropped, percent-encoding canonicalized). This re-encode decodes to the
181
+ same bytes server-side -- it is not a fetch break -- but it is a wire divergence, so "survives
182
+ byte-for-byte" holds only for URLs that carried no denied param.
183
+ - `maskAssetUrlFn(url, ctx) => string | null` -- a custom redactor with full host control. A
184
+ returned string replaces the URL; `null` **blocks** the URL (placeholder); and a **thrown error
185
+ fails closed -- the URL is blocked** (not raised, never passed raw). This is stricter than the
186
+ text mask functions (whose fallback is the default asterisk mask) because a thrown URL redactor
187
+ is an undecided-unsafe URL, which must not be fetched. `ctx` carries the element/attr/tag/nid so
188
+ the host can decide per asset.
189
+
190
+ The `maskAssetUrls` strip removes only **credential / signature / expiry / secret** params; it is
191
+ matched **case-insensitively**, by **exact name OR a denied prefix**. Functional params (`w`, `h`,
192
+ `q`, `format`, `v`, `id`, a `?t=` seek timestamp, etc.) are never stripped -- though on a URL where
193
+ some other param *is* stripped they ride along through the `URL.toString()` re-serialization and
194
+ may come back equivalently re-encoded (see the `maskAssetUrls` bullet above). The documented
195
+ denylist:
196
+
197
+ | Source | Param names |
198
+ |---|---|
199
+ | AWS S3 / CloudFront presigned (SigV4) | `X-Amz-Signature`, `X-Amz-Credential`, `X-Amz-Security-Token`, `X-Amz-Algorithm`, `X-Amz-Date`, `X-Amz-Expires`, `X-Amz-SignedHeaders`, plus the `x-amz-` *prefix* family |
200
+ | AWS S3 / CloudFront presigned (SigV2 / canned policy) | `AWSAccessKeyId`, `Signature`, `Expires`, `Policy`, `Key-Pair-Id` |
201
+ | Google Cloud Storage signed URL | `X-Goog-Signature`, `X-Goog-Credential`, `X-Goog-Algorithm`, `X-Goog-Date`, `X-Goog-Expires`, `X-Goog-SignedHeaders`, `GoogleAccessId`, plus the `x-goog-` *prefix* family |
202
+ | Azure Blob SAS | `sig`, `se`, `sp`, `sv`, `sr`, `st`, `skoid`, `sktid`, `skt`, `ske`, `sks`, `skv`, `spr`, `sip`, `ss`, `srt` |
203
+ | Generic token / secret / auth | `token`, `access_token`, `auth`, `authorization`, `apikey`, `api_key`, `key`, `signature`, `sign`, `hash`, `hmac`, `jwt`, `password`, `passwd`, `pwd`, `secret`, `session`, `sessionid`, `sid`, `expires`, `expiry`, `policy` |
204
+
205
+ The `x-amz-` / `x-goog-` prefix rules subsume the explicit AWS / GCP rows; both are listed for
206
+ clarity. `Expires` / `se` / `X-Amz-Expires` / `X-Goog-Expires` are stripped because a signed-URL
207
+ expiry timestamp is a replay / privacy signal; a plain content `?t=42` seek timestamp is a
208
+ different name and survives. The list is opt-in (`maskAssetUrls`) and auditable here; a host that
209
+ needs different membership uses `maskAssetUrlFn` for full control.
210
+
211
+ **Known residuals of the built-in `maskAssetUrls` strip.** The boolean strip is keyed on
212
+ `URLSearchParams` param **names**, which split a query only on `&`. Two shapes therefore fall
213
+ outside it:
214
+
215
+ - **Matrix / `;`-separated query params.** A legacy `;`-delimited query
216
+ (`?w=10;token=SECRET&sig=x`) hides the token inside another param's *value* (`w` =
217
+ `"10;token=SECRET"`), so the name match never sees it and it survives on the wire (the
218
+ separately-named `sig` is still stripped). Semicolon query separators are legacy and uncommon,
219
+ so the built-in strip does not split on `;`; a host whose signed URLs use matrix params (or that
220
+ needs airtight redaction) should use `maskAssetUrlFn`, which receives the raw URL string and can
221
+ redact any shape.
222
+ - **URL fragments.** A token in the fragment (`#access_token=...`) is not part of the query at
223
+ all. When the fragment carries a **denylisted param name** the built-in strip now drops the
224
+ whole fragment (it is never needed for an asset/media fetch); a fragment that merely contains
225
+ `=` without a denied name (an opaque app-router route, for example) is left intact, so a host
226
+ with credential-bearing fragments under non-denylisted names should still reach for
227
+ `maskAssetUrlFn`.
228
+
229
+ Both residuals are fully covered by `maskAssetUrlFn`, which sees the complete URL string before
230
+ any name-keyed parsing.
231
+
124
232
  ## 5. Host must-nevers
125
233
 
126
234
  Hosts embedding PhantomStream must preserve these rules:
@@ -132,8 +240,149 @@ Hosts embedding PhantomStream must preserve these rules:
132
240
  `textContent`; custom renderers should do the same.
133
241
  - Never add an opt-out switch for the capture or render sanitizers.
134
242
  - Never weaken the adopted CSP policy below script-blocking.
243
+ - Never relax the fail-closed asset-origin policy into an allow-by-default posture, and
244
+ never move the asset fetch gate after the URL is written into the mirror (a post-write
245
+ gate is too late -- the browser has already issued the GET). Widen reachable origins
246
+ only through `allowAssetOrigins` / the `assetOriginPolicy` hook.
247
+ - Never replay a recording outside `createPlayer` or `createViewer`, and never set
248
+ `inert: false` on a player for recordings you do not trust.
249
+
250
+ ## 6. Viewer-side resource fetching
251
+
252
+ v2.0 changes the viewer's verb from **render-inert to fetch**. In v1 the mirror only rendered
253
+ attacker-influenced markup inertly; from Phase 12 on, a mirrored `<img>` / `<source>` / `<video>`
254
+ poster / CSS `background-image` causes the **viewer's own browser** to issue a GET from the
255
+ viewer's (possibly privileged) network. Static images are the first instance of this fetch
256
+ surface, so the viewer-fetch security model lands here. Mirrored asset bytes never traverse the
257
+ relay -- the wire carries URL strings only; the viewer fetches directly from the source/CDN.
258
+
259
+ **Fail-closed origin policy (MSEC-01).** A pure, fail-closed origin classifier
260
+ (`classifyAssetOrigin` in `src/renderer/asset-policy.js`) decides which asset URLs the viewer may
261
+ fetch. It is a *fetch* control, distinct from the *injection* control `hasDangerousScheme`: an
262
+ `https://` URL to an internal host passes the injection check yet is a blind-SSRF / tracking
263
+ surface, which this classifier blocks. The default posture is **https-only plus a private /
264
+ internal denylist**; anything not provably public-https is blocked:
265
+
266
+ - scheme must be `https:` (non-`http(s)` and plain `http:` are blocked);
267
+ - hosts denied: `localhost`, `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`,
268
+ `192.168.0.0/16`, `169.254.0.0/16` (link-local), `::1`, `fc00::/7` (`fc..`/`fd..` ULA), and
269
+ `.local` / unqualified (dotless) hosts;
270
+ - any parse error fails closed (blocked).
271
+
272
+ A blocked origin is replaced by a dimensioned `data-ps-asset-unavailable="blocked-origin"`
273
+ placeholder, so the viewer's browser **never issues the GET** -- no tracking beacon fires and no
274
+ internal host is probed.
275
+
276
+ **Host override surface.** Two seams widen the conservative default, never relax it below
277
+ fail-closed:
135
278
 
136
- ## 6. Residual Risks
279
+ - `assetOriginPolicy(url, ctx) => boolean` -- a host hook that **fails closed**: it blocks on a
280
+ thrown error or any non-`true` return (it can never open a URL the classifier would allow only
281
+ by throwing). This mirrors the capture-side `compileMaskSelector` fail-closed-and-loud
282
+ precedent.
283
+ - `allowAssetOrigins` -- a convenience host allowlist; a listed host passes the gate even if the
284
+ classifier would otherwise deny it.
285
+
286
+ **`mediaMode` switch (MSEC-02).** A `createViewer` config option selects the privacy / bandwidth
287
+ posture: `off` (no viewer asset fetch at all -- every asset becomes a placeholder), `poster`
288
+ (*target* posture: posters/placeholders only, full-asset fetch withheld -- see the Phase-12
289
+ interim note below), and `reference` (full by-reference fetch). The **default is `reference`** --
290
+ media-by-reference is on by default (the milestone's purpose) and the fail-closed origin policy is
291
+ the safety net. An invalid `mediaMode` throws at viewer-factory time (the sanctioned throw site).
292
+
293
+ > **Phase 12 interim semantics for `poster` (review WR-02 -- read before relying on `poster`).**
294
+ > The poster / full-asset split is a Phase 13 deliverable, gated on the `<video>` / `<audio>`
295
+ > element actually shipping. In Phase 12 `poster` therefore behaves **identically to `reference`
296
+ > for images**: every origin-permitted image (content image OR `<video>` poster) is allowed to
297
+ > fetch, gated only by the fail-closed origin policy -- there is no content-image-vs-poster
298
+ > distinction yet (the gate's `kind` parameter is threaded through but does not yet narrow
299
+ > `poster`). A host that needs *all* content-image fetches suppressed today must use `off`, not
300
+ > `poster`. The stricter "posters only, full-asset withheld" guarantee lands in Phase 13.
301
+
302
+ **Pre-write timing (the non-negotiable rule).** The gate runs **before** the asset URL is written
303
+ into the mirror DOM, so a blocked origin never reaches a fetch. For diffs this is pre-`setAttribute`
304
+ (ATTR) and pre-`importNode` (ADD / subtree, over inert template content). For the **snapshot** it
305
+ is gated at the **string / payload layer**, before the srcdoc is assembled (`gateSnapshotAssets`
306
+ in `src/renderer/snapshot.js`): a real browser's HTML parser begins fetching `<img src>` *during*
307
+ srcdoc parse, before the post-parse scrub can run, so a post-parse-only gate would let the initial
308
+ snapshot image GET fire for a blocked origin. This string-layer rewrite operates on the typed
309
+ asset values being emitted -- it is **not** the scrub-then-reparse mutation-XSS anti-pattern
310
+ (`payload.html` stays raw for everything else); the post-parse DOM gate remains as
311
+ defense-in-depth.
312
+
313
+ **Variant pinning (ASST-03).** When a mirrored element carries the clone-only `data-ps-currentsrc`
314
+ enrichment, the renderer sets the element's effective `src` to that value and neutralizes
315
+ `srcset` / `sizes`, so the cross-origin viewer (different DPR/viewport) loads the same asset the
316
+ origin displayed rather than re-negotiating a different variant.
317
+
318
+ **Unchanged sandbox / CSP (no widening).** Phase 12 adds **no** sandbox or CSP-script change. The
319
+ iframe sandbox remains exactly `allow-same-origin` (never `allow-scripts`; the asset code contains
320
+ no `allow-scripts` literal and the static scan stays green), and the srcdoc CSP is unchanged:
321
+ `default-src 'none'`, the existing `img-src http: https: data:` already covers every static image
322
+ surface (including `<video>` poster), there is **no `script-src`**, and there is **no `media-src`**
323
+ -- the scoped `media-src` directive is deferred to Phase 13 (when `<video>`/`<audio>` actually
324
+ needs it). Capture-side asset/media URL **masking** and `referrerpolicy` completion are **done in
325
+ Phase 15** (MSEC-03/MSEC-04): see §4 Masking Guarantees for the masking vocabulary and the
326
+ **Referrer and credentials** subsection below for the `referrerpolicy="no-referrer"` /
327
+ no-credentials posture. Phase 12 makes the fetch-gate decisions, not the masking.
328
+
329
+ **Referrer and credentials (MSEC-04, completed in Phase 15).** Because the viewer's browser now
330
+ fetches mirrored asset/media URLs, two leakage vectors are closed at the document level:
331
+
332
+ - **`referrerpolicy="no-referrer"`** is delivered once as a document-level
333
+ `<meta name="referrer" content="no-referrer">` injected into the srcdoc `<head>` **immediately
334
+ after the CSP meta** (`src/renderer/snapshot.js`), before the charset, viewport, the first
335
+ stylesheet `<link>`, and the first payload `<img>`. One document control covers **every**
336
+ viewer subresource fetch -- `<img>`, `<video>` / `<source>`, `<video>` poster, CSS
337
+ `background-image` / `url()`, fonts -- including CSS-initiated fetches that a per-element
338
+ `referrerpolicy` attribute could never reach. The mirrored page URL (which can itself carry
339
+ tokens) therefore never leaks in the `Referer` header to third-party CDNs.
340
+ - **No credentials by default.** The posture already holds and is now documented and asserted: an
341
+ `allow-same-origin`-sandboxed srcdoc with **no `crossorigin` attribute** anywhere issues no-CORS
342
+ cross-origin GETs that omit credentials to third-party origins. Phase 15 deliberately adds **no**
343
+ `crossorigin` attribute -- forcing `crossorigin="anonymous"` would turn benign fetches into CORS
344
+ requests and break otherwise-fine assets served without `Access-Control-Allow-Origin`.
345
+
346
+ The string-layer contract (the `no-referrer` meta is present, ordered after the CSP meta and
347
+ before the first subresource, and no `crossorigin` attribute is emitted) is unit-pinned. The
348
+ **live** referrer suppression and credential omission -- real `Referer`-less GETs and CSP
349
+ enforcement observed in a browser -- are the documented deferred real-browser UAT, since jsdom
350
+ neither parses the srcdoc nor issues real subresource requests (the same hidden-tab / jsdom limit
351
+ as Phases 13-14).
352
+
353
+ ### Parent-Realm Object-URL Threat Model
354
+
355
+ Adaptive playback (HLS / DASH via Media Source Extensions) mints a `blob:` **object URL** in the
356
+ **parent (renderer-owning) realm** -- `URL.createObjectURL(mediaSource)` -- and assigns it to the
357
+ **inert in-iframe** `<video>.src`. hls.js runs in the parent and `attachMedia`s the iframe element;
358
+ the **parent** fetches every media segment and appends to the `SourceBuffer`. This is the one
359
+ genuinely novel cross-realm construct in v2.0, so its blast radius is threat-modeled here against
360
+ the existing sandbox. The asset under consideration is that parent-origin `blob:` object URL.
361
+
362
+ | # | Threat | STRIDE | Why it is mitigated |
363
+ |---|---|---|---|
364
+ | 1 | Mirrored (attacker-influenced) content scripts the page to read the object URL's bytes and exfiltrate them | Information Disclosure | The iframe sandbox is **exactly `allow-same-origin`, never `allow-scripts`** -- no script runs inside the mirror at all. A `blob:` URL is readable only via `fetch` / `XHR` / `FileReader`, all of which require script. With no script the child can *play* the element but cannot *read* the blob. `createViewer` reads the token back and throws `viewer-sandbox-invalid` on any deviation. |
365
+ | 2 | The object URL is parent-origin -- can the child reach parent-origin `blob:` resources for non-media use? | Information Disclosure / Elevation of Privilege | The blob's origin is the **parent document's**, not the mirrored page's. The child has no script to dereference it, and CSP `media-src blob:` permits only media *loading* of `blob:`, not `fetch` / `connect` (there is **no `connect-src`**). The blob is usable solely as a media source by the inert element. |
366
+ | 3 | A leaked / long-lived object URL persists after the player is gone (use-after-free / leak / cross-session bleed) | Information Disclosure / Denial of Service | The object URL is **revoked on `destroy` / `destroyAll`** (`URL.revokeObjectURL`), and `destroyAll()` runs before any new-identity snapshot document swap, tearing down every parent-realm player first. A revoked `blob:` is dead; a later session cannot resolve it. |
367
+ | 4 | `blob:` widens the CSP enough to load arbitrary local resources | Tampering | `blob:` is scoped to **`media-src` only** (not `img-src`, not `default-src`). `default-src 'none'` plus the absence of `script-src` / `connect-src` means `blob:` cannot be used for script, XHR, or any non-media fetch. |
368
+ | 5 | The parent realm itself is the privileged attacker target (segment fetches, MSE in the parent) | Elevation of Privilege | The parent realm is **renderer / host code**, not mirrored content -- it was never sandboxed and is trusted by construction. The threat boundary is *mirrored content -> host*, and that boundary **is** the sandbox; moving the player to the parent is precisely what *avoids* granting the sandbox `allow-scripts`. |
369
+
370
+ **Plain-language worst case:** the child iframe plays the parent's media object URL but cannot
371
+ script, read, copy, or exfiltrate it -- there is no `allow-scripts`, no `connect-src`, and the
372
+ `blob:` is dead the moment the player is destroyed. The only thing the mirror can do with the
373
+ object URL is what a `<video>` does with a source it was handed: render frames. An attacker who
374
+ fully controls the mirrored page gains the ability to display media the host already chose to
375
+ mirror, and nothing more.
376
+
377
+ Backing tests: the sandbox token is unchanged (`createViewer` `viewer-sandbox-invalid` + the
378
+ purity scan); `allow-scripts` is absent from `src/renderer/media-player.js` (the purity-test
379
+ renderer glob covers it, and `tests/security-media.test.js` names the case); `blob:` is scoped to
380
+ `media-src` with no `script-src` / `connect-src` (`tests/renderer-media-csp.test.js`); the object
381
+ URL is revoked on `destroy` / `destroyAll` (`tests/renderer-media-player.test.js` and
382
+ `tests/security-media.test.js`); and a late cross-session `STREAM.MEDIA` frame is rejected by
383
+ `isCurrentStream` (`tests/security-media.test.js`, citing `tests/renderer-media.test.js`).
384
+
385
+ ## 7. Residual Risks
137
386
 
138
387
  Snapshot `payload.html` remains string-raw at the srcdoc assembly layer by design. Scrubbing an
139
388
  HTML string and then asking the browser to parse it again is the mutation-XSS failure mode. The
@@ -154,3 +403,31 @@ Closed shadow roots, cross-origin iframe content, and media stream pixels remain
154
403
  non-captured content. PhantomStream does not bypass those browser boundaries.
155
404
  CSSOM mode is stylesheet capture only; it does not capture protected browser
156
405
  content or weaken the sanitizer, CSP, or sandbox constraints.
406
+
407
+ ## 8. Recordings and playback
408
+
409
+ The recorder (`src/recorder/`) stores a capture stream, and the player (`src/player/`) replays it
410
+ later through `createViewer`. Five rules apply:
411
+
412
+ 1. **Recordings hold page content at rest.** A recording is the post-masking wire content: DOM
413
+ text, attribute values, unmasked form values, overlay labels, and host mark data. Masking
414
+ happens in capture, before a message reaches the recorder, so configure `blockSelector`,
415
+ `maskTextSelector`, and `maskInputs` before recording. Protect stored recordings like the live
416
+ stream: access control, retention limits, and encryption at rest.
417
+ 2. **A recording is attacker-influenced input,** exactly like a live stream, and it may also have
418
+ been tampered with between recording and playback. The player writes no HTML: it routes every
419
+ payload through `createViewer`, so playback gets the same render sanitizers, srcdoc CSP, and
420
+ sandbox (exactly `allow-same-origin`) as a live mirror. `validateRecording` checks structure
421
+ only (format, version, bounds, event shape, time order, and a renderable snapshot); it is not
422
+ a content filter.
423
+ 3. **The player is inert by default.** A sandboxed srcdoc frame runs no script, but it can still
424
+ navigate itself when a mirrored link is clicked. The player sets `inert`,
425
+ `pointer-events: none`, and `tabindex="-1"` on its mirror iframe, so pointer and keyboard
426
+ input never reach mirrored links or forms. `inert: false` is for trusted recordings only.
427
+ 4. **The asset policy applies at playback time.** Images and media load by reference when the
428
+ recording is played, possibly long after it was made, through the same fail-closed gate
429
+ (section 6). For untrusted recordings use `mediaMode: 'poster'` or `mediaMode: 'off'`, or an
430
+ `assetOriginPolicy`. Playback reveals the viewer's network identity (address and timing) to
431
+ every asset origin the recording references.
432
+ 5. **Host marks and overlay labels are data.** Render marker payloads and overlay labels with
433
+ `textContent`, never as HTML, as with dialog and overlay text everywhere else.
@@ -1,100 +1,33 @@
1
- # Paper Outline — PhantomStream: DOM-Native Live Mirroring for Agentic Browsing
1
+ # Paper Draft — PhantomStream: DOM-Native Live Mirroring for Agentic Browsing
2
2
 
3
- > Working title. Status: outline. Venue candidates: WWW / UIST / CHI (system track),
4
- > or an agents/HCI workshop for an early version.
3
+ Status: IEEE-style LaTeX draft exists in [`paper/main.tex`](../../paper/main.tex), with
4
+ measured local benchmark results generated from [`bench/results/local-latest.json`](../../bench/results/local-latest.json).
5
5
 
6
- ## Abstract (draft sketch)
6
+ ## Build
7
7
 
8
- AI agents increasingly operate real browsers on a user's behalf. Supervising such an agent
9
- requires a live, trustworthy view of what it is doing — but video streaming is
10
- bandwidth-heavy, semantically opaque (which element is the agent touching?), and awkward to
11
- control through. We present PhantomStream, a DOM-native mirroring system that streams a
12
- live tab as a style-inlined snapshot plus display-matched MutationObserver diffs addressed
13
- by stable node identities, over a compressed, size-capped relay, reconstructed in a
14
- sandboxed viewer with bidirectional control. Deployed inside an open-source browsing agent
15
- (FSB), PhantomStream achieves [X]% lower bandwidth than WebRTC screen capture and [Y] ms
16
- mirror latency while preserving element-level semantics that enable action highlighting and
17
- click-through remote control. We report the reliability mechanisms — dual watchdogs,
18
- session-identity staleness guards, budgeted truncation — that emerged from production
19
- failures, and quantify the fidelity/bandwidth trade-offs of computed-style capture
20
- strategies.
8
+ From the repository root:
21
9
 
22
- ## 1. Introduction
10
+ ```sh
11
+ npm run bench:local
12
+ npm run paper:check
13
+ ```
23
14
 
24
- - The agentic-browsing supervision problem: trust, observability, intervention.
25
- - Why pixels are the wrong abstraction for watching an agent: no element identity, no
26
- cheap idle state, no semantic overlay channel.
27
- - Contributions:
28
- 1. A DOM-native live-mirroring architecture (snapshot + nid-addressed diffs +
29
- side channels + reverse control path).
30
- 2. Reliability mechanisms for hostile runtime conditions (MV3 SW eviction, relay
31
- message caps, slow/heavy pages) with production failure data.
32
- 3. An empirical comparison of style-capture strategies (full enumeration vs. curated
33
- inlining vs. stylesheet-centric) on fidelity, payload size, and serialize latency.
34
- 4. Open-source framework + evaluation harness.
15
+ `npm run bench:local` runs the deterministic local corpus and refreshes
16
+ `paper/generated-results.tex`. `npm run paper:check` validates the benchmark result
17
+ shape, checks for unresolved placeholders, and builds `paper/main.pdf` through
18
+ `tectonic`.
35
19
 
36
- ## 2. Related work
20
+ ## Current Draft Scope
37
21
 
38
- - **Session replay:** rrweb, SessionStack, LogRocket — record/replay vs. live mirroring;
39
- rrweb's stylesheet capture vs. our computed-style inlining (discuss trade-off honestly).
40
- - **Remote display:** VNC/RDP, WebRTC screen capture, Chrome DevTools Protocol screencast.
41
- - **Co-browsing:** Surfly, Upscope — commercial DOM co-browsing, little published detail.
42
- - **DOM diffing/virtual DOM literature**; CRDTs for DOM (peritext-adjacent) — why a
43
- single-writer mirror needs none of that.
44
- - **Agent observability:** browser-use/agent frameworks' screenshot streams; computer-use
45
- model viewers.
22
+ - Format: IEEE conference LaTeX, matching the Lattice paper style.
23
+ - Evaluation: deterministic local corpus with five pages and three activities.
24
+ - Baselines: PhantomStream, rrweb recorder/replay, and CDP PNG screencast.
25
+ - WebRTC: explicitly not claimed in this draft because headless Chromium does not provide
26
+ the same interactive `getDisplayMedia` permission surface as a real capture session.
46
27
 
47
- ## 3. System design
28
+ ## Next Paper Work
48
29
 
49
- Map of docs/ARCHITECTURE.md §§2–4, reframed as design decisions with rationale:
50
-
51
- - 3.1 Node identity (nid stamping; observability trade-off; WeakMap alternative)
52
- - 3.2 Snapshot serialization (parallel TreeWalker, URL absolutification, canvas, iframes)
53
- - 3.3 Style capture (the 45 s YouTube story; curated 85-prop list; default elision)
54
- - 3.4 Diff pipeline (rAF batching = display-matched delivery)
55
- - 3.5 Size budgeting (relay caps, 2-pass whole-subtree truncation, single-flush layout reads)
56
- - 3.6 Transport (LZ envelope, session identity, staleness rejection)
57
- - 3.7 Viewer (srcdoc reconstruction, scaling, layout modes, overlays, dialogs)
58
- - 3.8 Reverse path (remote control coordinate reverse-mapping)
59
-
60
- ## 4. Reliability in production
61
-
62
- The dual-watchdog design; MV3 service-worker eviction as an adversary; pending-intent
63
- re-arm for the startup race; staleFlushCount telemetry. Frame as: "what a lab prototype
64
- would not have needed, and a deployed system did" — supported by the inserted-phase
65
- history (122.1–122.4, 211, 276).
66
-
67
- ## 5. Evaluation (planned)
68
-
69
- - **Bandwidth:** PhantomStream vs. WebRTC screen capture vs. CDP screencast vs. rrweb
70
- live-mode across a site corpus (static article, infinite scroll feed, SPA dashboard,
71
- video-heavy page) and activity levels (idle, reading, agent-driven automation).
72
- - **Latency:** mutation-to-mirror-paint time distribution; snapshot time vs. page weight.
73
- - **Fidelity:** perceptual diff (SSIM / pixel-diff of mirror vs. real tab screenshots)
74
- across Alexa/Tranco top-N pages; failure taxonomy (shadow DOM, canvas, video, iframes).
75
- - **Style strategies ablation:** full-enumeration vs. curated-inlined vs.
76
- stylesheet-centric capture on the three axes above.
77
- - **Reliability:** watchdog rescue rates and stream-strand incidence from FSB telemetry
78
- (if usable) or synthetic fault injection.
79
-
80
- ## 6. Discussion & limitations
81
-
82
- Frozen-style drift; un-mirrored realms (shadow DOM, cross-origin iframes, media);
83
- sanitization/security model of rendering attacker-influenced HTML in the viewer; privacy
84
- of mirroring (the stream is the page content — implications and redaction hooks).
85
-
86
- ## 7. Future work
87
-
88
- Stylesheet-centric capture; on-demand subtree fetch; multi-viewer fan-out; CRDT-free
89
- multi-tab; integration as the standard observability layer for computer-use agents.
90
-
91
- ---
92
-
93
- ## TODO toward a draft
94
-
95
- - [ ] Build the evaluation harness (`examples/` + a bench runner)
96
- - [ ] Pick and freeze the site corpus
97
- - [ ] Implement the stylesheet-centric capture variant (needed for the ablation)
98
- - [ ] Pull watchdog/telemetry numbers from FSB if available
99
- - [ ] Related-work deep dive: rrweb internals, Surfly patents, CDP screencast docs
100
- - [ ] Decide venue + format (sets page budget)
30
+ - Add a public HAR record/replay corpus.
31
+ - Add a real WebRTC baseline with documented encoder and capture settings.
32
+ - Expand related work on co-browsing systems and agent-observability viewers.
33
+ - Turn the deterministic local benchmark into a CI performance-regression gate.
@@ -37,11 +37,20 @@ var viewer = createViewer({
37
37
  }
38
38
  });
39
39
 
40
- viewer.on('state', function (state) {
41
- document.getElementById('lifecycle').textContent = state.lifecycle;
40
+ function sumCounts(map) {
41
+ var total = 0;
42
+ map = map || {};
43
+ Object.keys(map).forEach(function (key) {
44
+ total += map[key] || 0;
45
+ });
46
+ return total;
47
+ }
48
+
49
+ viewer.on('state', function (event) {
50
+ document.getElementById('lifecycle').textContent = event.state;
42
51
  });
43
52
  viewer.on('health', function (health) {
44
- document.getElementById('health').textContent = String(health.framesReceived || 0) + ' frames';
53
+ document.getElementById('health').textContent = String(sumCounts(health.receivedByType)) + ' frames';
45
54
  });
46
55
  </script>
47
56
  </body>
@@ -37,11 +37,18 @@ var viewer = createViewer({
37
37
  }
38
38
  });
39
39
 
40
- viewer.on('state', function (state) {
41
- document.getElementById('lifecycle').textContent = state.lifecycle;
40
+ function sumCounts(map) {
41
+ var total = 0;
42
+ map = map || {};
43
+ Object.keys(map).forEach(function (key) { total += map[key] || 0; });
44
+ return total;
45
+ }
46
+
47
+ viewer.on('state', function (event) {
48
+ document.getElementById('lifecycle').textContent = event.state;
42
49
  });
43
50
  viewer.on('health', function (health) {
44
- document.getElementById('health').textContent = String(health.framesReceived || 0) + ' frames';
51
+ document.getElementById('health').textContent = String(sumCounts(health.receivedByType)) + ' frames';
45
52
  });
46
53
  </script>
47
54
  </body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@full-self-browsing/phantom-stream",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "DOM-native live browser mirroring: snapshot + MutationObserver diff streaming with stable node identity, compressed transport, and bidirectional remote control.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -56,6 +56,16 @@
56
56
  "import": "./src/renderer/index.js",
57
57
  "default": "./src/renderer/index.js"
58
58
  },
59
+ "./recorder": {
60
+ "types": "./dist/types/recorder/index.d.ts",
61
+ "import": "./src/recorder/index.js",
62
+ "default": "./src/recorder/index.js"
63
+ },
64
+ "./player": {
65
+ "types": "./dist/types/player/index.d.ts",
66
+ "import": "./src/player/index.js",
67
+ "default": "./src/player/index.js"
68
+ },
59
69
  "./relay": {
60
70
  "types": "./dist/types/relay/index.d.ts",
61
71
  "import": "./src/relay/index.js",
@@ -75,6 +85,9 @@
75
85
  "package:pack": "npm run types && npm pack --dry-run",
76
86
  "package:smoke": "npm run types && node scripts/package-smoke.mjs",
77
87
  "package:check": "npm test && npm run types && npm run lint:package && npm run attw && npm run package:pack && npm run package:smoke",
88
+ "bench:local": "node scripts/bench-local.mjs",
89
+ "paper:pdf": "cd paper && tectonic main.tex",
90
+ "paper:check": "node scripts/paper-check.mjs && npm run paper:pdf",
78
91
  "demo": "node bin/phantom-stream.js demo",
79
92
  "demo:playwright": "node bin/phantom-stream.js playwright-demo",
80
93
  "example:loopback": "node examples/serve.js"
@@ -97,10 +110,21 @@
97
110
  "devDependencies": {
98
111
  "@arethetypeswrong/cli": "^0.18.3",
99
112
  "jsdom": "^29.1.1",
113
+ "pixelmatch": "^7.2.0",
100
114
  "playwright": "^1.60.0",
115
+ "pngjs": "^7.0.0",
101
116
  "publint": "^0.3.21",
117
+ "rrweb": "^2.0.1",
102
118
  "typescript": "^6.0.3"
103
119
  },
120
+ "peerDependencies": {
121
+ "hls.js": ">=1.5.0"
122
+ },
123
+ "peerDependenciesMeta": {
124
+ "hls.js": {
125
+ "optional": true
126
+ }
127
+ },
104
128
  "dependencies": {
105
129
  "ws": "8.21.0"
106
130
  }