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

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 (46) hide show
  1. package/dist/types/adapters/extension.d.ts.map +1 -1
  2. package/dist/types/adapters/playwright.d.ts.map +1 -1
  3. package/dist/types/capture/index.d.ts +112 -0
  4. package/dist/types/capture/index.d.ts.map +1 -1
  5. package/dist/types/protocol/constants.d.ts +22 -0
  6. package/dist/types/protocol/constants.d.ts.map +1 -1
  7. package/dist/types/protocol/index.d.ts +1 -0
  8. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  9. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  10. package/dist/types/protocol/messages.d.ts +266 -2
  11. package/dist/types/protocol/messages.d.ts.map +1 -1
  12. package/dist/types/renderer/asset-policy.d.ts +72 -0
  13. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  14. package/dist/types/renderer/diff.d.ts.map +1 -1
  15. package/dist/types/renderer/index.d.ts +13 -0
  16. package/dist/types/renderer/index.d.ts.map +1 -1
  17. package/dist/types/renderer/media-player.d.ts +114 -0
  18. package/dist/types/renderer/media-player.d.ts.map +1 -0
  19. package/dist/types/renderer/overlays.d.ts +12 -0
  20. package/dist/types/renderer/overlays.d.ts.map +1 -1
  21. package/dist/types/renderer/sanitize.d.ts +22 -0
  22. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  23. package/dist/types/renderer/snapshot.d.ts +38 -0
  24. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  25. package/dist/types/transport/websocket.d.ts.map +1 -1
  26. package/docs/ARCHITECTURE.md +13 -4
  27. package/docs/SECURITY.md +233 -2
  28. package/examples/bookmarklet-demo/viewer.html +12 -3
  29. package/examples/extension-mv3/viewer.html +10 -3
  30. package/package.json +9 -1
  31. package/src/adapters/extension.js +202 -7
  32. package/src/adapters/playwright-inject.js +50 -0
  33. package/src/adapters/playwright.js +159 -0
  34. package/src/capture/index.js +1071 -11
  35. package/src/protocol/constants.js +24 -0
  36. package/src/protocol/index.js +1 -0
  37. package/src/protocol/media-reconcile.js +188 -0
  38. package/src/protocol/messages.js +145 -2
  39. package/src/renderer/asset-policy.js +172 -0
  40. package/src/renderer/diff.js +106 -2
  41. package/src/renderer/index.js +849 -9
  42. package/src/renderer/media-player.js +367 -0
  43. package/src/renderer/overlays.js +324 -0
  44. package/src/renderer/sanitize.js +25 -3
  45. package/src/renderer/snapshot.js +534 -3
  46. package/src/transport/websocket.js +36 -0
@@ -44,10 +44,12 @@ import {
44
44
  SNAPSHOT_BUDGET_BYTES,
45
45
  TRUNCATION_VIEWPORT_MULTIPLIER,
46
46
  SCROLL_THROTTLE_MS,
47
+ MEDIA_SYNC_THROTTLE_MS,
47
48
  OVERLAY_THROTTLE_MS,
48
49
  MUTATION_STALE_THRESHOLD_MS,
49
50
  WATCHDOG_TICK_MS,
50
51
  INLINE_STYLE_MAX_BYTES,
52
+ ASSET_DATA_URI_MAX_BYTES,
51
53
  } from '../protocol/constants.js';
52
54
  import { STREAM, CONTROL, DIFF_OP, createStreamSessionId } from '../protocol/messages.js';
53
55
 
@@ -186,6 +188,88 @@ function hasDangerousScheme(value) {
186
188
  || compact.indexOf('data:text/html') === 0;
187
189
  }
188
190
 
191
+ /**
192
+ * Count UTF-8 bytes of a string (module-scope twin of the createCapture-inner
193
+ * utf8ByteLength; both exist because classifyAssetRef is a pure module-level
194
+ * export and the inner degrade hooks reuse it). Surrogate pairs count as 4
195
+ * bytes; lone surrogates as 3.
196
+ * @param {string} text
197
+ * @returns {number}
198
+ */
199
+ function assetUtf8ByteLength(text) {
200
+ var str = String(text == null ? '' : text);
201
+ var bytes = 0;
202
+ for (var i = 0; i < str.length; i++) {
203
+ var code = str.charCodeAt(i);
204
+ if (code < 0x80) {
205
+ bytes += 1;
206
+ } else if (code < 0x800) {
207
+ bytes += 2;
208
+ } else if (code >= 0xD800 && code <= 0xDBFF && i + 1 < str.length) {
209
+ var next = str.charCodeAt(i + 1);
210
+ if (next >= 0xDC00 && next <= 0xDFFF) {
211
+ bytes += 4;
212
+ i++;
213
+ } else {
214
+ bytes += 3;
215
+ }
216
+ } else {
217
+ bytes += 3;
218
+ }
219
+ }
220
+ return bytes;
221
+ }
222
+
223
+ /**
224
+ * Classify an asset URL by FETCHABILITY (Phase 12 ASST-04). This is a control
225
+ * distinct from hasDangerousScheme (injection): a URL can be injection-safe yet
226
+ * non-shareable as a mirrored reference. Two non-shareable classes degrade to a
227
+ * dimensioned placeholder at capture so a dead/blob reference never reaches the
228
+ * wire and one giant inline image cannot blow the per-message cap:
229
+ * - `blob:`/origin-local object URLs (always non-shareable -- they are
230
+ * origin-local and dead at the cross-origin viewer);
231
+ * - `data:` URIs whose UTF-8 byte length exceeds `capBytes`.
232
+ * Everything else (http/https, small inline `data:`, relative URLs that
233
+ * absolutify) is shareable and passes through untouched -- benign small `data:`
234
+ * icons stay byte-identical (Pitfall 5: no over-degrade).
235
+ * @param {string} url the (resolved or raw) asset reference
236
+ * @param {number} capBytes byte cap for inline `data:` (ASSET_DATA_URI_MAX_BYTES)
237
+ * @returns {{ok: true}|{ok: false, reason: 'blob'|'oversized-data'}}
238
+ */
239
+ export function classifyAssetRef(url, capBytes) {
240
+ if (!url || typeof url !== 'string') return { ok: true };
241
+ // Match the whitespace-obfuscation discipline of hasDangerousScheme: a
242
+ // "blo\tb:" or " data:" form normalizes at parse time, so strip <= 0x20
243
+ // before scheme-matching.
244
+ var compact = stripLowChars(url).toLowerCase();
245
+ if (compact.indexOf('blob:') === 0) {
246
+ return { ok: false, reason: 'blob' };
247
+ }
248
+ if (compact.indexOf('data:') === 0) {
249
+ var cap = capBytes || 0;
250
+ if (assetUtf8ByteLength(url) > cap) {
251
+ return { ok: false, reason: 'oversized-data' };
252
+ }
253
+ }
254
+ return { ok: true };
255
+ }
256
+
257
+ /**
258
+ * Pure predicate (Phase 12 ASST-03): true only when a resolved `currentSrc`
259
+ * is present AND differs from the resolved plain `src`, i.e. a responsive
260
+ * `srcset`/`<picture>` actually negotiated a non-default variant worth pinning.
261
+ * Empty `currentSrc` (jsdom returns "") never enriches; an equal value never
262
+ * enriches (plain `<img src>` stays byte-identical on the wire).
263
+ * @param {string} resolvedCurrentSrc absolutified currentSrc
264
+ * @param {string} resolvedSrc absolutified src
265
+ * @returns {boolean}
266
+ */
267
+ export function currentSrcDiffers(resolvedCurrentSrc, resolvedSrc) {
268
+ if (!resolvedCurrentSrc || typeof resolvedCurrentSrc !== 'string') return false;
269
+ if (resolvedCurrentSrc === '') return false;
270
+ return resolvedCurrentSrc !== (resolvedSrc || '');
271
+ }
272
+
189
273
  /**
190
274
  * Minimal srcset candidate parser for the URL+descriptor forms this project
191
275
  * emits. Unlike split(','), it keeps commas inside data:image URLs attached
@@ -424,6 +508,31 @@ function defaultMaskText(text) {
424
508
  * @property {(text: string, element: Element) => string} [maskInputFn]
425
509
  * Optional (SEC-03). Custom input-value mask (rrweb signature). Same
426
510
  * fail-closed containment as maskTextFn.
511
+ * @property {string} [maskMediaSelector]
512
+ * Optional (MSEC-03). CSS selector: matching <video>/<audio>/asset elements
513
+ * omit their URL from the wire and degrade to the dimension-only block
514
+ * placeholder (the blockSelector placeholder path), AND emit NO STREAM.MEDIA
515
+ * state (the media-tracker skip predicates also gate on this selector). The
516
+ * privacy control for "mirror nothing about this media -- not its URL, not
517
+ * its playback timeline." Invalid selectors THROW Error('invalid-mask-
518
+ * selector') at factory time, exactly like blockSelector/maskTextSelector.
519
+ * @property {boolean} [maskAssetUrls]
520
+ * Optional (MSEC-03), default false. When true, strip a documented token/PII
521
+ * query-param denylist (AWS SigV4/SigV2, GCP signed-URL, Azure SAS, and a
522
+ * generic token/secret/auth set -- case-insensitive, exact-name OR denied
523
+ * prefix) from asset/media URLs before the wire. Functional params (w, h, q,
524
+ * format, v, id, t, ...) survive. A URL with no denylisted param is emitted
525
+ * BYTE-IDENTICAL (the original string, never URL.toString() normalization),
526
+ * so off-by-default keeps the wire byte-identical (the differential oracle is
527
+ * unaffected). See TOKEN_PARAM_DENYLIST + docs/SECURITY.md for the exact list.
528
+ * @property {(url: string, ctx: {attr: string, tag: string, nid: string, kind: ('image'|'media')}) => (string|null)} [maskAssetUrlFn]
529
+ * Optional (MSEC-03). Custom asset/media URL redactor; takes precedence over
530
+ * maskAssetUrls. A returned string replaces the URL on the wire; null BLOCKS
531
+ * the URL (the attribute is removed -> the viewer never fetches it); a THROW
532
+ * FAILS CLOSED -> block (logged, treated as null -- never raised, never the
533
+ * raw URL). Stricter than maskTextFn: a thrown text mask falls back to the
534
+ * asterisk default, but a thrown URL redactor blocks (a half-redacted URL
535
+ * that the viewer then fetches is worse than no URL).
427
536
  */
