@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
@@ -130,6 +130,86 @@ export var OVERLAY_CSS = [
130
130
  '.ps-overlay-dialog-message {',
131
131
  ' font-size: 14px; color: #e0e0e0; line-height: 1.5;',
132
132
  ' word-break: break-word; max-height: 200px; overflow-y: auto;',
133
+ '}',
134
+ // ---- Phase 13 (MEDIA-05): media affordance family (13-UI-SPEC States A/B/C).
135
+ // Parity values reused verbatim from the glow/progress/dialog built-ins:
136
+ // scrim rgba(0,0,0,0.5); pill rgba(0,0,0,0.75)+blur(4px)+radius 6px; accent
137
+ // #f59e0b (reserved for the actionable control); text #e0e0e0; glow
138
+ // 0 0 12px rgba(245,158,11,0.6); system-ui 13/600; play button >= 44x44.
139
+ // State A: blocked-play scrim clipped to the element rect.
140
+ '.ps-overlay-media-blocked {',
141
+ ' position: absolute;',
142
+ ' background: rgba(0, 0, 0, 0.5);',
143
+ ' display: flex; align-items: center; justify-content: center;',
144
+ ' pointer-events: none;', // the scrim is passive; only the button opts in
145
+ '}',
146
+ // State A: centered circular play button (the one actionable control).
147
+ '.ps-overlay-media-button {',
148
+ ' box-sizing: border-box;',
149
+ ' min-width: 44px; min-height: 44px;',
150
+ ' display: flex; align-items: center; justify-content: center;',
151
+ ' border: 2px solid #f59e0b;',
152
+ ' border-radius: 50%;',
153
+ ' box-shadow: 0 0 12px rgba(245, 158, 11, 0.6);',
154
+ ' background: transparent;',
155
+ ' color: #f59e0b;', // currentColor for the inline-SVG play glyph
156
+ ' cursor: pointer;',
157
+ ' pointer-events: auto;',
158
+ '}',
159
+ '@media (prefers-reduced-motion: no-preference) {',
160
+ ' .ps-overlay-media-button:hover, .ps-overlay-media-button:focus {',
161
+ ' filter: brightness(1.1);',
162
+ ' }',
163
+ '}',
164
+ // State B: unmute pill anchored bottom-left of the element rect.
165
+ '.ps-overlay-media-unmute {',
166
+ ' position: absolute;',
167
+ ' display: inline-flex; align-items: center; gap: 4px;',
168
+ ' background: rgba(0, 0, 0, 0.75);',
169
+ ' backdrop-filter: blur(4px);',
170
+ ' -webkit-backdrop-filter: blur(4px);',
171
+ ' color: #e0e0e0;',
172
+ ' font: 600 13px/1.2 system-ui, sans-serif;',
173
+ ' padding: 4px 12px;',
174
+ ' border-radius: 6px;',
175
+ ' cursor: pointer;',
176
+ ' pointer-events: auto;',
177
+ '}',
178
+ '.ps-overlay-media-unmute-icon {',
179
+ ' display: inline-flex; color: #f59e0b;', // amber speaker glyph fill
180
+ '}',
181
+ '@media (prefers-reduced-motion: no-preference) {',
182
+ ' .ps-overlay-media-unmute:hover, .ps-overlay-media-unmute:focus {',
183
+ ' filter: brightness(1.1);',
184
+ ' }',
185
+ '}',
186
+ // State C: passive poster-only caption (no accent, no pointer events).
187
+ '.ps-overlay-media-poster {',
188
+ ' position: absolute;',
189
+ ' display: inline-flex; align-items: center;',
190
+ ' background: rgba(0, 0, 0, 0.75);',
191
+ ' backdrop-filter: blur(4px);',
192
+ ' -webkit-backdrop-filter: blur(4px);',
193
+ ' color: #e0e0e0;',
194
+ ' font: 600 13px/1.2 system-ui, sans-serif;',
195
+ ' padding: 4px 12px;',
196
+ ' border-radius: 6px;',
197
+ ' pointer-events: none;',
198
+ '}',
199
+ // Phase 14 (MADPT-03): the degrade-reason caption -- a passive clone of the
200
+ // poster caption (same parity values), NO accent. Reason rides a data-
201
+ // attribute (set via setAttribute), never the visible caption.
202
+ '.ps-overlay-media-unavailable {',
203
+ ' position: absolute;',
204
+ ' display: inline-flex; align-items: center;',
205
+ ' background: rgba(0, 0, 0, 0.75);',
206
+ ' backdrop-filter: blur(4px);',
207
+ ' -webkit-backdrop-filter: blur(4px);',
208
+ ' color: #e0e0e0;',
209
+ ' font: 600 13px/1.2 system-ui, sans-serif;',
210
+ ' padding: 4px 12px;',
211
+ ' border-radius: 6px;',
212
+ ' pointer-events: none;',
133
213
  '}'
134
214
  ].join('\n');
