@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
@@ -0,0 +1,367 @@
1
+ // src/renderer/media-player.js
2
+ //
3
+ // Phase 14 (MADPT-01/MADPT-03): the renderer-owned PARENT-REALM adaptive media
4
+ // player. Extracted as the one genuinely net-new capability of the milestone --
5
+ // every other adaptive piece is wiring proven parts (the Phase 13 driver, the
6
+ // Phase 12 origin gate, the overlay registry, the adapter network hooks).
7
+ //
8
+ // The player runs ENTIRELY in the parent realm; the mirror iframe stays exactly
9
+ // sandbox="allow-same-origin" (NO allow-scripts -- T-14-04). The in-iframe
10
+ // <video> is inert data: the native path sets its `src` cross-realm; the MSE
11
+ // path hands hls.js (running in the parent) the bare child element via
12
+ // attachMedia(), and hls.js mints/owns the parent-realm MediaSource object URL
13
+ // (the spec ties the object-URL boundary to ORIGIN, not Document identity, and
14
+ // the srcdoc iframe is same-origin to its parent -- 14-RESEARCH A1/A5).
15
+ //
16
+ // attach(videoEl, manifestUrl, ctx) runs the decision tree EXACTLY in this order
17
+ // (14-RESEARCH "The attachment decision tree"):
18
+ // 1. GATE -> blocked manifest origin => degrade('no-manifest')
19
+ // 2. NATIVE HLS (canPlayType('application/vnd.apple.mpegurl') in
20
+ // {'probably','maybe'} on an HLS manifest) => set child
21
+ // videoEl.src directly; NO MSE, NO library.
22
+ // 3. HOST factory (a configured playerFactory) => factory(ctx).attach(...)
23
+ // 4. OPTIONAL lazy hls.js (HLS only, no factory) => feature-detect MSE,
24
+ // dynamic import('hls.js'), loadSource THEN attachMedia.
25
+ // 5. DASH no-factory => degrade('no-player')
26
+ // 6. anything else => degrade('no-manifest')
27
+ // The whole body is try/catch-contained -> degrade('mse-opaque') on ANY throw;
28
+ // attach() NEVER rethrows into the caller (T-14-07 -- the never-break contract).
29
+ //
30
+ // Every unmirrorable path funnels through the SINGLE degrade(nid, reason) sink
31
+ // (reason in {no-manifest|no-player|mse-opaque|drm}) which tears down the live
32
+ // player for nid (revoke parent object URLs, removeAttribute('src') + load() on
33
+ // the inert child, both guarded), shows the passive `media-unavailable` overlay,
34
+ // and invokes the contained onMediaUnavailable(nid, reason) host callback (the
35
+ // onMediaBlocked family -- logger-trapped, NEVER rethrown). The mirror never
36
+ // breaks; the rest of the snapshot/diff stream keeps updating.
37
+ //
38
+ // DRM (T-14-05): emeEnabled is NEVER set true; the child element's 'encrypted'
39
+ // event AND an hls.js KEY_SYSTEM_ERROR both route to degrade('drm'). Protected
40
+ // content is never mirrored.
41
+ //
42
+ // Plain JS ESM (no runtime build step -- the renderer must stay importable with
43
+ // hls.js ABSENT, so hls.js is referenced ONLY via the dynamic import inside
44
+ // tryLazyImportHls; a top-level `import 'hls.js'` would break package:smoke and
45
+ // the zero-hard-runtime-dependency guarantee -- 14-RESEARCH Pitfall 1).
46
+
47
+ import { classifyManifest } from '../protocol/messages.js';
48
+
49
+ /**
50
+ * @typedef {Object} PlayerAdapterCtx
51
+ * @property {Document} doc iframe.contentDocument (where videoEl lives)
52
+ * @property {string} manifestUrl gated, absolute manifest URL
53
+ * @property {'hls'|'dash'} kind derived from the manifest classifier
54
+ * @property {HTMLMediaElement} videoEl the in-iframe child element
55
+ * @property {Object} logger
56
+ * @property {(url: string, kind: string) => {allow: boolean}} gateAsset reuse Phase 12 gate
57
+ * @property {?string} nid element nid for overlay anchoring + the reason callback
58
+ */
59
+
60
+ /**
61
+ * @typedef {Object} PlayerAdapter
62
+ * @property {(videoEl: HTMLMediaElement, manifestUrl: string, ctx: PlayerAdapterCtx) => void} attach
63
+ * Bind the manifest to the element (host owns MSE/attachMedia/segment fetch in the PARENT realm).
64
+ * @property {() => void} destroy Tear down: detach MSE, revoke object URLs, free buffers. Idempotent.
65
+ * @property {(handler: (reason: string) => void) => void} [onError]
66
+ * Report a fatal/unrecoverable error with a reason code; the viewer degrades to poster.
67
+ */
68
+
69
+ /**
70
+ * @typedef {Object} MediaPlayerDeps
71
+ * @property {Document} doc iframe.contentDocument the child <video> lives in
72
+ * @property {Window} win the PARENT realm window (MSE feature-detect surface)
73
+ * @property {(url: string, kind: string) => {allow: boolean}} gateAsset Phase 12 fail-closed gate
74
+ * @property {Object} logger viewer logger (info/warn/error)
75
+ * @property {(ctx: PlayerAdapterCtx) => PlayerAdapter} [playerFactory] host-provided player seam
76
+ * @property {(nid: ?string, reason: string) => void} onMediaUnavailable degrade reason callback
77
+ * @property {(kind: string, payload: ?Object, ctx: ?Object) => void} showOverlay overlay driver
78
+ * @property {(nid: ?string) => ?Object} resolveNidRect anchor-rect resolver for the overlay
79
+ * @property {(videoEl: HTMLMediaElement, nid: ?string) => void} ensurePlaying Phase 13 play kickoff
80
+ * @property {(nid: ?string) => void} [keepPoster] keep/restore the element poster on degrade
81
+ * @property {() => Promise<*>} [tryLazyImportHls] TEST SEAM: override the dynamic hls.js import
82
+ */
83
+
84
+ /**
85
+ * Dynamic, try/catch-guarded hls.js loader. DYNAMIC import INSIDE this function
86
+ * ONLY -- never a top-level import (breaks package:smoke / zero-hard-dep --
87
+ * 14-RESEARCH Pitfall 1). Returns the Hls constructor or null on absence/failure
88
+ * (the graceful-absence path: degrade('no-player')).
89
+ * @returns {Promise<*>} the Hls constructor, or null when hls.js is unavailable
90
+ */
91
+ async function tryLazyImportHls() {
92
+ try {
93
+ var mod = await import('hls.js');
94
+ return (mod && (mod.default || mod.Hls || mod)) || null;
95
+ } catch (e) {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Is the MSE attachment surface present in the parent realm? hls.js prefers
102
+ * ManagedMediaSource (Safari/power-aware) and falls back to MediaSource; both
103
+ * are parent-realm globals and both produce a child-acceptable attachment.
104
+ * @param {?Window} win
105
+ * @returns {boolean}
106
+ */
107
+ function canUseMse(win) {
108
+ return !!(win && (win.ManagedMediaSource || win.MediaSource));
109
+ }
110
+
111
+ /**
112
+ * Native-HLS feature-detect: an HLS manifest the child element can play directly
113
+ * (Safari, and increasingly Chromium 142+). 'probably'/'maybe' are the advisory
114
+ * positives; '' means no native support -> fall through to the MSE path.
115
+ * @param {HTMLMediaElement} videoEl
116
+ * @param {'hls'|'dash'|null} kind
117
+ * @returns {boolean}
118
+ */
119
+ function isNativeHls(videoEl, kind) {
120
+ if (kind !== 'hls') return false;
121
+ var v = (videoEl && typeof videoEl.canPlayType === 'function')
122
+ ? videoEl.canPlayType('application/vnd.apple.mpegurl')
123
+ : '';
124
+ return v === 'probably' || v === 'maybe';
125
+ }
126
+
127
+ /**
128
+ * Create the parent-realm adaptive media player. The renderer injects the live
129
+ * deps in Plan 03; the Plan 02 tests inject stubs/fakes (a stub `win` carrying
130
+ * MediaSource, a controllable-canPlayType video stub, a fake playerFactory, and
131
+ * a `tryLazyImportHls` override). Maintains a per-nid registry so a re-snapshot
132
+ * (Plan 03) can destroyAll() before the new mirror document replaces the child
133
+ * elements (Pattern 2 -- player teardown on new identity).
134
+ *
135
+ * @param {MediaPlayerDeps} deps
136
+ * @returns {{
137
+ * attach: (videoEl: HTMLMediaElement, manifestUrl: string, ctx?: Object) => (Object|Promise<Object|undefined>|undefined),
138
+ * degrade: (nid: ?string, reason: string) => undefined,
139
+ * destroy: (nid: ?string) => undefined,
140
+ * destroyAll: () => undefined
141
+ * }}
142
+ */
143
+ export function createMediaPlayer(deps) {
144
+ var d = deps || {};
145
+ var logger = d.logger || { info: function () {}, warn: function () {}, error: function () {} };
146
+ // TEST SEAM: allow the lazy-import to be overridden by a dep; default to the
147
+ // dynamic-import helper. The override keeps the suite jsdom-runnable with
148
+ // hls.js uninstalled (both the absent path and a stub-Hls path).
149
+ var lazyImportHls = (typeof d.tryLazyImportHls === 'function') ? d.tryLazyImportHls : tryLazyImportHls;
150
+
151
+ // Per-nid live-player registry. Each entry: { nid, kind, videoEl, player? }
152
+ // where `player` is the host/lazy adapter (has destroy()). The native handle
153
+ // has no player object (the child element owns the source).
154
+ var registry = new Map();
155
+
156
+ /**
157
+ * Contained host-callback invoker (mirrors safeInvokeMediaHook): a throwing
158
+ * onMediaUnavailable is routed to the logger and never rethrown.
159
+ * @param {?string} nid
160
+ * @param {string} reason
161
+ */
162
+ function safeInvokeMediaHook(nid, reason) {
163
+ if (typeof d.onMediaUnavailable !== 'function') return;
164
+ try {
165
+ d.onMediaUnavailable(nid, reason);
166
+ } catch (err) {
167
+ logger.error('[Renderer] onMediaUnavailable callback failed', nid, reason, err);
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Tear down the live player for nid: destroy any host/lazy adapter, and reset
173
+ * the inert child element (removeAttribute('src') + load()). All steps are
174
+ * individually guarded -- teardown never throws. Idempotent.
175
+ * @param {?string} nid
176
+ */
177
+ function destroy(nid) {
178
+ var entry = registry.get(nid);
179
+ if (entry) {
180
+ if (entry.player && typeof entry.player.destroy === 'function') {
181
+ try { entry.player.destroy(); } catch (e) { /* contained */ }
182
+ }
183
+ var el = entry.videoEl;
184
+ if (el) {
185
+ try { if (typeof el.removeAttribute === 'function') el.removeAttribute('src'); } catch (e) { /* contained */ }
186
+ try { if (typeof el.load === 'function') el.load(); } catch (e) { /* contained */ }
187
+ }
188
+ registry.delete(nid);
189
+ }
190
+ }
191
+
192
+ /** Destroy every live player (Plan 03 calls this on a re-snapshot). */
193
+ function destroyAll() {
194
+ var nids = [];
195
+ registry.forEach(function (_entry, nid) { nids.push(nid); });
196
+ nids.forEach(destroy);
197
+ }
198
+
199
+ /**
200
+ * The single degrade sink -- every unmirrorable path routes here. Tears down
201
+ * the live player for nid, shows the passive media-unavailable overlay over
202
+ * the element rect, and invokes the contained onMediaUnavailable host hook.
203
+ * The element keeps its poster (if present) else the Phase-12 placeholder.
204
+ * NEVER throws.
205
+ * @param {?string} nid
206
+ * @param {string} reason no-manifest | no-player | mse-opaque | drm
207
+ * @returns {undefined}
208
+ */
209
+ function degrade(nid, reason) {
210
+ destroy(nid);
211
+ if (typeof d.showOverlay === 'function') {
212
+ var anchorRect = (typeof d.resolveNidRect === 'function') ? d.resolveNidRect(nid) : null;
213
+ try {
214
+ d.showOverlay('media-unavailable', { nid: nid, reason: reason }, { anchorRect: anchorRect });
215
+ } catch (e) {
216
+ logger.error('[Renderer] media-unavailable overlay failed', nid, reason, e);
217
+ }
218
+ }
219
+ if (typeof d.keepPoster === 'function') {
220
+ try { d.keepPoster(nid); } catch (e) { /* contained */ }
221
+ }
222
+ safeInvokeMediaHook(nid, reason);
223
+ return undefined;
224
+ }
225
+
226
+ /**
227
+ * The optional lazy hls.js branch (HLS only, no playerFactory). Feature-detects
228
+ * MSE, dynamic-imports hls.js, wires the DRM + fatal-error degrade paths, then
229
+ * loadSource() BEFORE attachMedia() (the documented happy path). Self-degrades
230
+ * on every failure; never rethrows.
231
+ * @param {HTMLMediaElement} videoEl
232
+ * @param {string} manifestUrl
233
+ * @param {PlayerAdapterCtx} ctx
234
+ * @returns {Promise<Object|undefined>} a hls handle, or undefined after degrade
235
+ */
236
+ async function attachViaLazyHls(videoEl, manifestUrl, ctx) {
237
+ var win = d.win || (ctx.doc && ctx.doc.defaultView) || null;
238
+ if (!canUseMse(win)) return degrade(ctx.nid, 'mse-opaque');
239
+ var Hls = await lazyImportHls();
240
+ if (!Hls || typeof Hls.isSupported !== 'function' || !Hls.isSupported()) {
241
+ return degrade(ctx.nid, 'no-player');
242
+ }
243
+ try {
244
+ // emeEnabled stays FALSE (DRM is never attempted -- T-14-05). We pass an
245
+ // explicit config WITHOUT emeEnabled so it can never be true.
246
+ var hls = new Hls({});
247
+ // The cheapest reliable DRM signal: the child element's 'encrypted' event.
248
+ // Hold the NAMED handler so destroy() can remove it -- an anonymous closure
249
+ // could never be unregistered, leaving the listener armed on the still-live
250
+ // child after teardown so a late 'encrypted' would re-degrade a torn-down
251
+ // nid (re-showing the overlay + re-invoking onMediaUnavailable for an
252
+ // element the player no longer owns). { once: true } still bounds a live
253
+ // fire to one; removal makes a post-teardown fire a no-op (WR-04).
254
+ var onEncrypted = function () { degrade(ctx.nid, 'drm'); };
255
+ videoEl.addEventListener('encrypted', onEncrypted, { once: true });
256
+ hls.on(Hls.Events.ERROR, function (_e, info) {
257
+ if (!info || !info.fatal) return;
258
+ degrade(ctx.nid, (info.type === Hls.ErrorTypes.KEY_SYSTEM_ERROR) ? 'drm' : 'mse-opaque');
259
+ });
260
+ hls.loadSource(manifestUrl); // LOAD first
261
+ hls.attachMedia(videoEl); // THEN attach the bare in-iframe element
262
+ var player = { destroy: function () {
263
+ // Remove the DRM listener FIRST so a late 'encrypted' after teardown is
264
+ // a no-op, then destroy hls (which revokes the parent-realm object URL
265
+ // it minted -- the no-leak property, IN-01). Both steps are contained.
266
+ try {
267
+ if (typeof videoEl.removeEventListener === 'function') {
268
+ videoEl.removeEventListener('encrypted', onEncrypted);
269
+ }
270
+ } catch (e) { /* contained */ }
271
+ try { hls.destroy(); } catch (e) { /* contained */ }
272
+ } };
273
+ registry.set(ctx.nid, { nid: ctx.nid, kind: 'hls', videoEl: videoEl, player: player });
274
+ return { kind: 'hls', hls: hls, player: player };
275
+ } catch (e) {
276
+ return degrade(ctx.nid, 'mse-opaque');
277
+ }
278
+ }
279
+
280
+ /**
281
+ * The host playerFactory branch -- the host owns MSE/attachMedia/segment fetch
282
+ * internally. Wires the adapter's optional onError to the degrade sink and
283
+ * records the live player for teardown.
284
+ * @param {HTMLMediaElement} videoEl
285
+ * @param {string} manifestUrl
286
+ * @param {PlayerAdapterCtx} ctx
287
+ * @returns {Object} a factory handle
288
+ */
289
+ function attachViaFactory(videoEl, manifestUrl, ctx) {
290
+ var player = d.playerFactory(ctx);
291
+ registry.set(ctx.nid, { nid: ctx.nid, kind: ctx.kind, videoEl: videoEl, player: player });
292
+ if (player && typeof player.onError === 'function') {
293
+ player.onError(function (reason) { degrade(ctx.nid, reason || 'mse-opaque'); });
294
+ }
295
+ // attach() may throw -- the caller's try/catch contains it to mse-opaque.
296
+ player.attach(videoEl, manifestUrl, ctx);
297
+ return { kind: 'factory', player: player };
298
+ }
299
+
300
+ /**
301
+ * Run the attachment decision tree for one media element. SYNCHRONOUS for the
302
+ * native / factory / no-MSE / dash-no-factory / no-manifest branches (so a
303
+ * caller that does not await still observes the degrade); the lazy-hls branch
304
+ * returns a Promise. The whole body is try/catch-contained -> degrade(
305
+ * 'mse-opaque') on ANY throw; NEVER rethrows.
306
+ * @param {HTMLMediaElement} videoEl the in-iframe child element
307
+ * @param {string} manifestUrl
308
+ * @param {Object} [ctx] { nid?, contentType? }
309
+ * @returns {Object|Promise<Object|undefined>|undefined} a handle, a promise, or undefined after degrade
310
+ */
311
+ function attach(videoEl, manifestUrl, ctx) {
312
+ var c = ctx || {};
313
+ var nid = (c.nid !== undefined) ? c.nid : null;
314
+ try {
315
+ // 1. GATE -- blocked manifest origin is unmirrorable.
316
+ var gate = (typeof d.gateAsset === 'function') ? d.gateAsset(manifestUrl, 'media') : { allow: true };
317
+ if (!gate || !gate.allow) return degrade(nid, 'no-manifest');
318
+
319
+ var kind = classifyManifest({ url: manifestUrl, contentType: c.contentType });
320
+
321
+ // 2. NATIVE HLS FIRST -- no MSE, no library, no parent player.
322
+ if (isNativeHls(videoEl, kind)) {
323
+ videoEl.src = manifestUrl; // cross-realm attribute set on the child el
324
+ registry.set(nid, { nid: nid, kind: 'native', videoEl: videoEl });
325
+ if (typeof d.ensurePlaying === 'function') d.ensurePlaying(videoEl, nid); // REUSE Phase 13
326
+ return { kind: 'native' };
327
+ }
328
+
329
+ // The full PlayerAdapterCtx the factory / lazy path receive.
330
+ var playerCtx = {
331
+ doc: d.doc,
332
+ manifestUrl: manifestUrl,
333
+ kind: kind,
334
+ videoEl: videoEl,
335
+ logger: logger,
336
+ gateAsset: d.gateAsset,
337
+ nid: nid
338
+ };
339
+
340
+ // 3. HOST playerFactory (DASH + custom + HLS) when provided.
341
+ if (typeof d.playerFactory === 'function') {
342
+ return attachViaFactory(videoEl, manifestUrl, playerCtx);
343
+ }
344
+
345
+ // 4. OPTIONAL LAZY hls.js (HLS only, no factory). Async; self-degrades.
346
+ if (kind === 'hls') {
347
+ return attachViaLazyHls(videoEl, manifestUrl, playerCtx);
348
+ }
349
+
350
+ // 5. DASH (.mpd) with no factory.
351
+ if (kind === 'dash') return degrade(nid, 'no-player');
352
+
353
+ // 6. anything unhandled (no classifiable manifest).
354
+ return degrade(nid, 'no-manifest');
355
+ } catch (e) {
356
+ // ANY throw -> poster, never break (T-14-07).
357
+ return degrade(nid, 'mse-opaque');
358
+ }
359
+ }
360
+
361
+ return {
362
+ attach: attach,
363
+ degrade: degrade,
364
+ destroy: destroy,
365
+ destroyAll: destroyAll
366
+ };
367
+ }