@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
@@ -36,10 +36,512 @@
36
36
  // contract says number, but wire
37
37
  // values are not trusted
38
38
 
39
- import { scrubCssText } from './sanitize.js';
39
+ import { scrubCssText, parseSrcsetCandidates } from './sanitize.js';
40
40
 
41
41
  /** @typedef {import('../protocol/messages.js').SnapshotPayload} SnapshotPayload */
42
42
 
43
+ // ---- Phase 12 (MSEC-01/MSEC-02/ASST-03): string-layer snapshot asset gate ----
44
+ //
45
+ // THE critical timing rule (12-RESEARCH Pitfall 1): a real browser's HTML
46
+ // parser begins fetching <img src> DURING srcdoc parse, before the iframe's
47
+ // post-parse `load` scrub can run. So for the SNAPSHOT, the authoritative
48
+ // fetch gate must run at the STRING/payload layer -- before buildSnapshotHtml
49
+ // assembles the srcdoc -- so a blocked origin never reaches the parser and
50
+ // the viewer's browser never issues the GET. The post-parse DOM scrub
51
+ // (src/renderer/index.js) and the diff-path gates remain as defense-in-depth.
52
+ //
53
+ // This is NOT the mXSS scrub-then-reparse anti-pattern guarded by the module
54
+ // header (lines 14-19): we rewrite TYPED attribute values inside the markup
55
+ // we are ABOUT TO EMIT (the wire payload's <img> src/srcset/poster), never a
56
+ // sanitized DOM serialized back to a string and re-parsed. payload.html stays
57
+ // raw for everything else; only fetchable asset attributes are rewritten, and
58
+ // only into a non-fetchable dimensioned placeholder or a pinned same-origin
59
+ // value. No DOM is constructed here (this module stays DOM-free by contract).
60
+
61
+ // ---- Quote-aware <img> start-tag locator (review CR-02) ----
62
+ //
63
+ // A regex over HTML (`/<img\b([^>]*)>/`) is the wrong tool for a security
64
+ // boundary: `[^>]*` terminates the tag at the FIRST literal `>`, but `>` is
65
+ // legal inside a quoted attribute value (`<img alt="a>b" src="https://...">`)
66
+ // and does NOT end the start tag for a real parser. That split let a blocked
67
+ // `src` AFTER the in-attribute `>` slip through the gate unchanged and fetch
68
+ // during srcdoc parse. The scanner below finds the REAL end of each `<img`
69
+ // start tag by consuming `"..."` / `'...'` spans atomically, so a `>` inside
70
+ // quotes never terminates the tag. If a tag end cannot be found (an unbalanced
71
+ // quote runs to EOF), the opener is treated as unparseable and FAILS CLOSED
72
+ // (its asset attributes are neutralized) rather than passing through. The one
73
+ // remaining scanner/parser divergence -- a backtick-unquoted value carrying a
74
+ // `>` (backtick is not an HTML quote char, so the scanner stops INSIDE it) --
75
+ // is ALSO failed closed: attrsBlobIsUnreliable detects the unbalanced backtick
76
+ // and gateOneImgTag emits the placeholder instead of re-emitting the opener
77
+ // (review WR-01), so no `<img>` shape re-emits unmodified.
78
+
79
+ /**
80
+ * Find the index of the `>` that closes a start tag, honoring quoted attribute
81
+ * values (a `>` inside `"..."`, `'...'`, or a backtick span does not end the
82
+ * tag). The scanner is tag-name agnostic -- it consumes from the index just
83
+ * past the matched opener token, so it serves `<img`, `<video`, and `<source`
84
+ * identically (Phase 13 generalized findImgTagEnd -> findTagEnd; no behavior
85
+ * change for the <img> path).
86
+ *
87
+ * Backtick handling (review WR-01): the backtick is NOT an HTML quote char, so
88
+ * a real parser ends the tag at the FIRST `>` even when it sits inside a
89
+ * backtick-unquoted value (`alt=` + "`a>b`"). Treating the backtick as a third
90
+ * delimiter here makes the scanner deliberately stop LATER than the parser --
91
+ * it reads the trailing `src` as an attribute and gates it. That is the SAFE
92
+ * divergence direction (over-block: a URL the real parser would render inert is
93
+ * still blocked) and it never lets a later fetchable `src` slip past the gate.
94
+ * A genuine `>`-terminated tag a real browser would fetch from is found by the
95
+ * `"`/`'` rules unchanged.
96
+ * @param {string} html The full markup.
97
+ * @param {number} from Index just past the opener token (the matched opener).
98
+ * @returns {number} Index of the closing `>`, or -1 if none (unbalanced quote).
99
+ */
100
+ function findTagEnd(html, from) {
101
+ var quote = null; // null = outside a quoted value; else the open-quote char
102
+ for (var i = from; i < html.length; i++) {
103
+ var ch = html.charAt(i);
104
+ if (quote !== null) {
105
+ if (ch === quote) quote = null; // matching close quote (incl. backtick)
106
+ continue;
107
+ }
108
+ if (ch === '"' || ch === "'" || ch === '`') {
109
+ quote = ch; // entering a quoted (or backtick-unquoted) attribute value
110
+ continue;
111
+ }
112
+ if (ch === '>') return i;
113
+ }
114
+ return -1;
115
+ }
116
+
117
+ /**
118
+ * Find the index just past the matching `</tagName>` close tag for a container
119
+ * element (`<video>`/`<audio>`) whose start tag has already been consumed
120
+ * (review WR-03). Scanning starts at `from` (just past the start tag's `>`) and
121
+ * tracks nesting depth: a nested same-name start tag (`<video ...>`, but not a
122
+ * self-closing `<video/>`) increments depth, a `</tagName>` decrements it, and
123
+ * the position just past the `>` of the depth-0 close tag is returned. Quoted
124
+ * attribute values are skipped quote-aware (a `>` inside `"..."`/`'...'`/`` `...` ``
125
+ * does not close a tag), reusing findTagEnd to step over each opener's
126
+ * attributes. Returns -1 when no matching close tag exists (the element ran to
127
+ * EOF unterminated) -- the caller then falls back to resuming just past the
128
+ * start tag rather than consuming the rest of the document.
129
+ * @param {string} html The full markup.
130
+ * @param {number} from Index just past the start tag's `>`.
131
+ * @param {string} tagName Lowercase container tag name ('video' / 'audio').
132
+ * @returns {number} Index just past the matching `</tagName>`, or -1.
133
+ */
134
+ function findMatchingCloseTag(html, from, tagName) {
135
+ var openRe = new RegExp('<' + tagName + '\\b', 'gi');
136
+ var closeRe = new RegExp('</' + tagName + '\\s*>', 'gi');
137
+ var depth = 0;
138
+ var i = from;
139
+ while (i < html.length) {
140
+ openRe.lastIndex = i;
141
+ closeRe.lastIndex = i;
142
+ var openM = openRe.exec(html);
143
+ var closeM = closeRe.exec(html);
144
+ if (!closeM) return -1; // no close tag remains -> unterminated
145
+ if (openM && openM.index < closeM.index) {
146
+ // A nested same-name start tag before the next close. Only count it as a
147
+ // nesting opener if it is NOT self-closing (`<video/>` opens nothing).
148
+ var openTagEnd = findTagEnd(html, openM.index + openM[0].length);
149
+ if (openTagEnd === -1) return -1; // malformed opener runs to EOF
150
+ var isSelfClosing = html.charAt(openTagEnd - 1) === '/';
151
+ if (!isSelfClosing) depth++;
152
+ i = openTagEnd + 1;
153
+ continue;
154
+ }
155
+ // The next relevant token is a close tag.
156
+ if (depth === 0) {
157
+ return closeM.index + closeM[0].length; // just past `</tagName>`
158
+ }
159
+ depth--;
160
+ i = closeM.index + closeM[0].length;
161
+ }
162
+ return -1;
163
+ }
164
+
165
+ /**
166
+ * True when a bounded <img> attribute blob cannot be confidently parsed, so the
167
+ * scanner's tag boundary may disagree with a real HTML parser's and the tag
168
+ * must FAIL CLOSED instead of being re-emitted (review WR-01).
169
+ *
170
+ * findImgTagEnd treats only `"` and `'` as quote delimiters (correct per the
171
+ * HTML tokenizer). A backtick is NOT a quote char, so an unquoted attribute
172
+ * value containing a backtick AND a `>` (`alt=` + "`a>b`") makes the scanner
173
+ * stop at the `>` INSIDE the backticks -- the bounded blob ends mid-value and a
174
+ * later `src` is excluded from the gate. A real browser instead reads the
175
+ * unquoted value up to the FIRST `>` (so that later `src` is inert text, never
176
+ * a fetch), which is why this is a fail-closed-intent drift, not a live SSRF.
177
+ * The reliable, parser-free signal is an ODD number of backticks in the bounded
178
+ * blob: a backtick opened a value but its partner sits beyond the `>` the
179
+ * scanner stopped at. When detected we emit the dimensioned placeholder rather
180
+ * than re-emit the opener, accepting a vanishingly rare fidelity loss for
181
+ * legitimate backtick attribute content (backticks are not HTML quote chars).
182
+ * @param {string} attrs The bounded img attribute blob.
183
+ * @returns {boolean}
184
+ */
185
+ function attrsBlobIsUnreliable(attrs) {
186
+ if (typeof attrs !== 'string' || attrs.indexOf('`') === -1) return false;
187
+ var backticks = 0;
188
+ for (var i = 0; i < attrs.length; i++) {
189
+ if (attrs.charAt(i) === '`') backticks++;
190
+ }
191
+ return (backticks % 2) === 1; // unbalanced backtick -> scanner boundary suspect
192
+ }
193
+
194
+ /** Match the START of an <img start tag only (`<img` + a name boundary). */
195
+ var IMG_OPEN_RE = /<img\b/gi;
196
+ /** Match the START of a <video start tag (`<video` + a name boundary). */
197
+ var VIDEO_OPEN_RE = /<video\b/gi;
198
+ /** Match the START of an <audio start tag (`<audio` + a name boundary). */
199
+ var AUDIO_OPEN_RE = /<audio\b/gi;
200
+ /** Match the START of a <source start tag (`<source` + a name boundary). */
201
+ var SOURCE_OPEN_RE = /<source\b/gi;
202
+ // Leading substring of the dimensioned blocked-origin placeholder emitted by
203
+ // assetUnavailablePlaceholderTag. Single source of truth so gateSnapshotAssets
204
+ // can detect when a media tag was neutralized to a placeholder (vs re-emitted
205
+ // or surgically src-stripped) and consume the container's body accordingly
206
+ // (review WR-03).
207
+ var PLACEHOLDER_MARKER = '<div data-ps-asset-unavailable=';
208
+ /** Pull a double/single/unquoted attribute value out of an attrs blob. */
209
+ function readTagAttr(attrs, name) {
210
+ var re = new RegExp(name + '\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\'|([^\\s"\'>]+))', 'i');
211
+ var m = re.exec(attrs);
212
+ if (!m) return null;
213
+ return m[1] != null ? m[1] : (m[2] != null ? m[2] : (m[3] != null ? m[3] : ''));
214
+ }
215
+ /** Remove an attribute (all quote forms) from an attrs blob. */
216
+ function stripTagAttr(attrs, name) {
217
+ return attrs.replace(
218
+ new RegExp('\\s' + name + '\\s*=\\s*(?:"[^"]*"|\'[^\']*\'|[^\\s"\'>]+)', 'gi'),
219
+ ''
220
+ );
221
+ }
222
+ /** Set/replace a double-quoted attribute on an attrs blob (value HTML-escaped). */
223
+ function setTagAttr(attrs, name, value) {
224
+ var cleaned = stripTagAttr(attrs, name);
225
+ return cleaned + ' ' + name + '="' + escapeAttribute(value) + '"';
226
+ }
227
+
228
+ /**
229
+ * Build the dimensioned blocked-origin placeholder STRING (renderer-owned;
230
+ * never imported from capture per the project's duplicate-don't-couple style).
231
+ * Mirrors the capture placeholder visual: a dimension-only <div> carrying
232
+ * rr_width/rr_height (read from the element's own rr_width/rr_height or
233
+ * width/height attrs) and the machine-readable
234
+ * data-ps-asset-unavailable="blocked-origin" reason. Replacing an <img> 1:1
235
+ * with this <div> keeps the renderer's positional nid pairing consistent (the
236
+ * index pairs elements with the nodeIds sidecar by position, not by any live
237
+ * identity attribute -- Phase 7), so no identity attribute is carried here.
238
+ * @param {string} attrs The original img attribute blob.
239
+ * @returns {string}
240
+ */
241
+ function assetUnavailablePlaceholderTag(attrs) {
242
+ var w = readTagAttr(attrs, 'rr_width') || readTagAttr(attrs, 'width') || '';
243
+ var h = readTagAttr(attrs, 'rr_height') || readTagAttr(attrs, 'height') || '';
244
+ var out = PLACEHOLDER_MARKER + '"blocked-origin"';
245
+ if (w) out += ' rr_width="' + escapeAttribute(w) + '"';
246
+ if (h) out += ' rr_height="' + escapeAttribute(h) + '"';
247
+ out += '></div>';
248
+ return out;
249
+ }
250
+
251
+ /**
252
+ * True when a srcset value contains a candidate the gate blocks. Reuses the
253
+ * shared per-candidate parser so the snapshot string layer gates srcset with
254
+ * the same vocabulary as the diff/fragment gates (review WR-03/WR-04). Any
255
+ * unparseable input fails closed (treated as blocked).
256
+ * @param {string} srcset
257
+ * @param {(url: string, kind: string) => { allow: boolean }} gate
258
+ * @returns {boolean}
259
+ */
260
+ function srcsetHasBlockedCandidate(srcset, gate) {
261
+ if (!srcset) return false;
262
+ try {
263
+ var candidates = parseSrcsetCandidates(srcset);
264
+ for (var i = 0; i < candidates.length; i++) {
265
+ var url = candidates[i].url;
266
+ if (!url) continue;
267
+ var verdict = gate(url, 'image');
268
+ if (!verdict || !verdict.allow) return true;
269
+ }
270
+ return false;
271
+ } catch (e) {
272
+ return true; // unparseable srcset: fail closed
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Gate the bounded attribute blob of a single <img> start tag and return the
278
+ * replacement markup for the whole tag. Applies the ASST-03 currentSrc pin,
279
+ * then gates the effective src AND srcset; any blocked fetchable URL -> the
280
+ * dimensioned blocked-origin placeholder (no fetchable attribute emitted).
281
+ * @param {string} attrs The img attribute blob (already correctly bounded).
282
+ * @param {(url: string, kind: string) => { allow: boolean }} gate
283
+ * @returns {string}
284
+ */
285
+ function gateOneImgTag(attrs, gate) {
286
+ // Fail closed when the bounded blob is unreliable (review WR-01): a backtick-
287
+ // unquoted value containing `>` truncates the scanner's boundary so a later
288
+ // src/srcset is excluded from the gate. Rather than re-emit the (possibly
289
+ // fetchable) opener unchanged, neutralize the whole tag to a placeholder.
290
+ if (attrsBlobIsUnreliable(attrs)) {
291
+ return assetUnavailablePlaceholderTag(attrs);
292
+ }
293
+ var pinned = readTagAttr(attrs, 'data-ps-currentsrc');
294
+ var src = readTagAttr(attrs, 'src');
295
+ var srcset = readTagAttr(attrs, 'srcset');
296
+ var nextAttrs = attrs;
297
+ var effective = src;
298
+ if (pinned) {
299
+ // ASST-03: pin the displayed variant and neutralize re-negotiation.
300
+ effective = pinned;
301
+ nextAttrs = setTagAttr(nextAttrs, 'src', pinned);
302
+ nextAttrs = stripTagAttr(nextAttrs, 'srcset');
303
+ nextAttrs = stripTagAttr(nextAttrs, 'sizes');
304
+ nextAttrs = stripTagAttr(nextAttrs, 'data-ps-currentsrc');
305
+ srcset = null; // neutralized above; nothing left to gate
306
+ }
307
+ if (effective) {
308
+ var verdict = gate(effective, 'image');
309
+ if (!verdict || !verdict.allow) {
310
+ // Blocked origin -> dimensioned placeholder; no fetchable src emitted.
311
+ return assetUnavailablePlaceholderTag(attrs);
312
+ }
313
+ }
314
+ // srcset gate (WR-03/WR-04): a blocked candidate on a src-less or src-allowed
315
+ // <img> would still let the parser fetch a responsive variant. If any
316
+ // candidate is blocked AND no allowed src remains, fall back to the
317
+ // placeholder; otherwise strip srcset so only the (allowed) src can fetch.
318
+ if (srcset && srcsetHasBlockedCandidate(srcset, gate)) {
319
+ if (!effective) return assetUnavailablePlaceholderTag(attrs);
320
+ nextAttrs = stripTagAttr(nextAttrs, 'srcset');
321
+ }
322
+ return '<img' + nextAttrs + '>';
323
+ }
324
+
325
+ /**
326
+ * Gate the bounded attribute blob of a single <video>/<audio>/<source> start tag
327
+ * and return the replacement markup. Phase 13 (MEDIA-01 / V12 SSRF): a real
328
+ * browser's parser prefetches <video src>, <video poster>, and <source src>
329
+ * DURING srcdoc parse -- exactly like <img src> -- so any blocked fetchable URL
330
+ * here must be neutralized at the string layer before the parser sees it.
331
+ *
332
+ * Two distinct deny shapes, distinguished by the gate's reason (CR-01):
333
+ * - POSTER-MODE SOURCE STRIP (reason 'poster-mode-media'): poster mode fetches
334
+ * the poster image and nothing else, so the playable source must not issue a
335
+ * GET, but the <video poster> SHOULD still render. The `src` attribute is
336
+ * stripped from the START TAG (and a <source src> likewise) while the tag
337
+ * itself is KEPT -- mirroring the post-parse gateFragmentMedia poster strip
338
+ * (src/renderer/index.js), but at the string layer so the parser never sees
339
+ * a playable src. The poster passes its own gate and is preserved.
340
+ * - BLOCKED ORIGIN (any other deny reason): a fetchable URL the policy forbids
341
+ * outright. The whole tag is replaced by the dimensioned blocked-origin
342
+ * placeholder (no fetchable attribute emitted) -- the same fail-closed
343
+ * posture as the <img> path.
344
+ *
345
+ * A blocked `poster` (its own origin denied) always forces the placeholder: the
346
+ * poster is the one fetch poster mode permits, so if it is forbidden there is
347
+ * nothing left to render.
348
+ * @param {string} tagName 'video', 'audio', or 'source' (re-emit token when allowed).
349
+ * @param {string} attrs The attribute blob (already correctly bounded).
350
+ * @param {(url: string, kind: string) => { allow: boolean, reason?: string }} gate
351
+ * @returns {string}
352
+ */
353
+ function gateOneMediaTag(tagName, attrs, gate) {
354
+ // Fail closed when the bounded blob is unreliable (review WR-01 parity): a
355
+ // backtick-unquoted value carrying `>` truncates the scanner boundary so a
356
+ // later src/poster is excluded from the gate. Neutralize the whole tag.
357
+ if (attrsBlobIsUnreliable(attrs)) {
358
+ return assetUnavailablePlaceholderTag(attrs);
359
+ }
360
+ var nextAttrs = attrs;
361
+ var src = readTagAttr(attrs, 'src');
362
+ var srcAllowed = false; // a usable (allowed, not stripped) src survives the gate
363
+ if (src) {
364
+ // Distinct kinds so the gate can apply mode-aware policy: a <video src>
365
+ // gates as 'media' and a <source src> as 'source'. In poster mode the gate
366
+ // denies both with reason 'poster-mode-media' (no playable media GET; the
367
+ // poster still renders), so the src is STRIPPED but the tag kept. Any other
368
+ // deny is a blocked origin -> placeholder (fail closed, same as <img>).
369
+ var srcVerdict = gate(src, tagName === 'source' ? 'source' : 'media');
370
+ if (!srcVerdict || !srcVerdict.allow) {
371
+ if (srcVerdict && srcVerdict.reason === 'poster-mode-media') {
372
+ nextAttrs = stripTagAttr(nextAttrs, 'src');
373
+ } else {
374
+ return assetUnavailablePlaceholderTag(attrs);
375
+ }
376
+ } else {
377
+ srcAllowed = true;
378
+ }
379
+ }
380
+ // <source srcset> (responsive <picture> candidates) is prefetched by the
381
+ // parser exactly like <img srcset>, so it must be gated with the same per-
382
+ // candidate vocabulary (review WR-04 parity) -- a srcset-only <source> would
383
+ // otherwise re-emit a blocked candidate unchanged. <video>/<audio> carry no
384
+ // srcset, so this only matters for <source>. If any candidate is blocked and
385
+ // no allowed src remains, fall back to the placeholder; otherwise strip srcset
386
+ // so only the (allowed) src can fetch.
387
+ if (tagName === 'source') {
388
+ var srcset = readTagAttr(attrs, 'srcset');
389
+ if (srcset && srcsetHasBlockedCandidate(srcset, gate)) {
390
+ if (!srcAllowed) return assetUnavailablePlaceholderTag(attrs);
391
+ nextAttrs = stripTagAttr(nextAttrs, 'srcset');
392
+ }
393
+ }
394
+ // <video poster> is a fetchable image; <source> has no poster. A blocked
395
+ // poster origin forces the placeholder (the poster is the only thing poster
396
+ // mode renders, so a forbidden poster leaves nothing to show).
397
+ if (tagName === 'video') {
398
+ var poster = readTagAttr(attrs, 'poster');
399
+ if (poster) {
400
+ var posterVerdict = gate(poster, 'poster');
401
+ if (!posterVerdict || !posterVerdict.allow) {
402
+ return assetUnavailablePlaceholderTag(attrs);
403
+ }
404
+ }
405
+ }
406
+ return '<' + tagName + nextSelfClose(nextAttrs);
407
+ }
408
+
409
+ /**
410
+ * Re-emit the bounded attribute blob and closing `>` for an allowed media tag.
411
+ * The blob is re-emitted verbatim (a trailing self-closing `/` is preserved by
412
+ * appending it before `>`), so an allowed <video>/<source> is byte-identical to
413
+ * its input. Kept tiny and separate so the gate's re-emit path is explicit.
414
+ * @param {string} attrs
415
+ * @returns {string}
416
+ */
417
+ function nextSelfClose(attrs) {
418
+ return attrs + '>';
419
+ }
420
+
421
+ /**
422
+ * Rewrite fetchable <img> assets in a raw snapshot HTML string against an
423
+ * injected pre-write fetch gate (MSEC-01) and apply the ASST-03 currentSrc
424
+ * pin. For each <img>:
425
+ * 1. currentSrc pin: if data-ps-currentsrc is present, the effective src
426
+ * becomes that value and srcset/sizes are neutralized (removed) so the
427
+ * cross-origin viewer's DPR cannot re-negotiate a different variant.
428
+ * 2. fetch gate: gate(effectiveSrc, 'image') and gate every srcset
429
+ * candidate; if blocked, the entire <img> is replaced by the dimensioned
430
+ * blocked-origin placeholder (or srcset is stripped when an allowed src
431
+ * remains) so the parser never sees a fetchable blocked URL.
432
+ * An <img> with no src/currentsrc/srcset is left untouched.
433
+ *
434
+ * QUOTE-AWARE TAG SCAN (review CR-02): every start tag is located with a
435
+ * quote-aware scanner (findTagEnd), NOT a `[^>]*` regex -- a `>` inside a
436
+ * quoted attribute value (`alt="a>b"`) does not terminate the tag, so a
437
+ * blocked `src` after such a `>` can no longer slip through unmodified. An
438
+ * opener whose tag end cannot be located (an unbalanced quote running to EOF)
439
+ * is FAILED CLOSED: it is replaced by the dimensioned placeholder rather than
440
+ * passed through, so a malformed shape can never emit a fetchable blocked URL.
441
+ * The gate is fail-closed by construction (createViewer's gateAssetUrl); a
442
+ * missing gate leaves the markup unchanged (no-op) so this stays a pure string
443
+ * transform.
444
+ *
445
+ * PHASE 13 MEDIA GENERALIZATION (MEDIA-01 / V12): the scan now covers <img>
446
+ * (src/srcset + currentSrc pin), <video> (src + poster), and <source> (src) in
447
+ * ONE left-to-right pass -- at each cursor it advances to the nearest of the
448
+ * three openers and gates that tag, so a blocked media URL is neutralized at
449
+ * the string layer BEFORE the srcdoc parser can prefetch it (13-RESEARCH
450
+ * Pitfall 5). Nesting (<source> inside <video>) is handled naturally: the
451
+ * openers are independent matches, so each is gated on its own.
452
+ * @param {string} html Raw payload.html (string layer, pre-srcdoc).
453
+ * @param {(url: string, kind: string) => { allow: boolean }} gate
454
+ * @returns {string}
455
+ */
456
+ export function gateSnapshotAssets(html, gate) {
457
+ if (typeof html !== 'string' || !html) return html;
458
+ if (typeof gate !== 'function') return html;
459
+ var out = '';
460
+ var cursor = 0; // index of the next un-copied char in html
461
+ while (cursor < html.length) {
462
+ // Find the nearest asset opener at or after the cursor.
463
+ var next = nextAssetOpener(html, cursor);
464
+ if (!next) {
465
+ break; // no more asset openers
466
+ }
467
+ var tagStart = next.index; // index of '<' in the opener
468
+ var attrsStart = next.attrsStart; // index just past the opener token
469
+ // Copy everything before this opener verbatim.
470
+ out += html.slice(cursor, tagStart);
471
+ var tagEnd = findTagEnd(html, attrsStart); // quote-aware
472
+ if (tagEnd === -1) {
473
+ // Unbalanced quote: the tag never closes. Fail closed -- emit a
474
+ // placeholder for the remainder so no fetchable blocked URL survives,
475
+ // and stop (the rest of the string is inside an unterminated tag).
476
+ out += assetUnavailablePlaceholderTag(html.slice(attrsStart));
477
+ cursor = html.length;
478
+ break;
479
+ }
480
+ var attrs = html.slice(attrsStart, tagEnd); // bounded attribute blob
481
+ // A self-closing '/' just before '>' is part of the blob; the helpers
482
+ // tolerate a trailing '/' (it is not a quote/value char), and re-emitting
483
+ // the opener token + attrs + '>' preserves it.
484
+ if (next.tag === 'img') {
485
+ out += gateOneImgTag(attrs, gate);
486
+ cursor = tagEnd + 1; // resume just past this tag's '>'
487
+ } else {
488
+ var replacement = gateOneMediaTag(next.tag, attrs, gate);
489
+ out += replacement;
490
+ // WR-03: when a <video>/<audio> CONTAINER is neutralized to the placeholder
491
+ // <div> (not re-emitted, not surgically src-stripped), its child
492
+ // <source>/<track> and its `</video>`/`</audio>` close tag would otherwise be
493
+ // left orphaned in the stream (a close tag with no opener). A self-closing
494
+ // '/' just before '>' means the start tag had no body to consume. Detect the
495
+ // placeholder by its marker, and -- for a non-self-closing container --
496
+ // consume through the matching close tag so the placeholder fully replaces
497
+ // the element. A <source> is void (no close tag) and is never a container, so
498
+ // it is unaffected. If no matching close tag is found (unterminated element),
499
+ // we fall back to resuming past the start tag rather than swallowing the rest
500
+ // of the document.
501
+ var wasNeutralized = replacement.indexOf(PLACEHOLDER_MARKER) === 0;
502
+ var selfClosed = html.charAt(tagEnd - 1) === '/';
503
+ var isContainer = (next.tag === 'video' || next.tag === 'audio');
504
+ if (wasNeutralized && isContainer && !selfClosed) {
505
+ var closeEnd = findMatchingCloseTag(html, tagEnd + 1, next.tag);
506
+ cursor = (closeEnd === -1) ? (tagEnd + 1) : closeEnd;
507
+ } else {
508
+ cursor = tagEnd + 1; // resume just past this tag's '>'
509
+ }
510
+ }
511
+ }
512
+ out += html.slice(cursor);
513
+ return out;
514
+ }
515
+
516
+ /**
517
+ * Find the nearest <img>/<video>/<audio>/<source> start-tag opener at or after `from`.
518
+ * Returns { index, attrsStart, tag } for the earliest match, or null when none
519
+ * remains. Each regex is reset and seeked from `from` so the scan is
520
+ * cursor-driven (the unified gateSnapshotAssets loop owns the cursor; we do not
521
+ * rely on a single regex's stateful lastIndex across heterogeneous tags).
522
+ * @param {string} html
523
+ * @param {number} from
524
+ * @returns {?{index: number, attrsStart: number, tag: string}}
525
+ */
526
+ function nextAssetOpener(html, from) {
527
+ var best = null;
528
+ var specs = [
529
+ { re: IMG_OPEN_RE, tag: 'img' },
530
+ { re: VIDEO_OPEN_RE, tag: 'video' },
531
+ { re: AUDIO_OPEN_RE, tag: 'audio' },
532
+ { re: SOURCE_OPEN_RE, tag: 'source' }
533
+ ];
534
+ for (var i = 0; i < specs.length; i++) {
535
+ var re = specs[i].re;
536
+ re.lastIndex = from;
537
+ var m = re.exec(html);
538
+ if (m && (best === null || m.index < best.index)) {
539
+ best = { index: m.index, attrsStart: re.lastIndex, tag: specs[i].tag };
540
+ }
541
+ }
542
+ return best;
543
+ }
544
+
43
545
  // The ADOPTED srcdoc CSP (backstop behind both sanitization chokepoints,
44
546
  // delivered via meta because the mirror is never a fetched URL). Baseline
45
547
  // from 03-CONTEXT with ONE documented adjustment under the decision's own
@@ -54,9 +556,23 @@ import { scrubCssText } from './sanitize.js';
54
556
  // (03-RESEARCH Pitfall 8); the iframe-level sandbox attribute asserted in
55
557
  // createViewer is the analogous control. Documented in docs/SECURITY.md
56
558
  // (plan 03-05).
559
+ // Phase 13 (MEDIA-01/V14): media-src is the twin of img-src, added so the
560
+ // viewer's browser may fetch <video>/<audio>/<source> bytes from the source
561
+ // origin (the by-reference media model). `data:` is for small poster data URIs
562
+ // only (media bytes are never inlined). default-src 'none' and the absence of
563
+ // script-src are untouched (the string-layer gateSnapshotAssets is the primary
564
+ // control; CSP is the backstop -- 13-RESEARCH V14).
565
+ // Phase 14 (MADPT-01): media-src gains `blob:` ONLY -- it lets the inert in-
566
+ // iframe <video> PLAY the parent-realm MediaSource object URL the adaptive
567
+ // player mints (the cross-realm MSE bind; 14-RESEARCH "CSP / connect-src").
568
+ // This is the ONLY Phase-14 CSP edit. NO `connect-src` is added (Pitfall 5: the
569
+ // iframe issues no network request in the MSE path -- the PARENT fetches all
570
+ // segments and the child only plays the blob; it has no script anyway), and NO
571
+ // `script-src` is introduced. `blob:` is added to media-src ONLY (not img-src).
57
572
  var CSP_META = '<meta http-equiv="Content-Security-Policy" content="'
58
573
  + "default-src 'none'; "
59
574
  + 'img-src http: https: data:; '
575
+ + 'media-src http: https: data: blob:; '
60
576
  + "style-src http: https: 'unsafe-inline'; "
61
577
  + 'font-src http: https: data:'
62
578
  + '">';
@@ -175,7 +691,18 @@ export function buildSnapshotHtml(payload) {
175
691
 
176
692
  // CSP meta FIRST after <head> so the policy applies before any
177
693
  // parser-initiated fetch (03-RESEARCH "CSP meta injection").
178
- return '<!DOCTYPE html><html' + htmlAttrs + '><head>' + CSP_META + '<meta charset="UTF-8">' +
694
+ // MSEC-04 (Phase 15-02): a document-level no-referrer meta IMMEDIATELY after
695
+ // CSP_META (before charset/viewport/stylesheets/payload <img>) so the policy
696
+ // is parsed before any viewer-side subresource fetch (img/video/source/poster/
697
+ // background-image). One control covers every parser- and CSS-initiated fetch,
698
+ // so the mirrored page URL (which can carry signed tokens) never leaks in a
699
+ // Referer header to third-party origins. No `crossorigin` is added: the
700
+ // allow-same-origin sandbox + no crossorigin already omits credentials, and
701
+ // forcing crossorigin="anonymous" would break non-CORS assets. Live referrer/
702
+ // credential suppression is the deferred real-browser UAT (15-RESEARCH A2);
703
+ // the string contract is unit-pinned in tests/renderer-media-csp.test.js.
704
+ return '<!DOCTYPE html><html' + htmlAttrs + '><head>' + CSP_META +
705
+ '<meta name="referrer" content="no-referrer">' + '<meta charset="UTF-8">' +
179
706
  '<meta name="viewport" content="width=' + (parseInt(p.viewportWidth, 10) || 1920) + '">' +
180
707
  stylesheetLinks +
181
708
  inlineStyleTags +
@@ -192,7 +719,11 @@ export function buildFramePlaceholderHtml(frame) {
192
719
  var meta = '';
193
720
  if (origin) meta += '<p>Origin: ' + origin + '</p>';
194
721
  if (src) meta += '<p>Source: ' + src + '</p>';
195
- return '<!DOCTYPE html><html><head>' + CSP_META + '<meta charset="UTF-8">' +
722
+ // MSEC-04 (Phase 15-02): same document-level no-referrer meta after CSP_META
723
+ // as buildSnapshotHtml -- this container-less variant is also a viewer-rendered
724
+ // srcdoc, so the referrer policy must precede any subresource fetch here too.
725
+ return '<!DOCTYPE html><html><head>' + CSP_META +
726
+ '<meta name="referrer" content="no-referrer">' + '<meta charset="UTF-8">' +
196
727
  '<style>body{margin:0;font:13px system-ui,sans-serif;color:#30333a;background:#f6f7f9;}' +
197
728
  '.ps-frame-placeholder{box-sizing:border-box;min-height:100vh;display:flex;flex-direction:column;gap:6px;' +
198
729
  'justify-content:center;align-items:center;text-align:center;border:1px dashed #9aa3af;padding:16px;}' +
@@ -338,6 +338,7 @@ export function createWebSocketTransport(options) {
338
338
  };
339
339
  var now = typeof cfg.now === 'function' ? cfg.now : defaultNow;
340
340
  var openState = typeof WebSocketCtor.OPEN === 'number' ? WebSocketCtor.OPEN : 1;
341
+ var connectingState = typeof WebSocketCtor.CONNECTING === 'number' ? WebSocketCtor.CONNECTING : 0;
341
342
  var statusState = 'connecting';
342
343
  var messageHandlers = new Set();
343
344
  var statusHandlers = new Set();
@@ -350,6 +351,21 @@ export function createWebSocketTransport(options) {
350
351
  var sendQueue = Promise.resolve();
351
352
  var receiveQueue = Promise.resolve();
352
353
  var unsubscribers = [];
354
+ // Pre-open gate: frames queued before the socket reaches OPEN park on this
355
+ // promise instead of being dropped, so the README quickstart (construct
356
+ // transport then immediately capture.start()) does not lose the initial
357
+ // READY/SNAPSHOT. The gate resolves once on the first terminal lifecycle
358
+ // event (open, error, or close) and is never re-armed afterward; settling it
359
+ // on error/close guarantees parked sends drain (and report a drop) rather
360
+ // than leaking pending tasks if the socket never opens.
361
+ var openGateSettled = false;
362
+ var resolveOpenGate = null;
363
+ var openGate = new Promise(function (resolve) { resolveOpenGate = resolve; });
364
+ function settleOpenGate() {
365
+ if (openGateSettled) return;
366
+ openGateSettled = true;
367
+ if (typeof resolveOpenGate === 'function') resolveOpenGate();
368
+ }
353
369
  var ws = new WebSocketCtor(url);
354
370
  if (ws && Object.prototype.hasOwnProperty.call(ws, 'binaryType')) {
355
371
  try {
@@ -423,9 +439,19 @@ export function createWebSocketTransport(options) {
423
439
  return ws && ws.readyState === openState;
424
440
  }
425
441
 
442
+ function isConnecting() {
443
+ return ws && ws.readyState === connectingState;
444
+ }
445
+
426
446
  function send(type, payload) {
427
447
  var msg = { type: type, payload: payload || {}, ts: now() };
428
448
  sendQueue = sendQueue.then(async function () {
449
+ // Park frames issued while the socket is still CONNECTING until the
450
+ // open gate settles, preserving FIFO order (this stays on the single
451
+ // chained queue) instead of dropping the initial READY/SNAPSHOT.
452
+ if (isConnecting() && !openGateSettled) {
453
+ await openGate;
454
+ }
429
455
  if (!isOpen()) {
430
456
  drops += 1;
431
457
  recordError('websocket-not-open');
@@ -508,6 +534,7 @@ export function createWebSocketTransport(options) {
508
534
  }
509
535
 
510
536
  unsubscribers.push(addSocketListener(ws, 'open', function () {
537
+ settleOpenGate();
511
538
  emitStatus('open');
512
539
  }));
513
540
  unsubscribers.push(addSocketListener(ws, 'message', function (event) {
@@ -520,10 +547,15 @@ export function createWebSocketTransport(options) {
520
547
  });
521
548
  }));
522
549
  unsubscribers.push(addSocketListener(ws, 'error', function () {
550
+ // Release any parked pre-open frames; the !isOpen() guard then records a
551
+ // drop for each instead of hanging the send queue on a socket that never
552
+ // reaches OPEN.
553
+ settleOpenGate();
523
554
  recordError('websocket-error');
524
555
  emitStatus('error', { reason: 'websocket-error' });
525
556
  }));
526
557
  unsubscribers.push(addSocketListener(ws, 'close', function (event) {
558
+ settleOpenGate();
527
559
  emitStatus('closed', {
528
560
  closeCode: event && typeof event.code === 'number' ? event.code : null,
529
561
  closeReason: event && typeof event.reason === 'string' ? event.reason : ''
@@ -534,6 +566,10 @@ export function createWebSocketTransport(options) {
534
566
  try {
535
567
  unsubscribers.forEach(function (unsubscribe) { unsubscribe(); });
536
568
  unsubscribers = [];
569
+ // close() detaches listeners above, so the socket's own close event can
570
+ // no longer settle the gate -- release parked sends here too so a
571
+ // pre-open close() does not leave queued tasks pending forever.
572
+ settleOpenGate();
537
573
  if (ws && typeof ws.close === 'function') ws.close();
538
574
  } catch (err) {
539
575
  recordError('websocket-close-failed');