135
215
 
@@ -155,6 +235,22 @@ var ICON_SVG = {
155
235
  + 'm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/></svg>'
156
236
  };
157
237
 
238
+ // Phase 13 media affordance glyphs (13-UI-SPEC: inline SVG, the zero-dependency
239
+ // Font-Awesome-replacement precedent of ICON_SVG above). fill: currentColor so
240
+ // the affordance accent (#f59e0b) applies. These are the ONLY innerHTML strings
241
+ // the media affordances assign -- every label is set via textContent.
242
+ var MEDIA_GLYPH = {
243
+ // play triangle (centered in the blocked-play button)
244
+ play: '<svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">'
245
+ + '<path d="M8 5v14l11-7z"/></svg>',
246
+ // muted speaker (line-sized for the unmute pill)
247
+ mutedSpeaker: '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">'
248
+ + '<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0'
249
+ + 'c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06'
250
+ + 'c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18'
251
+ + 'v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/></svg>'
252
+ };
253
+
158
254
  /**
159
255
  * Map a rect from capture-page viewport coordinates into host-document
160
256
  * pixel coordinates over the scaled, letterboxed iframe. Pure parity math
@@ -249,6 +345,10 @@ export function mapHostPointToViewport(point, scale) {
249
345
  * Dispatch one STREAM.OVERLAY payload through the registry.
250
346
  * @property {(payload: Object) => void} handleDialogMessage
251
347
  * STREAM.DIALOG handler (dialog card show/hide).
348
+ * @property {(kind: string, payload: ?Object, ctx?: {anchorRect?: ?Object}) => void} show
349
+ * Drive a registered overlay kind directly from renderer state (the media
350
+ * affordances are renderer-state-driven, not wire-driven; 13-UI-SPEC). ctx
351
+ * carries the pre-resolved anchorRect. A null payload hides (reset contract).
252
352
  * @property {() => void} resetOverlays
253
353
  * Hide all kinds (new-snapshot reset, dashboard.js:2762-2764 parity).
254
354
  */