428
537
 
429
538
  /**
@@ -488,6 +597,16 @@ export function createCapture(config) {
488
597
  var maskInputFn = (typeof cfg.maskInputFn === 'function') ? cfg.maskInputFn : null;
489
598
  var blockSelector = compileMaskSelector(cfg.blockSelector);
490
599
  var maskTextSelector = compileMaskSelector(cfg.maskTextSelector);
600
+ // MSEC-03 asset/media URL masking (plan 15-01). Same off-by-default + one-
601
+ // allowed-throw-site discipline as the SEC-03 family above: maskMediaSelector
602
+ // is compiled (validated) here so an invalid selector fails closed and LOUD;
603
+ // maskAssetUrls/maskAssetUrlFn default OFF so the wire stays byte-identical
604
+ // (the differential oracle is unaffected). maskAssetUrlFn fails closed at
605
+ // RUNTIME to BLOCK (see maskAssetUrlForWire), the safeMaskText precedent
606
+ // adapted for URLs (a half-redacted URL the viewer fetches is worse than none).
607
+ var maskMediaSelector = compileMaskSelector(cfg.maskMediaSelector);
608
+ var maskAssetUrls = cfg.maskAssetUrls === true;
609
+ var maskAssetUrlFn = (typeof cfg.maskAssetUrlFn === 'function') ? cfg.maskAssetUrlFn : null;
491
610
 
492
611
  /**
493
612
  * Ancestor-inclusive form of the skipElement seam (reference parity:
@@ -605,6 +724,14 @@ export function createCapture(config) {
605
724
  var valueCaptureActive = false;
606
725
  var valueListenerRoots = new WeakSet();
607
726
  var valueListenerRecords = [];
727
+ // Media tracker bookkeeping (STREAM.MEDIA). Mirrors the value-tracker's
728
+ // root-set/records pair (above): media events do NOT bubble, so listeners
729
+ // are PER-ELEMENT and must be explicitly torn down. mediaTracked maps a live
730
+ // <video>/<audio> to its bound listener handlers + per-element lastMediaSend
731
+ // throttle stamp; mediaTrackedRecords is the iteration order for teardown.
732
+ var mediaTrackingActive = false;
733
+ var mediaTracked = new Map();
734
+ var mediaTrackedRecords = [];
608
735
  var nativeAttachShadow = null;
609
736
  var attachShadowProto = null;
610
737
  var pendingStyleSourceChanges = new Map();
@@ -626,7 +753,8 @@ export function createCapture(config) {
626
753
  blockedSubtrees: 0, // object/embed subtrees dropped + srcdoc attrs dropped
627
754
  cssScrubs: 0, // CSS values rewritten by scrubCssText
628
755
  maskedTextNodes: 0, // (plan 03-03) maskTextSelector-matched text masked
629
- maskedInputs: 0 // (plan 03-03) masked input values
756
+ maskedInputs: 0, // (plan 03-03) masked input values
757
+ maskedAssetUrls: 0 // (plan 15-01) asset/media URLs stripped/redacted/blocked
630
758
  };
631
759
 
632
760
  function beginStreamSession() {
@@ -645,6 +773,7 @@ export function createCapture(config) {
645
773
  sanitizeCounters.cssScrubs = 0;
646
774
  sanitizeCounters.maskedTextNodes = 0;
647
775
  sanitizeCounters.maskedInputs = 0;
776
+ sanitizeCounters.maskedAssetUrls = 0;
648
777
  pendingStyleSourceChanges.clear();
649
778
  styleSourceRegistry.clear();
650
779
  styleScopeRoots.clear();
@@ -1442,6 +1571,7 @@ export function createCapture(config) {
1442
1571
  var cloneDescendants = bodyClone.querySelectorAll('*');
1443
1572
  var toRemove = [];
1444
1573
  var blockedPairs = [];
1574
+ var assetUnavailablePairs = [];
1445
1575
 
1446
1576
  for (var i = 0; i < liveDescendants.length; i++) {
1447
1577
  var live = liveDescendants[i];
@@ -1484,6 +1614,21 @@ export function createCapture(config) {
1484
1614
  }
1485
1615
  var srcsetVal = clone.getAttribute('srcset');
1486
1616
  if (srcsetVal) clone.setAttribute('srcset', absolutifySrcset(srcsetVal, frameDoc));
1617
+
1618
+ // ASST-04 degrade + ASST-03 currentSrc pin (same treatment as the main
1619
+ // snapshot pair walk), clone-only -- the live frame node is never touched.
1620
+ var frameDegradeReason = assetDegradeReason(clone);
1621
+ if (frameDegradeReason) {
1622
+ assetUnavailablePairs.push({ orig: live, clone: clone, reason: frameDegradeReason });
1623
+ } else if (tag === 'img') {
1624
+ var frameResolvedCurrent = absolutifyUrl(live.currentSrc || '', frameDoc);
1625
+ var frameResolvedSrc = clone.getAttribute('src') || '';
1626
+ if (currentSrcDiffers(frameResolvedCurrent, frameResolvedSrc)
1627
+ && !hasDangerousScheme(frameResolvedCurrent)) {
1628
+ clone.setAttribute('data-ps-currentsrc', frameResolvedCurrent);
1629
+ }
1630
+ }
1631
+
1487
1632
  if (styleMode !== 'cssom') captureComputedStyles(live, clone);
1488
1633
  sanitizeForWire('element', { orig: live, clone: clone });
1489
1634
  }
@@ -1499,6 +1644,15 @@ export function createCapture(config) {
1499
1644
  cloneToNid
1500
1645
  );
1501
1646
  }
1647
+ for (var aub = 0; aub < assetUnavailablePairs.length; aub++) {
1648
+ replaceWithAssetUnavailablePlaceholder(
1649
+ assetUnavailablePairs[aub].orig,
1650
+ assetUnavailablePairs[aub].clone,
1651
+ readBlockRect(assetUnavailablePairs[aub].orig),
1652
+ assetUnavailablePairs[aub].reason,
1653
+ cloneToNid
1654
+ );
1655
+ }
1502
1656
  }
1503
1657
 
1504
1658
  function serializeFrameDocument(iframe, frameNid, frameDoc) {
@@ -1712,6 +1866,39 @@ export function createCapture(config) {
1712
1866
  return values;
1713
1867
  }
1714
1868
 
1869
+ // Positional identity for the selected options. selectedValues carry the
1870
+ // masked option text, so colliding masks (default mask turns 'aa' and 'bb'
1871
+ // both into '**') make value-based selection ambiguous on the renderer.
1872
+ // Option indexes contain no page content, survive masking unchanged, and
1873
+ // pin the exact option(s) the renderer must select.
1874
+ function selectedOptionIndexes(select) {
1875
+ var indexes = [];
1876
+ var options = select && select.options ? select.options : [];
1877
+ for (var i = 0; i < options.length; i++) {
1878
+ if (options[i].selected) indexes.push(i);
1879
+ }
1880
+ return indexes;
1881
+ }
1882
+
1883
+ // Positional selectedIndexes only line up with the mirror when EVERY option
1884
+ // survives the wire. If skipElement/blockSelector drops an <option> (or an
1885
+ // <optgroup>), the mirror's options list is shorter, so live-collection
1886
+ // indexes would address the wrong option. Detect that and fall back to value
1887
+ // matching instead.
1888
+ function selectHasFilteredOptions(select) {
1889
+ var nodes = select && select.querySelectorAll
1890
+ ? select.querySelectorAll('option, optgroup')
1891
+ : [];
1892
+ for (var i = 0; i < nodes.length; i++) {
1893
+ if (skipElementWithAncestors(nodes[i])
1894
+ || blockedWithAncestors(nodes[i])
1895
+ || wireDroppedWithAncestors(nodes[i])) {
1896
+ return true;
1897
+ }
1898
+ }
1899
+ return false;
1900
+ }
1901
+
1715
1902
  function sanitizeInputValue(value, owner) {
1716
1903
  return sanitizeForWire('input', {
1717
1904
  value: value == null ? '' : String(value),
@@ -1748,6 +1935,15 @@ export function createCapture(config) {
1748
1935
  for (var s = 0; s < selected.length; s++) {
1749
1936
  diff.selectedValues.push(sanitizeInputValue(selected[s], control));
1750
1937
  }
1938
+ // Authoritative selection identity (the renderer prefers this over the
1939
+ // maskable selectedValues): option indexes never carry page content and
1940
+ // stay unambiguous even when masked option values collide. Only emit when
1941
+ // every option survives the wire -- if an option is filtered out, the
1942
+ // live indexes would mis-address the shorter mirror options list, so fall
1943
+ // back to value matching there.
1944
+ if (!selectHasFilteredOptions(control)) {
1945
+ diff.selectedIndexes = selectedOptionIndexes(control);
1946
+ }
1751
1947
  return diff;
1752
1948
  }
1753
1949
 
@@ -2087,6 +2283,49 @@ export function createCapture(config) {
2087
2283
  }
2088
2284
  }
2089
2285
 
2286
+ /**
2287
+ * True when the element itself matches maskMediaSelector (MSEC-03). The
2288
+ * blockMatches twin keyed off maskMediaSelector: used by the snapshot/subtree
2289
+ * placeholder path so a masked media/asset element degrades to the
2290
+ * dimension-only block placeholder. Runtime selector errors are contained
2291
+ * (logged, treated as not-matched) so capture never wedges after factory-time
2292
+ * validation. Returns false immediately when maskMediaSelector is null, so the
2293
+ * no-config path is wire-identical (no closest() walk).
2294
+ * @param {Element} el
2295
+ * @returns {boolean}
2296
+ */
2297
+ function maskMediaMatches(el) {
2298
+ if (!maskMediaSelector) return false;
2299
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2300
+ try {
2301
+ return !!(el.matches && el.matches(maskMediaSelector));
2302
+ } catch (err) {
2303
+ logger.error('[DOM Stream] maskMediaSelector match failed', err);
2304
+ return false;
2305
+ }
2306
+ }
2307
+
2308
+ /**
2309
+ * Ancestor-inclusive maskMediaSelector predicate (MSEC-03), the
2310
+ * blockedWithAncestors twin. ORed into the media-tracker skip guards
2311
+ * (collectTrackedMediaElements + attachMediaListeners) so a masked
2312
+ * <video>/<audio> -- or media inside a masked subtree -- emits NO STREAM.MEDIA
2313
+ * baseline entry and NO STREAM.MEDIA events. Returns false immediately when
2314
+ * maskMediaSelector is null (no-config path wire-identical, no walk).
2315
+ * @param {Element} el
2316
+ * @returns {boolean}
2317
+ */
2318
+ function maskMediaWithAncestors(el) {
2319
+ if (!maskMediaSelector) return false;
2320
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2321
+ try {
2322
+ return !!(el.closest && el.closest(maskMediaSelector));
2323
+ } catch (err) {
2324
+ logger.error('[DOM Stream] maskMediaSelector match failed', err);
2325
+ return false;
2326
+ }
2327
+ }
2328
+
2090
2329
  /**
2091
2330
  * Elements intentionally absent from the wire must also be absent from the
2092
2331
  * live tracking graph. Otherwise descendants can receive nids before the
@@ -2325,6 +2564,98 @@ export function createCapture(config) {
2325
2564
  return placeholder;
2326
2565
  }
2327
2566
 
2567
+ /**
2568
+ * Build the placeholder for a non-shareable asset (ASST-04). Mirrors
2569
+ * createBlockPlaceholder (dimension-only <div>, identity in the nodeIds
2570
+ * sidecar) plus a machine-readable reason attribute so the renderer/viewer
2571
+ * can show a neutral, dimensioned gap instead of a broken/dead reference.
2572
+ * @param {Document} doc
2573
+ * @param {{width: number, height: number}} rect
2574
+ * @param {'blob'|'oversized-data'} reason
2575
+ * @returns {Element}
2576
+ */
2577
+ function createAssetUnavailablePlaceholder(doc, rect, reason) {
2578
+ var placeholder = doc.createElement('div');
2579
+ placeholder.setAttribute('rr_width', String(rect.width || 0) + 'px');
2580
+ placeholder.setAttribute('rr_height', String(rect.height || 0) + 'px');
2581
+ placeholder.setAttribute('data-ps-asset-unavailable', reason);
2582
+ return placeholder;
2583
+ }
2584
+
2585
+ /**
2586
+ * Replace a detached clone element with its asset-unavailable placeholder,
2587
+ * transferring the nid in cloneToNid exactly like replaceWithBlockPlaceholder.
2588
+ * The LIVE element is never touched (clone-only; Phase 7 no-mutation
2589
+ * invariant -- Pitfall 4).
2590
+ * @param {Element} liveEl
2591
+ * @param {Element} cloneEl
2592
+ * @param {{width: number, height: number}} rect
2593
+ * @param {'blob'|'oversized-data'} reason
2594
+ * @param {Map<Element, string>} [cloneToNid]
2595
+ * @returns {Element|null}
2596
+ */
2597
+ function replaceWithAssetUnavailablePlaceholder(liveEl, cloneEl, rect, reason, cloneToNid) {
2598
+ if (!cloneEl || !cloneEl.parentNode) return null;
2599
+ var nid = cloneToNid && cloneToNid.get(cloneEl);
2600
+ if (!nid) nid = getTrackedNodeId(liveEl) || '';
2601
+ var placeholder = createAssetUnavailablePlaceholder(cloneEl.ownerDocument, rect, reason);
2602
+ cloneEl.parentNode.replaceChild(placeholder, cloneEl);
2603
+ if (cloneToNid) {
2604
+ cloneToNid.delete(cloneEl);
2605
+ if (nid) cloneToNid.set(placeholder, nid);
2606
+ }
2607
+ sanitizeCounters.blockedSubtrees++;
2608
+ return placeholder;
2609
+ }
2610
+
2611
+ /**
2612
+ * Decide whether a clone's URL-bearing attributes make it a non-shareable
2613
+ * asset that must degrade to a placeholder (ASST-04). Inspects the wire
2614
+ * clone's already-absolutified `src`/`poster`/`srcset` and returns the
2615
+ * degrade reason, or '' when the asset is shareable. Pure read of the clone;
2616
+ * never mutates anything.
2617
+ * @param {Element} cloneEl the detached wire clone (post-absolutify)
2618
+ * @returns {'blob'|'oversized-data'|''}
2619
+ */
2620
+ function assetDegradeReason(cloneEl) {
2621
+ if (!cloneEl || !cloneEl.getAttribute) return '';
2622
+ // Scalar src/poster: classify the value directly.
2623
+ var scalarAttrs = ['src', 'poster'];
2624
+ for (var s = 0; s < scalarAttrs.length; s++) {
2625
+ var v = cloneEl.getAttribute(scalarAttrs[s]);
2626
+ if (v) {
2627
+ var c = classifyAssetRef(v, ASSET_DATA_URI_MAX_BYTES);
2628
+ if (!c.ok) return c.reason;
2629
+ }
2630
+ }
2631
+ // srcset: classify each candidate; a single non-shareable candidate
2632
+ // degrades the element (the whole responsive set is unusable as a
2633
+ // reference when one variant is blob:/oversized-data).
2634
+ var srcset = cloneEl.getAttribute('srcset');
2635
+ if (srcset) {
2636
+ var reason = assetDegradeReasonForSrcset(srcset);
2637
+ if (reason) return reason;
2638
+ }
2639
+ return '';
2640
+ }
2641
+
2642
+ /**
2643
+ * Classify a raw srcset string by fetchability: returns the degrade reason of
2644
+ * the first non-shareable candidate, or '' when every candidate is shareable.
2645
+ * Used by the mutation attr branch (which has the raw value, not a clone).
2646
+ * @param {string} srcset
2647
+ * @returns {'blob'|'oversized-data'|''}
2648
+ */
2649
+ function assetDegradeReasonForSrcset(srcset) {
2650
+ if (!srcset) return '';
2651
+ var candidates = parseSrcsetCandidates(srcset);
2652
+ for (var k = 0; k < candidates.length; k++) {
2653
+ var rc = classifyAssetRef(candidates[k].url, ASSET_DATA_URI_MAX_BYTES);
2654
+ if (!rc.ok) return rc.reason;
2655
+ }
2656
+ return '';
2657
+ }
2658
+
2328
2659
  function createTruncatedPlaceholder(doc) {
2329
2660
  var placeholder = doc.createElement('div');
2330
2661
  placeholder.setAttribute('data-phantomstream-truncated', 'true');
@@ -2510,6 +2841,20 @@ export function createCapture(config) {
2510
2841
  bodyAttrs: Object.assign({}, payload && payload.bodyAttrs ? payload.bodyAttrs : {})
2511
2842
  });