@@ -442,6 +542,229 @@ export function createOverlays(opts) {
442
542
  register('glow', renderGlow);
443
543
  register('progress', renderProgress);
444
544
 
545
+ // --- Phase 13 media affordances (13-UI-SPEC States A/B/C). Siblings of the
546
+ // built-ins, registered through the same Map. Elements are created lazily on
547
+ // first show and persist across show/hide (a null payload hides -- the
548
+ // universal reset contract). Interactive controls (blocked-play button,
549
+ // unmute pill) set pointer-events:auto and invoke a payload.onActivate
550
+ // callback on click + Enter/Space; the poster caption is passive. ALL text is
551
+ // set via textContent; the ONLY innerHTML is the static MEDIA_GLYPH SVGs. ---
552
+ var mediaBlockedEl = null;
553
+ var mediaBlockedBtn = null;
554
+ var mediaBlockedActivate = null; // current onActivate (re-pointed per show)
555
+ var mediaUnmuteEl = null;
556
+ var mediaUnmuteActivate = null;
557
+ var mediaPosterEl = null;
558
+ var mediaUnavailableEl = null; // Phase 14: the degrade-reason caption
559
+
560
+ /**
561
+ * Invoke a stored onActivate callback in containment -- a throwing host
562
+ * handler routes to the logger and never breaks the affordance.
563
+ * @param {?Function} fn
564
+ */
565
+ function safeActivate(fn) {
566
+ if (typeof fn !== 'function') return;
567
+ try { fn(); } catch (err) { logger.error('[Renderer] media affordance onActivate failed', err); }
568
+ }
569
+
570
+ /** Attach click + Enter/Space activation to an interactive control. */
571
+ function wireActivation(el, getHandler) {
572
+ el.addEventListener('click', function () { safeActivate(getHandler()); });
573
+ el.addEventListener('keydown', function (ev) {
574
+ if (ev && (ev.key === 'Enter' || ev.key === ' ' || ev.key === 'Spacebar')) {
575
+ if (typeof ev.preventDefault === 'function') ev.preventDefault();
576
+ safeActivate(getHandler());
577
+ }
578
+ });
579
+ }
580
+
581
+ /** Apply an anchor rect to an absolutely-positioned affordance element. */
582
+ function anchorAffordance(el, anchorRect) {
583
+ if (!anchorRect) return;
584
+ el.style.top = anchorRect.top + 'px';
585
+ el.style.left = anchorRect.left + 'px';
586
+ el.style.width = anchorRect.width + 'px';
587
+ el.style.height = anchorRect.height + 'px';
588
+ }
589
+
590
+ /**
591
+ * State A -- blocked-play affordance. Non-null payload renders a scrim
592
+ * clipped to the rect with a centered >=44x44 amber play button; null hides.
593
+ * The button is the one actionable control (pointer-events:auto, role=button,
594
+ * focusable, aria-label, inline-SVG play glyph). onActivate fires on
595
+ * click/Enter/Space (a user gesture, so the re-issued play() is allowed).
596
+ * @param {?Object} value
597
+ * @param {?Object} anchorRect
598
+ */
599
+ function renderMediaBlocked(value, anchorRect) {
600
+ if (!value) {
601
+ if (mediaBlockedEl) mediaBlockedEl.style.display = 'none';
602
+ mediaBlockedActivate = null;
603
+ return;
604
+ }
605
+ if (!mediaBlockedEl) {
606
+ mediaBlockedEl = doc.createElement('div');
607
+ mediaBlockedEl.className = 'ps-overlay-media-blocked';
608
+ mediaBlockedEl.style.zIndex = '25'; // above progress (20), below dialog (30)
609
+ mediaBlockedBtn = doc.createElement('div');
610
+ mediaBlockedBtn.className = 'ps-overlay-media-button';
611
+ mediaBlockedBtn.setAttribute('role', 'button');
612
+ mediaBlockedBtn.setAttribute('tabindex', '0');
613
+ mediaBlockedBtn.setAttribute('aria-label', 'Play mirrored media');
614
+ mediaBlockedBtn.style.pointerEvents = 'auto';
615
+ // 44x44 hit-target floor set inline so it holds regardless of CSS
616
+ // delivery (13-UI-SPEC; the button auto-grows to this minimum even over a
617
+ // small <audio> rect).
618
+ mediaBlockedBtn.style.minWidth = '44px';
619
+ mediaBlockedBtn.style.minHeight = '44px';
620
+ mediaBlockedBtn.innerHTML = MEDIA_GLYPH.play; // static glyph -- ONLY innerHTML
621
+ wireActivation(mediaBlockedBtn, function () { return mediaBlockedActivate; });
622
+ mediaBlockedEl.appendChild(mediaBlockedBtn);
623
+ layer.appendChild(mediaBlockedEl);
624
+ }
625
+ mediaBlockedActivate = (typeof value.onActivate === 'function') ? value.onActivate : null;
626
+ anchorAffordance(mediaBlockedEl, anchorRect);
627
+ mediaBlockedEl.style.display = 'flex';
628
+ }
629
+
630
+ /**
631
+ * State B -- unmute affordance. Non-null payload renders a bottom-left pill
632
+ * (amber muted-speaker glyph + "Unmute" label via textContent); null hides.
633
+ * The pill is actionable (pointer-events:auto, role=button, focusable,
634
+ * aria-label). onActivate fires on click/Enter/Space.
635
+ * @param {?Object} value
636
+ * @param {?Object} anchorRect
637
+ */
638
+ function renderMediaUnmute(value, anchorRect) {
639
+ if (!value) {
640
+ if (mediaUnmuteEl) mediaUnmuteEl.style.display = 'none';
641
+ mediaUnmuteActivate = null;
642
+ return;
643
+ }
644
+ if (!mediaUnmuteEl) {
645
+ mediaUnmuteEl = doc.createElement('div');
646
+ mediaUnmuteEl.className = 'ps-overlay-media-unmute';
647
+ mediaUnmuteEl.style.zIndex = '25';
648
+ mediaUnmuteEl.setAttribute('role', 'button');
649
+ mediaUnmuteEl.setAttribute('tabindex', '0');
650
+ mediaUnmuteEl.setAttribute('aria-label', 'Unmute mirrored media');
651
+ mediaUnmuteEl.style.pointerEvents = 'auto';
652
+ var icon = doc.createElement('span');
653
+ icon.className = 'ps-overlay-media-unmute-icon';
654
+ icon.innerHTML = MEDIA_GLYPH.mutedSpeaker; // static glyph -- ONLY innerHTML
655
+ var label = doc.createElement('span');
656
+ label.className = 'ps-overlay-media-unmute-label';
657
+ label.textContent = 'Unmute'; // text via textContent (security invariant)
658
+ mediaUnmuteEl.appendChild(icon);
659
+ mediaUnmuteEl.appendChild(label);
660
+ wireActivation(mediaUnmuteEl, function () { return mediaUnmuteActivate; });
661
+ layer.appendChild(mediaUnmuteEl);
662
+ }
663
+ mediaUnmuteActivate = (typeof value.onActivate === 'function') ? value.onActivate : null;
664
+ // Anchor bottom-left of the rect (mirrors the progress-pill anchor).
665
+ if (anchorRect) {
666
+ mediaUnmuteEl.style.left = anchorRect.left + 8 + 'px';
667
+ mediaUnmuteEl.style.top = (anchorRect.top + anchorRect.height - 8 - 24) + 'px';
668
+ }
669
+ mediaUnmuteEl.style.display = 'inline-flex';
670
+ }
671
+
672
+ /**
673
+ * State C -- poster-only caption (no-poster fallback). Passive: pointer-events
674
+ * none, no accent, no activation, text "Media (poster only)" via textContent.
675
+ * Null hides.
676
+ * @param {?Object} value
677
+ * @param {?Object} anchorRect
678
+ */
679
+ function renderMediaPoster(value, anchorRect) {
680
+ if (!value) {
681
+ if (mediaPosterEl) mediaPosterEl.style.display = 'none';
682
+ return;
683
+ }
684
+ if (!mediaPosterEl) {
685
+ mediaPosterEl = doc.createElement('div');
686
+ mediaPosterEl.className = 'ps-overlay-media-poster';
687
+ mediaPosterEl.style.zIndex = '24';
688
+ mediaPosterEl.style.pointerEvents = 'none';
689
+ mediaPosterEl.textContent = 'Media (poster only)'; // textContent only
690
+ layer.appendChild(mediaPosterEl);
691
+ }
692
+ // Centered in the rect.
693
+ if (anchorRect) {
694
+ mediaPosterEl.style.left = (anchorRect.left + anchorRect.width / 2) + 'px';
695
+ mediaPosterEl.style.top = (anchorRect.top + anchorRect.height / 2) + 'px';
696
+ mediaPosterEl.style.transform = 'translate(-50%, -50%)';
697
+ }
698
+ mediaPosterEl.style.display = 'inline-flex';
699
+ }
700
+
701
+ /**
702
+ * Phase 14 (MADPT-03) -- the degrade-reason caption. A passive near-clone of
703
+ * renderMediaPoster: a centered caption "Media unavailable" via textContent,
704
+ * pointer-events none, no accent, no activation. The four reason codes
705
+ * (no-manifest/no-player/mse-opaque/drm) ride a data- attribute set via
706
+ * setAttribute (diagnostic only -- NEVER interpolated into markup, so the
707
+ * innerHTML sink allowlist is unchanged; T-14-09). Null hides (universal
708
+ * reset). Shown by media-player.js's degrade(nid, reason) sink.
709
+ * @param {?Object} value { nid?, reason? } or null
710
+ * @param {?Object} anchorRect
711
+ */
712
+ function renderMediaUnavailable(value, anchorRect) {
713
+ if (!value) {
714
+ if (mediaUnavailableEl) mediaUnavailableEl.style.display = 'none';
715
+ return;
716
+ }
717
+ if (!mediaUnavailableEl) {
718
+ mediaUnavailableEl = doc.createElement('div');
719
+ mediaUnavailableEl.className = 'ps-overlay-media-unavailable';
720
+ mediaUnavailableEl.style.zIndex = '24';
721
+ mediaUnavailableEl.style.pointerEvents = 'none';
722
+ mediaUnavailableEl.textContent = 'Media unavailable'; // textContent only
723
+ layer.appendChild(mediaUnavailableEl);
724
+ }
725
+ // The reason is a diagnostic attribute value, never user-facing markup.
726
+ if (value.reason !== undefined && value.reason !== null) {
727
+ mediaUnavailableEl.setAttribute('data-ps-reason', String(value.reason));
728
+ } else {
729
+ mediaUnavailableEl.removeAttribute('data-ps-reason');
730
+ }
731
+ // Centered in the rect (same math as the poster caption).
732
+ if (anchorRect) {
733
+ mediaUnavailableEl.style.left = (anchorRect.left + anchorRect.width / 2) + 'px';
734
+ mediaUnavailableEl.style.top = (anchorRect.top + anchorRect.height / 2) + 'px';
735
+ mediaUnavailableEl.style.transform = 'translate(-50%, -50%)';
736
+ }
737
+ mediaUnavailableEl.style.display = 'inline-flex';
738
+ }
739
+
740
+ register('media-blocked', renderMediaBlocked);
741
+ register('media-unmute', renderMediaUnmute);
742
+ register('media-poster', renderMediaPoster);
743
+ register('media-unavailable', renderMediaUnavailable);
744
+
745
+ /**
746
+ * Drive a registered overlay kind directly from renderer state (NOT a wire
747
+ * message). The media affordances appear/disappear as a function of local
748
+ * play() outcome / muted mismatch / mediaMode (13-UI-SPEC Motion section), so
749
+ * the renderer calls show(kind, payload, ctx) where ctx.anchorRect is the
750
+ * pre-resolved host rect for the element (or ctx carries { value, scale } for
751
+ * the standard resolver). A null payload hides (the universal reset). Errors
752
+ * in the renderFn are contained (safeRenderOverlay -> logger).
753
+ * @param {string} kind
754
+ * @param {?Object} payload
755
+ * @param {{anchorRect?: ?Object}} [ctx]
756
+ */
757
+ function show(kind, payload, ctx) {
758
+ var renderFn = registry.get(kind);
759
+ if (!renderFn) {
760
+ logger.warn('[Renderer] show() unknown overlay kind ignored', kind);
761
+ return;
762
+ }
763
+ var anchorRect = (ctx && ctx.anchorRect) ? ctx.anchorRect : null;
764
+ var value = (payload === undefined) ? null : payload;
765
+ safeRenderOverlay(kind, renderFn, value, anchorRect);
766
+ }
767
+
445
768
  /**
446
769
  * Dispatch one STREAM.OVERLAY payload. Every own key except the identity
447
770
  * keys (streamSessionId / snapshotId) is an overlay kind:
@@ -523,6 +846,7 @@ export function createOverlays(opts) {
523
846
  register: register,
524
847
  handleOverlayMessage: handleOverlayMessage,
525
848
  handleDialogMessage: handleDialogMessage,
849
+ show: show,
526
850
  resetOverlays: resetOverlays
527
851
  };
528
852
  }
@@ -0,0 +1,111 @@
1
+ // PhantomStream renderer: parser-safe placeholder restore (quick task
2
+ // 261202-jwf).
3
+ //
4
+ // A DOM built by scripts can hold nesting that HTML text cannot express (a
5
+ // button inside a button, a link inside a link, a div inside a paragraph, a
6
+ // row without a tbody). Capture renames such elements to
7
+ // <ps-node data-ps-tag="original-tag"> placeholders
8
+ // (neutralizeParserHostileNesting), so the viewer's parse keeps the tree and
9
+ // the positional nodeIds pairing intact. restoreParserSafePlaceholders turns
10
+ // them back into their original tags right after EVERY renderer parse, before
11
+ // sanitizeFragment and identity pairing, so restored elements always pass
12
+ // through the post-parse scrub and the asset gate.
13
+ //
14
+ // Only an allowlist is restored. script, iframe, object, embed, style, link,
15
+ // meta, base, html, head, body and frameset (and any other tag) stay inert
16
+ // generic <ps-node> elements. This module never assigns innerHTML and touches
17
+ // no DOM at import time.
18
+
19
+ import { PARSER_SAFE_TAG, PARSER_SAFE_TAG_ATTR } from '../protocol/messages.js';
20
+
21
+ // The tags capture's rename rules can produce that are safe to recreate.
22
+ var RESTORABLE = {
23
+ button: true, a: true, form: true, nobr: true, p: true,
24
+ h1: true, h2: true, h3: true, h4: true, h5: true, h6: true,
25
+ li: true, dd: true, dt: true, option: true, optgroup: true, select: true,
26
+ textarea: true, xmp: true, plaintext: true,
27
+ img: true, input: true, br: true, hr: true, wbr: true, area: true,
28
+ col: true, source: true, track: true,
29
+ table: true, tbody: true, thead: true, tfoot: true, tr: true, td: true,
30
+ th: true, caption: true, colgroup: true
31
+ };
32
+
33
+ // Restored tags whose URL attributes fetch as soon as they are set in a live
34
+ // document, and those attributes. data-ps-currentsrc is included because the
35
+ // asset gate promotes it to an <img> src (the ASST-03 currentSrc pin).
36
+ var URL_FILTERED_TAGS = { img: true, input: true, source: true, track: true };
37
+ var URL_FILTERED_ATTRS = { src: true, srcset: true, 'data-ps-currentsrc': true };
38
+
39
+ function filteredUrlValue(filterUrl, tag, attr, value) {
40
+ try {
41
+ var out = filterUrl(tag, attr, value);
42
+ return out === null || out === undefined ? null : String(out);
43
+ } catch (err) {
44
+ return null; // a throwing filter fails closed: the URL is dropped
45
+ }
46
+ }
47
+
48
+ function copyAttribute(el, attr, value) {
49
+ try {
50
+ el.setAttribute(attr.name, value);
51
+ } catch (err) {
52
+ try {
53
+ var clone = attr.cloneNode(true);
54
+ clone.value = value;
55
+ el.setAttributeNode(clone);
56
+ } catch (err2) { /* an attribute no element can carry is dropped */ }
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Restore capture's parser-safe placeholders under root, in document order.
62
+ *
63
+ * Each `ps-node[data-ps-tag]` whose trimmed, lowercased tag is on the
64
+ * restorable allowlist becomes a real element created by root's owner
65
+ * document: every attribute except data-ps-tag is copied, the children are
66
+ * moved, and the element takes the placeholder's position. Placeholders for
67
+ * any other tag, and `ps-node` elements without data-ps-tag, are left as they
68
+ * are.
69
+ *
70
+ * Call it right after a parse and BEFORE sanitizeFragment and identity
71
+ * pairing. In a live document (the snapshot and frame mirrors) pass
72
+ * `options.filterUrl`: restored img, input, source and track elements then
73
+ * get their src / srcset / data-ps-currentsrc only through it, so a blocked
74
+ * URL is never set (and never fetched). Template content is inert and is
75
+ * gated before importNode instead.
76
+ *
77
+ * @param {ParentNode} root A parsed body, document or template content.
78
+ * @param {{ filterUrl?: (tag: string, attr: string, value: string) => (string|null) }} [options]
79
+ * filterUrl returns the value to set, or null to drop the attribute.
80
+ * @returns {number} How many placeholders were restored.
81
+ */
82
+ export function restoreParserSafePlaceholders(root, options) {
83
+ if (!root || typeof root.querySelectorAll !== 'function') return 0;
84
+ var opts = options || {};
85
+ var filterUrl = typeof opts.filterUrl === 'function' ? opts.filterUrl : null;
86
+ var doc = root.ownerDocument || root;
87
+ if (!doc || typeof doc.createElement !== 'function') return 0;
88
+ var placeholders = root.querySelectorAll(PARSER_SAFE_TAG + '[' + PARSER_SAFE_TAG_ATTR + ']');
89
+ var restored = 0;
90
+ for (var i = 0; i < placeholders.length; i++) {
91
+ var placeholder = placeholders[i];
92
+ var tag = String(placeholder.getAttribute(PARSER_SAFE_TAG_ATTR) || '').trim().toLowerCase();
93
+ if (RESTORABLE[tag] !== true || !placeholder.parentNode) continue;
94
+ var el = doc.createElement(tag);
95
+ var attrs = placeholder.attributes;
96
+ for (var a = 0; a < attrs.length; a++) {
97
+ var name = String(attrs[a].name).toLowerCase();
98
+ if (name === PARSER_SAFE_TAG_ATTR) continue;
99
+ var value = attrs[a].value;
100
+ if (filterUrl && URL_FILTERED_TAGS[tag] === true && URL_FILTERED_ATTRS[name] === true) {
101
+ value = filteredUrlValue(filterUrl, tag, name, value);
102
+ if (value === null) continue;
103
+ }
104
+ copyAttribute(el, attrs[a], value);
105
+ }
106
+ while (placeholder.firstChild) el.appendChild(placeholder.firstChild);
107
+ placeholder.parentNode.replaceChild(el, placeholder);
108
+ restored++;
109
+ }
110
+ return restored;
111
+ }
@@ -93,17 +93,39 @@ function hasDangerousScheme(value) {
93
93
  || probe.indexOf('data:text/html') === 0;
94
94
  }