2512
2843
 
2844
+ // CSSOM mode carries full stylesheet text in styleSources; copy the array
2845
+ // so the budget passes below can prune it without mutating the caller's
2846
+ // sources. Only present in cssom mode -- computed mode omits the field.
2847
+ if (Array.isArray(next.styleSources)) {
2848
+ next.styleSources = next.styleSources.slice();
2849
+ }
2850
+
2851
+ // media[] (MEDIA-02) addresses nodes by nid; truncation can drop those nodes
2852
+ // from the clone. Copy the array so the prune below never mutates the
2853
+ // caller's baseline. Only present when the page had <video>/<audio>.
2854
+ if (Array.isArray(next.media)) {
2855
+ next.media = next.media.slice();
2856
+ }
2857
+
2513
2858
  while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
2514
2859
  next.inlineStyles.pop();
2515
2860
  markSnapshotPayloadTruncated(next);
@@ -2518,6 +2863,12 @@ export function createCapture(config) {
2518
2863
  next.stylesheets.pop();
2519
2864
  markSnapshotPayloadTruncated(next);
2520
2865
  }
2866
+ // A single large CSSOM source can dominate the payload; shed sources before
2867
+ // dropping DOM structure so an oversized stylesheet cannot blow the cap.
2868
+ while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Array.isArray(next.styleSources) && next.styleSources.length) {
2869
+ next.styleSources.pop();
2870
+ markSnapshotPayloadTruncated(next);
2871
+ }
2521
2872
 
2522
2873
  if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
2523
2874
  next.htmlStyle = '';
@@ -2553,6 +2904,12 @@ export function createCapture(config) {
2553
2904
  next.nodeIds = buildNodeIdSidecar(clone, cloneToNid, false);
2554
2905
  next.shadowRoots = collectShadowRootPayloads(document.body, next.nodeIds, truncatedNodeIds);
2555
2906
  next.frames = collectFramePayloads(document.body, cloneToNid, truncatedNodeIds);
2907
+ // WR-02: a dropped <video>/<audio> subtree leaves a media[] baseline
2908
+ // entry that addresses a nid no longer in nodeIds. Re-derive media[]
2909
+ // against the freshly rebuilt sidecar so the baseline can never
2910
+ // reference a truncated node (and dead entries stop counting toward
2911
+ // the cap).
2912
+ pruneMediaToNodeIds(next);
2556
2913
  next.missingDescendants = (next.missingDescendants || 0) + 1;
2557
2914
  markSnapshotPayloadTruncated(next);
2558
2915
  }
@@ -2566,12 +2923,19 @@ export function createCapture(config) {
2566
2923
  next.frames = [];
2567
2924
  next.inlineStyles = [];
2568
2925
  next.stylesheets = [];
2926
+ if (Array.isArray(next.styleSources)) next.styleSources = [];
2569
2927
  next.htmlAttrs = {};
2570
2928
  next.bodyAttrs = {};
2571
2929
  next.htmlStyle = '';
2572
2930
  next.bodyStyle = '';
2573
2931
  next.title = '';
2574
2932
  next.url = '';
2933
+ // WR-02: the hard reset empties every nid-addressed field; media[] must go
2934
+ // with them or an emptied snapshot would still ship a baseline that
2935
+ // addresses nodes nodeIds (now []) no longer contains. pruneMediaToNodeIds
2936
+ // filters against the now-empty sidecar, so media[] becomes [] (or stays
2937
+ // absent when the page had no media).
2938
+ pruneMediaToNodeIds(next);
2575
2939
  next.missingDescendants = (next.missingDescendants || 0) + 1;
2576
2940
  markSnapshotPayloadTruncated(next);
2577
2941
  }