95
95
 
96
- function parseSrcsetCandidates(srcset) {
96
+ /**
97
+ * Minimal srcset candidate parser for the URL+descriptor forms this project
98
+ * emits (mirror of the capture-side parser). Unlike split(','), it keeps
99
+ * commas inside a candidate URL attached to the URL token, so a benign
100
+ * candidate cannot turn into a bogus relative fetch candidate. Two carve-outs
101
+ * suppress the comma-as-separator split: (1) data:image URLs (a base64 comma /
102
+ * the data: mediatype comma), and (2) any scheme-bearing absolute URL
103
+ * (http(s)/etc.), because an unencoded comma in an http(s) query string would
104
+ * otherwise mis-split a legitimate responsive CDN URL into a bogus second
105
+ * candidate -- which then fails the fetch gate and over-blocks the whole <img>
106
+ * to a placeholder (review WR-02). This is a fidelity widening only; the gate
107
+ * decision per candidate is unchanged. Exported so the Phase-12 renderer fetch
108
+ * gates (diff ATTR branch, gateFragmentAssets, the snapshot string layer) gate
109
+ * srcset per-candidate through ONE parser and the attribute coverage cannot
110
+ * drift between sites (review WR-03/WR-04).
111
+ * @param {string} srcset
112
+ * @returns {{url: string, descriptor: string}[]}
113
+ */
114
+ export function parseSrcsetCandidates(srcset) {
97
115
  var raw = String(srcset == null ? '' : srcset);
98
116
  var out = [];
99
117
  var i = 0;
100
118
  while (i < raw.length) {
101
119
  while (i < raw.length && /[\s,]/.test(raw.charAt(i))) i++;
102
120
  var urlStart = i;
103
- var isData = raw.slice(i, i + 5).toLowerCase() === 'data:';
121
+ var tokenSoFar = raw.slice(urlStart);
122
+ var isData = tokenSoFar.slice(0, 5).toLowerCase() === 'data:';
123
+ // A scheme-bearing absolute URL (scheme://...) keeps in-query commas
124
+ // attached to the URL token, mirroring the data: carve-out (WR-02).
125
+ var isAbsolute = /^[a-z][a-z0-9+.\-]*:\/\//i.test(tokenSoFar);
104
126
  while (i < raw.length
105
127
  && !/\s/.test(raw.charAt(i))
106
- && (isData || raw.charAt(i) !== ',')) {
128
+ && (isData || isAbsolute || raw.charAt(i) !== ',')) {
107
129
  i++;
108
130
  }
109
131
  var url = raw.slice(urlStart, i);