@@ -2579,6 +2943,179 @@ export function createCapture(config) {
2579
2943
  return next;
2580
2944
  }
2581
2945
 
2946
+ /**
2947
+ * Prune a budget-fitted snapshot payload's media[] baseline to entries whose
2948
+ * nid is still present in the payload's nodeIds sidecar (WR-02). Truncation
2949
+ * (clone-subtree drop or the over-cap hard reset) re-derives nodeIds but the
2950
+ * media[] array is independent, so without this an entry can address a node
2951
+ * the snapshot no longer carries. No-op when media[] is absent (the common
2952
+ * media-free page -- the field stays unset, preserving wire byte-identity).
2953
+ * Compares String(nid) because ensureNodeId stamps string nids and nodeIds
2954
+ * holds those same strings (renderer applyMediaBaseline also keys on String).
2955
+ * @param {Object} payload The mutable budget-fitted payload (next).
2956
+ */
2957
+ function pruneMediaToNodeIds(payload) {
2958
+ if (!payload || !Array.isArray(payload.media)) return;
2959
+ var ids = Array.isArray(payload.nodeIds) ? payload.nodeIds : [];
2960
+ var live = new Set();
2961
+ for (var i = 0; i < ids.length; i++) live.add(String(ids[i]));
2962
+ payload.media = payload.media.filter(function (m) {
2963
+ return m && live.has(String(m.nid));
2964
+ });
2965
+ }
2966
+
2967
+ // =========================================================================
2968
+ // 0.45 MSEC-03 asset/media URL masking (plan 15-01)
2969
+ // =========================================================================
2970
+
2971
+ // Token/PII query-param denylist (documented in docs/SECURITY.md §4). When
2972
+ // maskAssetUrls is on, these param NAMES are stripped from asset/media URLs
2973
+ // before the wire -- credential/signature/expiry params only; functional
2974
+ // params (w, h, q, format, v, id, t, ...) survive. Matching is CASE-
2975
+ // INSENSITIVE and exact-name OR denied-prefix (TOKEN_PARAM_PREFIXES). The set
2976
+ // is lowercased so isTokenParamName can do a single lowercased membership
2977
+ // test. Provider param names are CITED from each signing scheme (AWS SigV4/
2978
+ // SigV2, GCP signed-URL V4, Azure SAS); the generic set is a reasoned default.
2979
+ var TOKEN_PARAM_DENYLIST = {
2980
+ // AWS S3 / CloudFront presigned (SigV4) -- the x-amz- prefix subsumes these
2981
+ // but they are kept explicit for documentation/audit clarity.
2982
+ 'x-amz-signature': 1, 'x-amz-credential': 1, 'x-amz-security-token': 1,
2983
+ 'x-amz-algorithm': 1, 'x-amz-date': 1, 'x-amz-expires': 1, 'x-amz-signedheaders': 1,
2984
+ // AWS S3 / CloudFront presigned (SigV2 / canned policy)
2985
+ 'awsaccesskeyid': 1, 'key-pair-id': 1, 'policy': 1,
2986
+ // Google Cloud Storage signed URL (V4) -- x-goog- prefix subsumes these.
2987
+ 'x-goog-signature': 1, 'x-goog-credential': 1, 'x-goog-algorithm': 1,
2988
+ 'x-goog-date': 1, 'x-goog-expires': 1, 'x-goog-signedheaders': 1, 'googleaccessid': 1,
2989
+ // Azure Blob SAS
2990
+ 'sig': 1, 'se': 1, 'sp': 1, 'sv': 1, 'sr': 1, 'st': 1, 'skoid': 1, 'sktid': 1,
2991
+ 'skt': 1, 'ske': 1, 'sks': 1, 'skv': 1, 'spr': 1, 'sip': 1, 'ss': 1, 'srt': 1,
2992
+ // Generic token/secret/auth/expiry
2993
+ 'token': 1, 'access_token': 1, 'auth': 1, 'authorization': 1, 'apikey': 1,
2994
+ 'api_key': 1, 'key': 1, 'signature': 1, 'sign': 1, 'hash': 1, 'hmac': 1,
2995
+ 'jwt': 1, 'password': 1, 'passwd': 1, 'pwd': 1, 'secret': 1, 'session': 1,
2996
+ 'sessionid': 1, 'sid': 1, 'expires': 1, 'expiry': 1
2997
+ };
2998
+ // Denied-name prefixes: any param whose lowercased name starts with one of
2999
+ // these is a token param (the AWS/GCP signed-URL families add provider-
3000
+ // specific x-amz-*/x-goog-* params beyond the explicit names above).
3001
+ var TOKEN_PARAM_PREFIXES = ['x-amz-', 'x-goog-'];
3002
+
3003
+ /**
3004
+ * True when a query-param name is a token/PII param to strip: lowercased
3005
+ * exact-set membership OR starts-with a denied prefix. Case-insensitive.
3006
+ * @param {string} name
3007
+ * @returns {boolean}
3008
+ */
3009
+ function isTokenParamName(name) {
3010
+ if (!name || typeof name !== 'string') return false;
3011
+ var lower = name.toLowerCase();
3012
+ if (TOKEN_PARAM_DENYLIST[lower] === 1) return true;
3013
+ for (var i = 0; i < TOKEN_PARAM_PREFIXES.length; i++) {
3014
+ if (lower.indexOf(TOKEN_PARAM_PREFIXES[i]) === 0) return true;
3015
+ }
3016
+ return false;
3017
+ }
3018
+
3019
+ /**
3020
+ * True when a URL fragment (the part after '#') carries a denied token param
3021
+ * (review WR-04). OAuth implicit flow returns tokens in the fragment
3022
+ * (#access_token=...); the fragment is never sent in the asset GET, but the
3023
+ * URL STRING crosses the relay to a possibly-cross-origin viewer, so a token
3024
+ * there is still a disclosure. We parse the fragment as a URLSearchParams and
3025
+ * report whether any name is denylisted. Empty / token-free fragments report
3026
+ * false so the no-strip byte-identity path is preserved (a plain `#section-2`
3027
+ * anchor never triggers a rewrite).
3028
+ * @param {string} hash - u.hash, including the leading '#' (or '')
3029
+ * @returns {boolean}
3030
+ */
3031
+ function fragmentHasTokenParam(hash) {
3032
+ if (!hash || hash.length < 2) return false; // '' or bare '#' -> no token
3033
+ var body = hash.charAt(0) === '#' ? hash.slice(1) : hash;
3034
+ if (body.indexOf('=') === -1) return false; // plain anchor, not key=value
3035
+ var fragParams;
3036
+ try { fragParams = new URLSearchParams(body); }
3037
+ catch (e) { return false; } // unparseable -> not a token map
3038
+ var found = false;
3039
+ fragParams.forEach(function (_v, k) { if (isTokenParamName(k)) found = true; });
3040
+ return found;
3041
+ }
3042
+
3043
+ /**
3044
+ * Strip the TOKEN_PARAM_DENYLIST params from a URL (the maskAssetUrls path).
3045
+ * PURE: parses with new URL() in try/catch (a non-absolute/opaque URL --
3046
+ * data:/blob:/relative -- throws and is returned UNCHANGED). Returns the
3047
+ * original `url` string when nothing was stripped (Pitfall 1: new URL()
3048
+ * .toString() normalizes host case / default port / trailing slash / percent-
3049
+ * encoding, which would diverge the wire even with masking effectively off for
3050
+ * this URL). Only emits u.toString() when a query param was deleted OR a
3051
+ * token-bearing fragment was dropped.
3052
+ *
3053
+ * Fragment handling (review WR-04): a token in the fragment
3054
+ * (#access_token=...) is not part of u.search, so the query strip never sees
3055
+ * it, yet the full URL string -- fragment included -- crosses the relay to a
3056
+ * possibly-cross-origin viewer. When the fragment carries a denylisted param
3057
+ * name we drop the WHOLE fragment (it is never needed for an asset/media
3058
+ * fetch); a benign anchor fragment (no '=', or no denied name) is left intact
3059
+ * so byte-identity holds on the no-strip path.
3060
+ * @param {string} url
3061
+ * @returns {string}
3062
+ */
3063
+ function stripTokenParams(url) {
3064
+ var u;
3065
+ try { u = new URL(url); }
3066
+ catch (e) { return url; } // non-absolute / opaque -> leave as-is
3067
+ var dropFragment = fragmentHasTokenParam(u.hash);
3068
+ // No query AND no token fragment -> unchanged (byte-identity). A token-only
3069
+ // fragment URL has no u.search, so the old `if (!u.search) return url` fast
3070
+ // path would have leaked it; gate the early return on the fragment too.
3071
+ if (!u.search && !dropFragment) return url;
3072
+ var changed = dropFragment;
3073
+ // Snapshot the keys first: URLSearchParams is live, deleting while iterating
3074
+ // skips entries. URLSearchParams preserves order and repeated keys.
3075
+ var keys = [];
3076
+ u.searchParams.forEach(function (_v, k) { keys.push(k); });
3077
+ for (var i = 0; i < keys.length; i++) {
3078
+ if (isTokenParamName(keys[i])) { u.searchParams.delete(keys[i]); changed = true; }
3079
+ }
3080
+ if (dropFragment) u.hash = ''; // redact the token-bearing fragment
3081
+ return changed ? u.toString() : url; // original string identity when untouched
3082
+ }
3083
+
3084
+ /**
3085
+ * PURE asset/media URL masking helper (MSEC-03). Decides the wire value for a
3086
+ * single URL attribute value: a custom redactor (maskAssetUrlFn) first, then
3087
+ * the boolean token-param strip (maskAssetUrls), else the URL UNCHANGED
3088
+ * (off-by-default -> byte-identical wire). NEVER reads the DOM or mutates a
3089
+ * clone -- the caller owns the clone mutation / placeholder swap.
3090
+ *
3091
+ * Fail-closed direction (Pitfall 3): maskAssetUrlFn mirrors safeMaskText's
3092
+ * try/catch but the catch returns null (BLOCK), not the asterisk default --
3093
+ * a thrown URL redactor is an undecided-unsafe URL, which must NOT be fetched.
3094
+ * @param {string} url
3095
+ * @param {{attr: string, tag: string, nid: string, kind: ('image'|'media')}} [ctx]
3096
+ * @returns {string|null} replacement URL, the unchanged URL, or null (block)
3097
+ */
3098
+ function maskAssetUrlForWire(url, ctx) {
3099
+ if (!url || typeof url !== 'string') return url;
3100
+ // 1. Custom redactor first -- full host control, FAIL CLOSED on throw.
3101
+ if (maskAssetUrlFn) {
3102
+ try {
3103
+ var out = maskAssetUrlFn(url, ctx || {});
3104
+ if (out === null) return null; // explicit block -> placeholder/remove
3105
+ return String(out); // redacted replacement
3106
+ } catch (err) {
3107
+ logger.error('[DOM Stream] maskAssetUrlFn failed; URL blocked (fail-closed)', err);
3108
+ return null; // THROW -> block (never raise, never pass raw)
3109
+ }
3110
+ }
3111
+ // 2. Boolean token/PII strip.
3112
+ if (maskAssetUrls) {
3113
+ return stripTokenParams(url);
3114
+ }
3115
+ // 3. Default OFF -> unchanged (byte-identical wire).
3116
+ return url;
3117
+ }
3118
+
2582
3119
  // =========================================================================
2583
3120
  // 0.5 SEC-01 Sanitization chokepoint
2584
3121
  // =========================================================================
@@ -2595,7 +3132,8 @@ export function createCapture(config) {
2595
3132
  blockedSubtrees: sanitizeCounters.blockedSubtrees,
2596
3133
  cssScrubs: sanitizeCounters.cssScrubs,
2597
3134
  maskedTextNodes: sanitizeCounters.maskedTextNodes,
2598
- maskedInputs: sanitizeCounters.maskedInputs
3135
+ maskedInputs: sanitizeCounters.maskedInputs,
3136
+ maskedAssetUrls: sanitizeCounters.maskedAssetUrls
2599
3137
  };
2600
3138
  }
2601
3139
 
@@ -2737,6 +3275,32 @@ export function createCapture(config) {
2737
3275
  sanitizeCounters.blockedUrlSchemes++;
2738
3276
  }
2739
3277
  }
3278
+ // MSEC-03 asset/media URL masking (plan 15-01): route each SURVIVING
3279
+ // URL-attr value through the dedicated 'asset-url'/'media-url' dispatch
3280
+ // AFTER the scheme scrub (a hostile scheme is already gone, so it never
3281
+ // reaches maskAssetUrlForWire). Gated on the masking config so the
3282
+ // off-by-default path is wire-identical (no per-attr work, no string
3283
+ // churn). A null result BLOCKS -> remove the attribute (the viewer never
3284
+ // fetches it); a changed value replaces it. The live element is never
3285
+ // touched (clone-only, Phase 7 invariant).
3286
+ if (maskAssetUrls || maskAssetUrlFn) {
3287
+ var elNid = getTrackedNodeId(payload.orig) || '';
3288
+ for (var um = 0; um < URL_ATTRS.length; um++) {
3289
+ var maskAttr = URL_ATTRS[um];
3290
+ var maskVal = clone.getAttribute(maskAttr);
3291
+ if (!maskVal) continue;
3292
+ var maskKind = assetUrlKindForTag(tag);
3293
+ var maskRes = sanitizeForWire(maskKind === 'media' ? 'media-url' : 'asset-url', {
3294
+ value: maskVal,
3295
+ ctx: { attr: maskAttr, tag: tag, nid: elNid, kind: maskKind }
3296
+ });
3297
+ if (maskRes.value === null) {
3298
+ clone.removeAttribute(maskAttr);
3299
+ } else if (maskRes.value !== maskVal) {
3300
+ clone.setAttribute(maskAttr, maskRes.value);
3301
+ }
3302
+ }
3303
+ }
2740
3304
  var formactionVal = clone.getAttribute('formaction');
2741
3305
  if (formactionVal && hasDangerousScheme(formactionVal)) {
2742
3306
  clone.removeAttribute('formaction');
@@ -2828,7 +3392,10 @@ export function createCapture(config) {
2828
3392
  if (!root.contains(desc)) continue;
2829
3393
  if (liveDesc && wireDroppedWithAncestors(liveDesc.parentElement)) continue;
2830
3394
  if (liveDesc && blockedWithAncestors(liveDesc.parentElement)) continue;
2831
- if (liveDesc && blockMatches(liveDesc)) {
3395
+ if (liveDesc && maskMediaWithAncestors(liveDesc.parentElement)) continue;
3396
+ // blockSelector OR maskMediaSelector (MSEC-03): degrade the matched
3397
+ // element to the same dimension-only block placeholder.
3398
+ if (liveDesc && (blockMatches(liveDesc) || maskMediaMatches(liveDesc))) {
2832
3399
  replaceWithBlockPlaceholder(liveDesc, desc, readBlockRect(liveDesc), payload.cloneToNid);
2833
3400
  continue;
2834
3401
  }
@@ -2879,6 +3446,25 @@ export function createCapture(config) {
2879
3446
  sanitizeCounters.blockedUrlSchemes++;
2880
3447
  return { value: null };
2881
3448
  }
3449
+ // MSEC-03 asset/media URL masking (plan 15-01): the mutation 'attr' path's
3450
+ // URL values flow through the SAME dedicated dispatch after the scheme
3451
+ // scrub above. A null result becomes the inert ATTR-op shape ({ value:
3452
+ // null } -> diff.js removeAttribute), matching the dangerous-scheme branch.
3453
+ // Gated on config so off-by-default attr ops are byte-identical.
3454
+ if ((maskAssetUrls || maskAssetUrlFn)
3455
+ && URL_ATTRS.indexOf(attrName) !== -1 && payload.value) {
3456
+ var attrTag = (payload.target && payload.target.tagName)
3457
+ ? String(payload.target.tagName).toLowerCase() : '';
3458
+ var attrMaskKind = assetUrlKindForTag(attrTag);
3459
+ var attrMaskRes = sanitizeForWire(attrMaskKind === 'media' ? 'media-url' : 'asset-url', {
3460
+ value: payload.value,
3461
+ ctx: {
3462
+ attr: attrName, tag: attrTag,
3463
+ nid: getTrackedNodeId(payload.target) || '', kind: attrMaskKind
3464
+ }
3465
+ });
3466
+ return { value: attrMaskRes.value };
3467
+ }
2882
3468
  if (attrName === 'value' && (shouldMaskInput(payload.target) || isOptionUnderMaskedSelect(payload.target))) {
2883
3469
  var maskedAttrValue = safeMaskInput(payload.value == null ? '' : payload.value, payload.target);
2884
3470
  if (maskedAttrValue !== payload.value) {
@@ -2933,9 +3519,40 @@ export function createCapture(config) {
2933
3519
  return { css: scrubbedCss };
2934
3520
  }
2935
3521
 
3522
+ // MSEC-03 asset/media URL masking (plan 15-01). The single dedicated seam
3523
+ // for redacting/stripping/blocking a URL attribute value -- a thin wrapper
3524
+ // around the PURE maskAssetUrlForWire helper so URL masking lives in ONE
3525
+ // testable place rather than overloading the 'attr' path. 'asset-url' and
3526
+ // 'media-url' share one branch (the behavior is identical); the asset-vs-
3527
+ // media distinction travels in payload.ctx.kind ('image'|'media'). The
3528
+ // 'element' and 'attr' paths route their surviving URL-attr values through
3529
+ // this branch AFTER the hasDangerousScheme scrub (a hostile scheme is gone
3530
+ // before masking runs). Returns the same { value } discriminated shape as
3531
+ // 'attr'; value === null signals block -> the caller removes the attribute /
3532
+ // emits a placeholder.
3533
+ if (kind === 'asset-url' || kind === 'media-url') {
3534
+ var maskedUrl = maskAssetUrlForWire(payload.value, payload.ctx);
3535
+ if (maskedUrl !== payload.value) {
3536
+ sanitizeCounters.maskedAssetUrls++;
3537
+ }
3538
+ return { value: maskedUrl };
3539
+ }
3540
+
2936
3541
  return {};
2937
3542
  }
2938
3543
 
3544
+ /**
3545
+ * Map a tag name to the maskAssetUrlFn ctx.kind ('media' for the media
3546
+ * elements that carry a fetchable URL, 'image' for everything else -- <img>,
3547
+ * SVG <image>, <link>, <a>, ...). Used to build the ctx for the 'asset-url'/
3548
+ * 'media-url' dispatch so a host redactor can branch on asset-vs-media.
3549
+ * @param {string} tag lowercased tag name
3550
+ * @returns {('image'|'media')}
3551
+ */
3552
+ function assetUrlKindForTag(tag) {
3553
+ return (tag === 'video' || tag === 'audio' || tag === 'source') ? 'media' : 'image';
3554
+ }
3555
+
2939
3556
  // =========================================================================
2940
3557
  // 1. DOM Serializer
2941
3558
  // =========================================================================
@@ -3108,6 +3725,11 @@ export function createCapture(config) {
3108
3725
  // Elements to remove from clone (scripts, noscript, host-flagged elements)
3109
3726
  var toRemove = [];
3110
3727
  var blockedPairs = [];
3728
+ // ASST-04: clones whose absolutified asset refs are non-shareable
3729
+ // (blob:/oversized-data:). Collected during the walk, their live rects
3730
+ // read together below (single-pass layout discipline), then swapped for a
3731
+ // dimensioned placeholder after the walk -- exactly like blockedPairs.
3732
+ var assetUnavailablePairs = [];
3111
3733
 
3112
3734
  for (var i = 0; i < pairs.length; i++) {
3113
3735
  var orig = pairs[i].orig;
@@ -3149,14 +3771,19 @@ export function createCapture(config) {
3149
3771
  continue;
3150
3772
  }
3151
3773
 
3152
- // blockSelector: descendants of a blocked root get no nid assignment
3153
- // (the root swap discards the whole cloned subtree). The blocked root
3154
- // itself is still tracked, then replaced after this walk by a
3155
- // dimension-preserving placeholder whose identity travels in nodeIds.
3156
- if (blockedWithAncestors(orig.parentElement)) {
3774
+ // blockSelector / maskMediaSelector: descendants of a blocked OR masked
3775
+ // root get no nid assignment (the root swap discards the whole cloned
3776
+ // subtree). The root itself is still tracked, then replaced after this
3777
+ // walk by a dimension-preserving placeholder whose identity travels in
3778
+ // nodeIds. maskMediaSelector (MSEC-03) reuses the blockSelector placeholder
3779
+ // path verbatim so a masked <video>/<audio> degrades to the same identity-
3780
+ // only dimensioned <div> (A3: no distinct reason attr -- "masked" and
3781
+ // "blocked" are visually identical and the masked element legitimately
3782
+ // carries no identity-leaking attribute).
3783
+ if (blockedWithAncestors(orig.parentElement) || maskMediaWithAncestors(orig.parentElement)) {
3157
3784
  continue;
3158
3785
  }
3159
- if (blockMatches(orig)) {
3786
+ if (blockMatches(orig) || maskMediaMatches(orig)) {
3160
3787
  assignNodeId(orig, cl, cloneToNid);
3161
3788
  blockedPairs.push({ orig: orig, clone: cl });
3162
3789
  continue;
@@ -3213,6 +3840,29 @@ export function createCapture(config) {
3213
3840
  cl.setAttribute('srcset', absolutifySrcset(srcsetVal));
3214
3841
  }
3215
3842
 
3843
+ // ASST-04: detect non-shareable asset refs (blob:/oversized-data:) on the
3844
+ // already-absolutified clone. If the element degrades, record it for the
3845
+ // post-walk placeholder swap and skip the currentSrc enrich (the clone is
3846
+ // about to be replaced wholesale). The live element is never touched.
3847
+ var degradeReason = assetDegradeReason(cl);
3848
+ if (degradeReason) {
3849
+ assetUnavailablePairs.push({ orig: orig, clone: cl, reason: degradeReason });
3850
+ } else if (tag === 'img') {
3851
+ // ASST-03: clone-only data-ps-currentsrc variant pin. Enrich ONLY when
3852
+ // the live element's currentSrc is present AND differs from the
3853
+ // resolved src (a responsive srcset/<picture> negotiated a non-default
3854
+ // variant). currentSrc is set on the CLONE, never the live page
3855
+ // (Pitfall 4: preserves the Phase 7 no-mutation invariant). jsdom
3856
+ // returns currentSrc === "" so this never fires under unit/oracle tests
3857
+ // unless the scenario injects a divergent currentSrc.
3858
+ var resolvedCurrent = absolutifyUrl(orig.currentSrc || '');
3859
+ var resolvedSrc = cl.getAttribute('src') || '';
3860
+ if (currentSrcDiffers(resolvedCurrent, resolvedSrc)
3861
+ && !hasDangerousScheme(resolvedCurrent)) {
3862
+ cl.setAttribute('data-ps-currentsrc', resolvedCurrent);
3863
+ }
3864
+ }
3865
+
3216
3866
  // Capture generated computed styles only in the default compatibility mode.
3217
3867
  if (styleMode !== 'cssom') captureComputedStyles(orig, cl);
3218
3868
 
@@ -3231,6 +3881,12 @@ export function createCapture(config) {
3231
3881
  for (var bp = 0; bp < blockedPairs.length; bp++) {
3232
3882
  blockedRects.push(readBlockRect(blockedPairs[bp].orig));
3233
3883
  }
3884
+ // ASST-04: read non-shareable asset rects in the same single-pass region
3885
+ // (dimensions from the ORIG live element, never the detached clone).
3886
+ var assetUnavailableRects = [];
3887
+ for (var ap = 0; ap < assetUnavailablePairs.length; ap++) {
3888
+ assetUnavailableRects.push(readBlockRect(assetUnavailablePairs[ap].orig));
3889
+ }
3234
3890
 
3235
3891
  // Remove marked elements
3236
3892
  for (var r = 0; r < toRemove.length; r++) {
@@ -3242,6 +3898,17 @@ export function createCapture(config) {
3242
3898
  for (var br = 0; br < blockedPairs.length; br++) {
3243
3899
  replaceWithBlockPlaceholder(blockedPairs[br].orig, blockedPairs[br].clone, blockedRects[br], cloneToNid);
3244
3900
  }
3901
+ // ASST-04: swap each non-shareable asset clone for its dimensioned
3902
+ // placeholder, transferring the nid (clone-only; live page untouched).
3903
+ for (var aur = 0; aur < assetUnavailablePairs.length; aur++) {
3904
+ replaceWithAssetUnavailablePlaceholder(
3905
+ assetUnavailablePairs[aur].orig,
3906
+ assetUnavailablePairs[aur].clone,
3907
+ assetUnavailableRects[aur],
3908
+ assetUnavailablePairs[aur].reason,
3909
+ cloneToNid
3910
+ );
3911
+ }
3245
3912
 
3246
3913
  // Collect stylesheet URLs from document.head
3247
3914
  var stylesheets = collectStylesheetsFrom(document);
@@ -3409,7 +4076,31 @@ export function createCapture(config) {
3409
4076
  snapshotPayload.styleSources = documentCssom.sources;
3410
4077
  snapshotPayload.styleStrategy = documentCssom.strategy;
3411
4078
  }
3412
- return fitSnapshotPayloadForBudget(snapshotPayload, clone, cloneToNid, truncatedNodeIds);
4079
+ // MEDIA-02 / MEDIA-04: append a media[] playback-state baseline keyed by
4080
+ // nid -- one entry per tracked <video>/<audio> in document order, read from
4081
+ // the LIVE DOM. This mirrors the DIFF_OP.VALUE side-channel precedent
4082
+ // (live property state travels keyed by nid, never baked into the clone),
4083
+ // so payload.html stays byte-identical (differential-oracle invariant) and
4084
+ // the live page is never mutated (Phase 7 capture-no-mutation invariant).
4085
+ // The media[] key is added ONLY when at least one <video>/<audio> exists.
4086
+ // A media-free page emits NO media key at all, so existing fixtures stay
4087
+ // byte-identical to the FSB reference and the differential oracle needs no
4088
+ // new ledger entry yet (RESEARCH A4 / Pitfall 7 -- the ledger entry + media
4089
+ // fixture land with Plan 13-04, once a fixture instantiates media).
4090
+ var trackedMedia = collectTrackedMediaElements();
4091
+ if (trackedMedia.length > 0) {
4092
+ snapshotPayload.media = trackedMedia.map(buildMediaBaselineEntry);
4093
+ }
4094
+ var fitted = fitSnapshotPayloadForBudget(snapshotPayload, clone, cloneToNid, truncatedNodeIds);
4095
+ // WR-02: media[] is read from the LIVE DOM, so it carries an entry for a
4096
+ // <video>/<audio> even when its clone subtree was dropped by ANY truncation
4097
+ // pass -- the serializeDOM below-fold/over-cap pre-pass (above), the sidecar
4098
+ // prune, the budget loop, or the over-cap hard reset. Reconcile media[]
4099
+ // against the FINAL nodeIds here (the single point every pass funnels
4100
+ // through) so the emitted baseline can never address a node nodeIds no
4101
+ // longer contains. No-op for a media-free page (media stays absent).
4102
+ pruneMediaToNodeIds(fitted);
4103
+ return fitted;
3413
4104
  }
3414
4105
 
3415
4106
  // =========================================================================
@@ -3504,6 +4195,50 @@ export function createCapture(config) {
3504
4195
  appendStyleDeclaration(cloneDescendants[c], descStyleText);
3505
4196
  }
3506
4197
  }
4198
+
4199
+ // ASST-03/04 on the added-node path. CRITICAL (Pitfall 4): the live node
4200
+ // was mutated above for URL absolutify (reference parity), but the
4201
+ // currentSrc enrich and the asset-unavailable degrade land on the
4202
+ // wireClone ONLY -- never the live node, so the framework attributes never
4203
+ // leak to the observed page. Descendants first (parent-replacement is safe
4204
+ // on the detached clone), then the root.
4205
+ for (var ce = 0; ce < liveDescendants.length; ce++) {
4206
+ var liveDesc2 = liveDescendants[ce];
4207
+ var cloneDesc2 = cloneDescendants[ce];
4208
+ if (!cloneDesc2) continue;
4209
+ var descReason = assetDegradeReason(cloneDesc2);
4210
+ if (descReason) {
4211
+ replaceWithAssetUnavailablePlaceholder(
4212
+ liveDesc2, cloneDesc2, readBlockRect(liveDesc2), descReason, cloneToNid
4213
+ );
4214
+ } else if (cloneDesc2.tagName && String(cloneDesc2.tagName).toLowerCase() === 'img') {
4215
+ var descCurrent = absolutifyUrl(liveDesc2.currentSrc || '', liveDesc2.ownerDocument || baseDoc);
4216
+ var descSrc = cloneDesc2.getAttribute('src') || '';
4217
+ if (currentSrcDiffers(descCurrent, descSrc) && !hasDangerousScheme(descCurrent)) {
4218
+ cloneDesc2.setAttribute('data-ps-currentsrc', descCurrent);
4219
+ }
4220
+ }
4221
+ }
4222
+ // Root: the detached wireClone has no parent, so a degrade swaps the
4223
+ // reference held by `wireClone` (preserving rootNid in cloneToNid) rather
4224
+ // than calling replaceWithAssetUnavailablePlaceholder.
4225
+ var rootReason = assetDegradeReason(wireClone);
4226
+ if (rootReason) {
4227
+ var rootPlaceholder = createAssetUnavailablePlaceholder(
4228
+ wireClone.ownerDocument || document, readBlockRect(el), rootReason
4229
+ );
4230
+ cloneToNid.delete(wireClone);
4231
+ if (rootNid) cloneToNid.set(rootPlaceholder, rootNid);
4232
+ sanitizeCounters.blockedSubtrees++;
4233
+ wireClone = rootPlaceholder;
4234
+ } else if (rootTag === 'img') {
4235
+ var rootCurrent = absolutifyUrl(el.currentSrc || '', baseDoc);
4236
+ var rootSrc = wireClone.getAttribute('src') || '';
4237
+ if (currentSrcDiffers(rootCurrent, rootSrc) && !hasDangerousScheme(rootCurrent)) {
4238
+ wireClone.setAttribute('data-ps-currentsrc', rootCurrent);
4239
+ }
4240
+ }
4241
+
3507
4242
  prepareIframeWireShellsForClone(el, wireClone);
3508
4243
  var subtreeResult = sanitizeForWire('subtree', {
3509
4244
  root: wireClone,
@@ -3711,6 +4446,10 @@ export function createCapture(config) {
3711
4446
  frames: addedPayload.frames || []
3712
4447
  }, frameRecord);
3713
4448
  diffs.push(boundMutationDiffForBudget(addDiff));
4449
+ // STREAM.MEDIA: a mutation-added <video>/<audio> (or a subtree
4450
+ // containing one) must receive listeners -- media events do not
4451
+ // bubble, so they are not caught by any delegated handler.
4452
+ attachMediaListenersUnder(added);
3714
4453
  } else if (added.nodeType === Node.TEXT_NODE || added.nodeType === Node.CDATA_SECTION_NODE) {
3715
4454
  sawBareTextNode = true;
3716
4455
  }
@@ -3720,6 +4459,10 @@ export function createCapture(config) {
3720
4459
  for (var r = 0; r < m.removedNodes.length; r++) {
3721
4460
  var removed = m.removedNodes[r];
3722
4461
  if (removed.nodeType === Node.ELEMENT_NODE) {
4462
+ // STREAM.MEDIA: release listeners for a removed <video>/<audio>
4463
+ // subtree before any wire-drop short-circuit, so a tracked media
4464
+ // element can never emit after it leaves the live DOM.
4465
+ detachMediaListenersUnder(removed);
3723
4466
  if (wireDroppedWithAncestors(removed)) continue;
3724
4467
  var nid = getTrackedNodeId(removed);
3725
4468
  if (!nid) continue; // Not tracked
@@ -3793,6 +4536,28 @@ export function createCapture(config) {
3793
4536
  attrVal = absolutifySrcset(attrVal, m.target.ownerDocument);
3794
4537
  }
3795
4538
 
4539
+ // ASST-04: a mutation that sets src/poster/srcset to a non-shareable
4540
+ // ref (blob:/oversized-data:) must NOT ship the dead reference. Drop
4541
+ // the offending URL from the wire (empty value) and emit a sibling
4542
+ // data-ps-asset-unavailable op so the viewer shows the dimensioned
4543
+ // placeholder instead of fetching a dead ref. The live element is
4544
+ // unchanged (we only shape the wire diff).
4545
+ var attrIsAssetUrl = (attrNameLower === 'src' || attrNameLower === 'poster' || attrNameLower === 'srcset');
4546
+ if (attrIsAssetUrl && attrVal) {
4547
+ var mutClass = (attrNameLower === 'srcset')
4548
+ ? assetDegradeReasonForSrcset(attrVal)
4549
+ : (function () { var c = classifyAssetRef(attrVal, ASSET_DATA_URI_MAX_BYTES); return c.ok ? '' : c.reason; })();
4550
+ if (mutClass) {
4551
+ diffs.push(scopeFrameDiff({
4552
+ op: 'attr',
4553
+ nid: targetNid,
4554
+ attr: 'data-ps-asset-unavailable',
4555
+ val: mutClass
4556
+ }, frameRecord));
4557
+ attrVal = '';
4558
+ }
4559
+ }
4560
+
3796
4561
  // SEC-01: route through the chokepoint AFTER absolutification so
3797
4562
  // the scheme check runs on final wire values (Pitfall 5: this
3798
4563
  // branch was the snapshot sanitizer's bypass).
@@ -4187,6 +4952,231 @@ export function createCapture(config) {
4187
4952
  logger.info('[DOM Stream] Scroll tracker stopped');
4188
4953
  }
4189
4954
 
4955
+ // =========================================================================
4956
+ // 3.5 Media Tracker (STREAM.MEDIA -- scroll-twin side channel)
4957
+ // =========================================================================
4958
+
4959
+ /**
4960
+ * Every <video>/<audio> currently in the live document, in document order.
4961
+ * Read from the LIVE DOM only (never the clone) so the media[] baseline and
4962
+ * tracker walk the same real elements capture sees.
4963
+ * @returns {HTMLMediaElement[]}
4964
+ */
4965
+ function collectTrackedMediaElements() {
4966
+ var out = [];
4967
+ if (!document || typeof document.querySelectorAll !== 'function') return out;
4968
+ var nodes = document.querySelectorAll('video, audio');
4969
+ for (var i = 0; i < nodes.length; i++) {
4970
+ // WR-01: a <video>/<audio> the host excludes (skipElement / a blocked or
4971
+ // wire-dropped ancestor -- e.g. the host's own viewer UI in a same-page
4972
+ // loopback mirror) must NOT be media-tracked. The value tracker already
4973
+ // gates on these predicates (buildValueDiff); the media baseline now
4974
+ // matches so a deliberately-excluded element emits no media[] entry.
4975
+ if (skipElementWithAncestors(nodes[i])
4976
+ || blockedWithAncestors(nodes[i])
4977
+ || wireDroppedWithAncestors(nodes[i])
4978
+ || maskMediaWithAncestors(nodes[i])) {
4979
+ continue;
4980
+ }
4981
+ out.push(nodes[i]);
4982
+ }
4983
+ return out;
4984
+ }
4985
+
4986
+ /**
4987
+ * Build one MediaBaselineEntry (MEDIA-02/MEDIA-04) from a LIVE media element.
4988
+ * Reads playback-state properties only; assigns/reuses the element nid via
4989
+ * ensureNodeId so the renderer can address it. NEVER writes an attribute on
4990
+ * the element (Phase 7 no-mutation invariant) and NEVER touches the clone.
4991
+ *
4992
+ * duration|live are mutually exclusive: a finite duration is sent as-is; a
4993
+ * non-finite duration (live stream / unloaded element) sets live:true and
4994
+ * omits duration, closing the JSON Infinity->null trap (13-RESEARCH Pitfall
4995
+ * 2) so the reconciler branches on live before any duration arithmetic.
4996
+ * @param {HTMLMediaElement} el
4997
+ * @returns {import('../protocol/messages.js').MediaBaselineEntry}
4998
+ */
4999
+ function buildMediaBaselineEntry(el) {
5000
+ var entry = {
5001
+ nid: ensureNodeId(el),
5002
+ currentTime: el.currentTime,
5003
+ paused: !!el.paused,
5004
+ muted: !!el.muted,
5005
+ volume: el.volume,
5006
+ playbackRate: el.playbackRate,
5007
+ loop: !!el.loop,
5008
+ ended: !!el.ended
5009
+ };
5010
+ if (isFinite(el.duration)) entry.duration = el.duration;
5011
+ else entry.live = true;
5012
+ return entry;
5013
+ }
5014
+
5015
+ /**
5016
+ * Build a MediaSyncPayload from a LIVE media element and emit it on the wire
5017
+ * (MWIRE-01). The payload is the baseline entry enriched with the triggering
5018
+ * event name, a capture-side sentAt latency stamp, and the stream identity
5019
+ * stamps so the renderer's isCurrentStream guard rejects stale cross-
5020
+ * generation frames. nid reuses the tracked id (or assigns one). No media
5021
+ * BYTES are ever sent -- only nid-addressed playback state (T-13-05).
5022
+ * @param {HTMLMediaElement} el
5023
+ * @param {string} eventName
5024
+ */
5025
+ function sendMediaState(el, eventName) {
5026
+ var payload = {
5027
+ nid: getTrackedNodeId(el) || ensureNodeId(el),
5028
+ event: eventName,
5029
+ currentTime: el.currentTime,
5030
+ paused: !!el.paused,
5031
+ muted: !!el.muted,
5032
+ volume: el.volume,
5033
+ playbackRate: el.playbackRate,
5034
+ loop: !!el.loop,
5035
+ ended: !!el.ended,
5036
+ sentAt: Date.now(),
5037
+ streamSessionId: streamSessionId || '',
5038
+ snapshotId: currentSnapshotId || 0
5039
+ };
5040
+ if (isFinite(el.duration)) payload.duration = el.duration;
5041
+ else payload.live = true;
5042
+ safeSend(STREAM.MEDIA, payload);
5043
+ }
5044
+
5045
+ /**
5046
+ * Attach per-element media listeners to one <video>/<audio>. Discrete
5047
+ * transition events flush a STREAM.MEDIA immediately; timeupdate is the
5048
+ * throttled drift heartbeat -- it returns early while paused (heartbeat is
5049
+ * playing-only) then applies a per-element MEDIA_SYNC_THROTTLE_MS gate
5050
+ * (mirrors the scroll tracker's now-lastSend timestamp check), bounding the
5051
+ * 1 MiB-capped relay against timeupdate flooding (T-13-06). Idempotent:
5052
+ * re-attaching a tracked element is a no-op (added-node + startMediaTracker
5053
+ * can both reach the same element).
5054
+ * @param {Element} el
5055
+ */
5056
+ function attachMediaListeners(el) {
5057
+ if (!mediaTrackingActive || !el || el.nodeType !== Node.ELEMENT_NODE) return;
5058
+ if (typeof el.addEventListener !== 'function') return;
5059
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
5060
+ if (tag !== 'video' && tag !== 'audio') return;
5061
+ // WR-01 / MSEC-03: never track a host-excluded OR masked media element. This
5062
+ // is the chokepoint every attach path funnels through (startMediaTracker, the
5063
+ // added-node path, attachMediaListenersUnder), so gating here guarantees a
5064
+ // skipped/blocked/wire-dropped/masked <video>/<audio> emits no STREAM.MEDIA
5065
+ // frames -- matching the value tracker's exclusion (buildValueDiff) so the
5066
+ // wire never leaks the play/pause/seek timeline of deliberately-excluded
5067
+ // host-UI media or maskMediaSelector-redacted private media.
5068
+ if (skipElementWithAncestors(el) || blockedWithAncestors(el)
5069
+ || wireDroppedWithAncestors(el) || maskMediaWithAncestors(el)) return;
5070
+ if (mediaTracked.has(el)) return;
5071
+
5072
+ var record = { lastMediaSend: 0, handlers: {} };
5073
+
5074
+ // Discrete transition events: emit immediately (coalesced by the browser's
5075
+ // own one-event-per-transition delivery).
5076
+ var discrete = ['play', 'pause', 'seeked', 'ratechange', 'ended', 'volumechange', 'loadedmetadata'];
5077
+ for (var i = 0; i < discrete.length; i++) {
5078
+ (function (name) {
5079
+ var handler = function () {
5080
+ if (!mediaTrackingActive) return;
5081
+ sendMediaState(el, name);
5082
+ };
5083
+ record.handlers[name] = handler;
5084
+ el.addEventListener(name, handler);
5085
+ })(discrete[i]);
5086
+ }
5087
+
5088
+ // timeupdate: throttled drift heartbeat, only while playing.
5089
+ var timeupdateHandler = function () {
5090
+ if (!mediaTrackingActive) return;
5091
+ if (el.paused) return; // heartbeat is playing-only
5092
+ var now = Date.now();
5093
+ if (now - record.lastMediaSend < MEDIA_SYNC_THROTTLE_MS) return;
5094
+ record.lastMediaSend = now;
5095
+ sendMediaState(el, 'timeupdate');
5096
+ };
5097
+ record.handlers.timeupdate = timeupdateHandler;
5098
+ el.addEventListener('timeupdate', timeupdateHandler);
5099
+
5100
+ mediaTracked.set(el, record);
5101
+ mediaTrackedRecords.push(el);
5102
+ }
5103
+
5104
+ /**
5105
+ * Detach the media listeners from one element and forget it. Safe on an
5106
+ * untracked element (no-op). Called on element removal and on teardown.
5107
+ * @param {Element} el
5108
+ */
5109
+ function detachMediaListeners(el) {
5110
+ var record = mediaTracked.get(el);
5111
+ if (!record) return;
5112
+ if (typeof el.removeEventListener === 'function') {
5113
+ for (var name in record.handlers) {
5114
+ if (Object.prototype.hasOwnProperty.call(record.handlers, name)) {
5115
+ el.removeEventListener(name, record.handlers[name]);
5116
+ }
5117
+ }
5118
+ }
5119
+ mediaTracked.delete(el);
5120
+ var idx = mediaTrackedRecords.indexOf(el);
5121
+ if (idx !== -1) mediaTrackedRecords.splice(idx, 1);
5122
+ }
5123
+
5124
+ /**
5125
+ * Attach media listeners to a root (if it is a media element) and to every
5126
+ * <video>/<audio> descendant. Used by the added-node mutation path so a
5127
+ * mutation-inserted media element (or a subtree containing one) is tracked.
5128
+ * @param {Element} root
5129
+ */
5130
+ function attachMediaListenersUnder(root) {
5131
+ if (!mediaTrackingActive || !root || root.nodeType !== Node.ELEMENT_NODE) return;
5132
+ var tag = root.tagName ? String(root.tagName).toLowerCase() : '';
5133
+ if (tag === 'video' || tag === 'audio') attachMediaListeners(root);
5134
+ if (typeof root.querySelectorAll !== 'function') return;
5135
+ var nested = root.querySelectorAll('video, audio');
5136
+ for (var i = 0; i < nested.length; i++) attachMediaListeners(nested[i]);
5137
+ }
5138
+
5139
+ /**
5140
+ * Detach media listeners from a removed root and any tracked <video>/<audio>
5141
+ * descendant. Used by the removed-node mutation path so a detached subtree's
5142
+ * media listeners are released (no leak, no post-removal emissions).
5143
+ * @param {Element} root
5144
+ */
5145
+ function detachMediaListenersUnder(root) {
5146
+ if (!root || root.nodeType !== Node.ELEMENT_NODE) return;
5147
+ detachMediaListeners(root);
5148
+ if (typeof root.querySelectorAll !== 'function') return;
5149
+ var nested = root.querySelectorAll('video, audio');
5150
+ for (var i = 0; i < nested.length; i++) detachMediaListeners(nested[i]);
5151
+ }
5152
+
5153
+ /**
5154
+ * Start the media tracker: walk every current <video>/<audio> and attach
5155
+ * per-element listeners (scroll-twin lifecycle; armed in start()/resume()).
5156
+ * Idempotent -- re-arming first tears down any prior listeners so a restart
5157
+ * cannot double-bind.
5158
+ */
5159
+ function startMediaTracker() {
5160
+ stopMediaTracker();
5161
+ mediaTrackingActive = true;
5162
+ var els = collectTrackedMediaElements();
5163
+ for (var i = 0; i < els.length; i++) attachMediaListeners(els[i]);
5164
+ logger.info('[DOM Stream] Media tracker started');
5165
+ }
5166
+
5167
+ /**
5168
+ * Stop the media tracker: detach every per-element listener and clear the
5169
+ * bookkeeping (torn down in start() re-arm, stop(), and pause()).
5170
+ */
5171
+ function stopMediaTracker() {
5172
+ mediaTrackingActive = false;
5173
+ var els = mediaTrackedRecords.slice();
5174
+ for (var i = 0; i < els.length; i++) detachMediaListeners(els[i]);
5175
+ mediaTracked = new Map();
5176
+ mediaTrackedRecords = [];
5177
+ logger.info('[DOM Stream] Media tracker stopped');
5178
+ }
5179
+
4190
5180
  // =========================================================================
4191
5181
  // 4. Overlay Event Broadcaster
4192
5182
  // =========================================================================
@@ -4264,6 +5254,7 @@ export function createCapture(config) {
4264
5254
  if (streaming) {
4265
5255
  stopMutationStream();
4266
5256
  stopScrollTracker();
5257
+ stopMediaTracker();
4267
5258
  }
4268
5259
  beginStreamSession();
4269
5260
  clearNodeMirror();
@@ -4273,6 +5264,7 @@ export function createCapture(config) {
4273
5264
  startMutationStream();
4274
5265
  startValueCapture();
4275
5266
  startScrollTracker();
5267
+ startMediaTracker();
4276
5268
  streaming = true;
4277
5269
  broadcastOverlayState(true);
4278
5270
  }
@@ -4285,6 +5277,7 @@ export function createCapture(config) {
4285
5277
  logger.info('[DOM Stream] Stop requested');
4286
5278
  stopMutationStream();
4287
5279
  stopScrollTracker();
5280
+ stopMediaTracker();
4288
5281
  streaming = false;
4289
5282
  clearNodeMirror();
4290
5283
  safeFlush();
@@ -4298,6 +5291,7 @@ export function createCapture(config) {
4298
5291
  logger.info('[DOM Stream] Pause requested');
4299
5292
  stopMutationStream();
4300
5293
  stopScrollTracker();
5294
+ stopMediaTracker();
4301
5295
  // Keep streaming = true (paused state, not stopped)
4302
5296
  }
4303
5297
 
@@ -4315,6 +5309,7 @@ export function createCapture(config) {
4315
5309
  startMutationStream();
4316
5310
  startValueCapture();
4317
5311
  startScrollTracker();
5312
+ startMediaTracker();
4318
5313
  streaming = true;
4319
5314
  }
4320
5315
 
@@ -4356,6 +5351,71 @@ export function createCapture(config) {
4356
5351
  resume: resume,
4357
5352
  handleControl: handleControl,
4358
5353
  getNodeId: getNodeId,
4359
- getObservedFrameDocuments: getObservedFrameDocuments
5354
+ getObservedFrameDocuments: getObservedFrameDocuments,
5355
+ // One-shot snapshot serializer over the ambient document. Exposed for the
5356
+ // serializeSnapshot() top-level helper (capture-asset-degrade unit tests)
5357
+ // and any host that wants a single payload without arming observers.
5358
+ serializeSnapshot: serializeDOM
4360
5359
  };
4361
5360
  }
5361
+
5362
+ // Ambient globals the snapshot serializer dereferences (audited from the
5363
+ // reference source, mirrors the differential harness AMBIENT_GLOBALS). The
5364
+ // serializeSnapshot() helper swaps these from the passed document's window for
5365
+ // the duration of one serialization, then restores them unconditionally.
5366
+ var SNAPSHOT_AMBIENT_GLOBALS = [
5367
+ 'window', 'document', 'Node', 'NodeFilter', 'MutationObserver',
5368
+ 'requestAnimationFrame', 'cancelAnimationFrame', 'CustomEvent',
5369
+ 'ShadowRoot', 'location', 'getComputedStyle', 'URL'
5370
+ ];
5371
+
5372
+ /**
5373
+ * Serialize ONE snapshot of the given document and return the snapshot payload
5374
+ * (`{ html, nodeIds, ... }`). A convenience top-level entry that swaps the
5375
+ * ambient globals from `doc.defaultView` for the lifetime of one serialization
5376
+ * (mirroring the differential harness's createExtractedSide), runs a fresh
5377
+ * capture's serializer against it, and restores the globals unconditionally.
5378
+ *
5379
+ * This is the no-observer path used by the capture-asset-degrade unit tests to
5380
+ * prove the clone-only currentSrc enrichment and the blob:/oversized-data:
5381
+ * placeholder degrade WITHOUT mutating the live document.
5382
+ *
5383
+ * @param {Document} doc the document to snapshot (must have a defaultView)
5384
+ * @returns {{html: string, nodeIds: string[]}} the snapshot payload
5385
+ */
5386
+ export function serializeSnapshot(doc) {
5387
+ var win = doc && doc.defaultView;
5388
+ if (!win) throw new Error('serializeSnapshot-requires-document-with-defaultView');
5389
+
5390
+ var saved = SNAPSHOT_AMBIENT_GLOBALS.map(function (name) {
5391
+ return {
5392
+ name: name,
5393
+ had: Object.prototype.hasOwnProperty.call(globalThis, name),
5394
+ value: globalThis[name]
5395
+ };
5396
+ });
5397
+ function restore() {
5398
+ for (var i = 0; i < saved.length; i++) {
5399
+ if (saved[i].had) {
5400
+ globalThis[saved[i].name] = saved[i].value;
5401
+ } else {
5402
+ delete globalThis[saved[i].name];
5403
+ }
5404
+ }
5405
+ }
5406
+
5407
+ for (var g = 0; g < SNAPSHOT_AMBIENT_GLOBALS.length; g++) {
5408
+ var n = SNAPSHOT_AMBIENT_GLOBALS[g];
5409
+ globalThis[n] = n === 'window' ? win : win[n];
5410
+ }
5411
+
5412
+ try {
5413
+ var capture = createCapture({
5414
+ transport: { send: function () {} },
5415
+ logger: { info: function () {}, warn: function () {}, error: function () {} }
5416
+ });
5417
+ return capture.serializeSnapshot();
5418
+ } finally {
5419
+ restore();
5420
+ }
5421
+ }