@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
@@ -29,6 +29,18 @@ export const TRUNCATION_VIEWPORT_MULTIPLIER = 3;
29
29
  /** Scroll side-channel throttle: at most one event per this many ms. */
30
30
  export const SCROLL_THROTTLE_MS = 200;
31
31
 
32
+ /**
33
+ * Media side-channel heartbeat throttle: while a tracked <video>/<audio> is
34
+ * playing, a `timeupdate` heartbeat (STREAM.MEDIA) is emitted at most once per
35
+ * this many ms for drift correction. 250 ms is a practice-based co-watching
36
+ * cadence (~4 Hz) -- frequent enough for the reconciler to converge sub-second
37
+ * drift, sparse enough to stay well under the relay cap. Discrete transitions
38
+ * (play/pause/seeked/ratechange/ended/volumechange/loadedmetadata) bypass this
39
+ * throttle and flush immediately; the value is tunable against the v2.1
40
+ * evaluation harness (Phase 13 concern).
41
+ */
42
+ export const MEDIA_SYNC_THROTTLE_MS = 250;
43
+
32
44
  /** Overlay side-channel throttle: at most one broadcast per this many ms. */
33
45
  export const OVERLAY_THROTTLE_MS = 500;
34
46
 
@@ -47,3 +59,15 @@ export const READY_PROBE_BUDGET_MS = 5000;
47
59
 
48
60
  /** Inline <style> tags larger than this are skipped during snapshot capture. */
49
61
  export const INLINE_STYLE_MAX_BYTES = 500000;
62
+
63
+ /**
64
+ * Maximum UTF-8 byte length of an inline `data:` image URI that capture will
65
+ * emit verbatim on the wire. 262144 = 256 KiB -- roughly a quarter of the
66
+ * per-message cap headroom (SNAPSHOT_BUDGET_BYTES is ~838 KiB, the 80%
67
+ * truncation budget of the 1 MiB relay cap), so a single inline asset cannot
68
+ * crowd out the rest of the snapshot. A `data:` image larger than this degrades
69
+ * to a dimensioned placeholder; small inline icons/sprites (<= cap) pass through
70
+ * byte-identical, preserving the existing `data:image/*` pass-through and the
71
+ * differential oracle. (Phase 12 ASST-04.)
72
+ */
73
+ export const ASSET_DATA_URI_MAX_BYTES = 262144; // 256 KiB
@@ -2,3 +2,4 @@ export * from './constants.js';
2
2
  export * from './messages.js';
3
3
  export * from './envelope.js';
4
4
  export * from './remote-control.js';
5
+ export * from './media-reconcile.js';
@@ -0,0 +1,188 @@
1
+ // Pure drift reconciler for media-playback sync (Phase 13: MWIRE-02, MEDIA-03).
2
+ //
3
+ // reconcileMediaDrift(local, remote, now, config) is a PURE function over plain
4
+ // objects: no DOM, no media element, no clock read inside (the caller passes
5
+ // `now`), and ZERO imports (the zero-dependency protocol invariant). That purity
6
+ // is what makes it jsdom-unit-testable with no real media timeline -- the whole
7
+ // MWIRE-02 contract.
8
+ //
9
+ // It is the phase's novel contribution over rrweb's MediaManager: rrweb
10
+ // interpolates the expected position with `currentTime + rate*elapsed` and then
11
+ // ALWAYS hard-seeks. PhantomStream keeps that interpolation but adds a tolerance
12
+ // band + a bounded temporary rate-nudge (so small drift converges smoothly
13
+ // instead of snapping) and a live-edge rejoin (so streams never absolute-seek).
14
+ //
15
+ // The returned action is a plain object { action, ... } where action is one of
16
+ // hold | pause | nudge | seek | rejoin-edge. The DRIVER (renderer, Plan 03)
17
+ // decides whether to apply it; the reconciler itself is side-effect-free and
18
+ // keeps NO internal memory -- whether a nudge is currently applied is read back
19
+ // from local.playbackRate vs remote.playbackRate on the next call.
20
+
21
+ /**
22
+ * @typedef {Object} MediaReconcileConfig
23
+ * @property {number} holdBandSec In-tolerance band (s); within this, hold. Default 0.25
24
+ * @property {number} hardSeekSec Hard-seek threshold (s); above this, seek. Default 1.0
25
+ * @property {number} maxNudgeFraction Max temporary rate delta (fraction). Default 0.05
26
+ * @property {number} liveRejoinSec Live-edge rejoin threshold (s). Default 1.0
27
+ */
28
+
29
+ /** Locked defaults (13-CONTEXT); tunable against the v2.1 evaluation harness. */
30
+ export var DEFAULT_MEDIA_RECONCILE_CONFIG = {
31
+ holdBandSec: 0.25, // |drift| <= this -> hold (no correction)
32
+ hardSeekSec: 1.0, // |drift| > this -> hard-seek to the clamped expected position
33
+ maxNudgeFraction: 0.05, // (0.25, 1.0] band nudges playbackRate by at most +/- this
34
+ liveRejoinSec: 1.0 // live streams rejoin the edge only when drift exceeds this
35
+ };
36
+
37
+ /** Is v a usable finite number? Rejects NaN, +/-Infinity, null, undefined, non-numbers. */
38
+ function isFiniteNum(v) {
39
+ return typeof v === 'number' && isFinite(v);
40
+ }
41
+
42
+ /**
43
+ * Merge a partial config over the locked defaults so a missing field can never
44
+ * leave a threshold `undefined` (which would make every comparison NaN). Only
45
+ * finite overrides are accepted; anything else falls back to the default.
46
+ * @param {Partial<MediaReconcileConfig>} [config]
47
+ * @returns {MediaReconcileConfig}
48
+ */
49
+ function mergeConfig(config) {
50
+ var d = DEFAULT_MEDIA_RECONCILE_CONFIG;
51
+ var c = config || {};
52
+ return {
53
+ holdBandSec: isFiniteNum(c.holdBandSec) ? c.holdBandSec : d.holdBandSec,
54
+ hardSeekSec: isFiniteNum(c.hardSeekSec) ? c.hardSeekSec : d.hardSeekSec,
55
+ maxNudgeFraction: isFiniteNum(c.maxNudgeFraction) ? c.maxNudgeFraction : d.maxNudgeFraction,
56
+ liveRejoinSec: isFiniteNum(c.liveRejoinSec) ? c.liveRejoinSec : d.liveRejoinSec
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Clamp a seek target into [0, duration]. When duration is non-finite or absent,
62
+ * only the lower bound applies (the live branch handles streams before this is
63
+ * ever called for an absolute seek). Always returns a finite number.
64
+ * @param {number} t
65
+ * @param {number} duration
66
+ * @returns {number}
67
+ */
68
+ function clampToDuration(t, duration) {
69
+ var lo = isFiniteNum(t) ? t : 0;
70
+ if (lo < 0) lo = 0;
71
+ if (isFiniteNum(duration) && lo > duration) lo = duration;
72
+ return lo;
73
+ }
74
+
75
+ /**
76
+ * Loop-wrap detector: a looping element where the local position is near the end
77
+ * of the timeline while the expected position has wrapped to near the start (or
78
+ * vice versa). This produces a huge raw |drift| that must NOT trigger a spurious
79
+ * hard-seek across the whole timeline; instead the driver seeks to the wrapped
80
+ * position. The wrap window is a fraction of duration, floored at the hard-seek
81
+ * threshold so tiny clips still register a wrap.
82
+ * @param {number} localTime
83
+ * @param {number} expected
84
+ * @param {number} duration
85
+ * @param {MediaReconcileConfig} cfg
86
+ * @returns {boolean}
87
+ */
88
+ function isLoopWrap(localTime, expected, duration, cfg) {
89
+ if (!isFiniteNum(duration) || duration <= 0) return false;
90
+ if (!isFiniteNum(localTime) || !isFiniteNum(expected)) return false;
91
+ // Window near each edge of the timeline.
92
+ var window = Math.max(cfg.hardSeekSec, duration * 0.1);
93
+ if (window >= duration / 2) return false; // timeline too short to distinguish ends
94
+ var localNearEnd = localTime >= duration - window;
95
+ var localNearStart = localTime <= window;
96
+ var expectedNearEnd = expected >= duration - window;
97
+ var expectedNearStart = expected <= window;
98
+ return (localNearEnd && expectedNearStart) || (localNearStart && expectedNearEnd);
99
+ }
100
+
101
+ /**
102
+ * Decide the single drift-correction action for one media element.
103
+ *
104
+ * Decision order (RESEARCH Pattern 1, exact):
105
+ * merge cfg -> incomplete-remote guard -> explicit `seeked` short-circuit ->
106
+ * paused/rate-0 -> NaN local guard -> latency-compensated `expected` (elapsed
107
+ * clamped >= 0) -> LIVE branch (before any duration math) -> VOD: loop-wrap ->
108
+ * hold band (carries revertRate) -> bounded sign-correct nudge (carries
109
+ * baseRate) -> hard-seek (clamp toTime into [0, duration]).
110
+ *
111
+ * @param {{currentTime?: number, paused?: boolean, playbackRate?: number}} local Observed element state
112
+ * @param {import('./messages.js').MediaSyncPayload|null} remote Latency-uncompensated captured state
113
+ * @param {number} now Caller clock (ms), e.g. performance.now()-equivalent
114
+ * @param {Partial<MediaReconcileConfig>} [config] Overrides merged over DEFAULT_MEDIA_RECONCILE_CONFIG
115
+ * @returns {{action:'hold'|'pause'|'nudge'|'seek'|'rejoin-edge', toTime?:number, rate?:number, baseRate?:number, revertRate?:number, reason?:string}}
116
+ */
117
+ export function reconcileMediaDrift(local, remote, now, config) {
118
+ var cfg = mergeConfig(config);
119
+
120
+ // ---- 0. guard incomplete / non-finite remote (no NaN propagation) ----
121
+ if (!remote || remote.currentTime == null ||
122
+ !isFiniteNum(remote.currentTime) || !isFiniteNum(remote.sentAt)) {
123
+ return { action: 'hold', reason: 'incomplete-remote' };
124
+ }
125
+
126
+ // ---- 1. explicit seek short-circuits everything (CONTEXT: always hard-seek) ----
127
+ if (remote.event === 'seeked') {
128
+ return { action: 'seek', toTime: clampToDuration(remote.currentTime, remote.duration) };
129
+ }
130
+
131
+ // ---- 2. paused / rate-0: mirror pause, never interpolate position ----
132
+ if (remote.paused === true || remote.playbackRate === 0) {
133
+ return (local && local.paused)
134
+ ? { action: 'hold', reason: 'paused' }
135
+ : { action: 'pause' };
136
+ }
137
+
138
+ // ---- 3. NaN local (element not ready): wait for readiness ----
139
+ var localTime = (local && isFiniteNum(local.currentTime)) ? local.currentTime : null;
140
+ if (localTime === null) {
141
+ return { action: 'hold', reason: 'local-not-ready' };
142
+ }
143
+
144
+ // ---- 4. latency-compensated expected position (playing only) ----
145
+ var elapsedSec = Math.max(0, (now - remote.sentAt) / 1000); // negative clock skew -> 0
146
+ if (!isFiniteNum(elapsedSec)) elapsedSec = 0;
147
+ var rate = isFiniteNum(remote.playbackRate) && remote.playbackRate > 0 ? remote.playbackRate : 1;
148
+ var expected = remote.currentTime + rate * elapsedSec;
149
+
150
+ // ---- 5. LIVE branch: before ANY duration arithmetic; never absolute-seek ----
151
+ if (remote.live === true || !isFiniteNum(remote.duration)) {
152
+ var liveDrift = Math.abs(expected - localTime);
153
+ return liveDrift > cfg.liveRejoinSec
154
+ ? { action: 'rejoin-edge' }
155
+ : { action: 'hold', reason: 'live-in-band' };
156
+ }
157
+
158
+ // ---- 6. VOD branch (duration is finite here by construction) ----
159
+ var duration = remote.duration;
160
+
161
+ // duration 0 is a non-seekable timeline: never seek into it.
162
+ if (duration <= 0) {
163
+ return { action: 'hold', reason: 'zero-duration' };
164
+ }
165
+
166
+ // loop wrap: seek to the wrapped position, not the raw (huge) delta.
167
+ if (remote.loop === true && isLoopWrap(localTime, expected, duration, cfg)) {
168
+ return { action: 'seek', toTime: clampToDuration(expected, duration) };
169
+ }
170
+
171
+ var drift = expected - localTime;
172
+ var adrift = Math.abs(drift);
173
+
174
+ // hold band: carry revertRate so the driver restores the true rate if a nudge was active.
175
+ if (adrift <= cfg.holdBandSec) {
176
+ return { action: 'hold', reason: 'in-band', revertRate: rate };
177
+ }
178
+
179
+ // (holdBandSec, hardSeekSec]: bounded, sign-correct temporary rate nudge.
180
+ if (adrift <= cfg.hardSeekSec) {
181
+ var sign = drift > 0 ? 1 : -1; // behind (expected ahead) -> speed up; ahead -> slow down
182
+ var nudgeRate = rate * (1 + sign * cfg.maxNudgeFraction);
183
+ return { action: 'nudge', rate: nudgeRate, baseRate: rate };
184
+ }
185
+
186
+ // adrift > hardSeekSec: hard-seek to the clamped expected position.
187
+ return { action: 'seek', toTime: clampToDuration(expected, duration) };
188
+ }
@@ -21,6 +21,10 @@ export const STREAM = {
21
21
  MUTATIONS: 'ext:dom-mutations',
22
22
  /** Scroll position. Payload: { scrollX, scrollY, streamSessionId, snapshotId } */
23
23
  SCROLL: 'ext:dom-scroll',
24
+ /** Media playback state. Payload: MediaSyncPayload */
25
+ MEDIA: 'ext:dom-media',
26
+ /** Adaptive-manifest discovery hint (opt-in, adapter-originated). Payload: MediaHintPayload */
27
+ MEDIA_HINT: 'ext:dom-media-hint',
24
28
  /** Automation overlay state. Payload: { glow, progress, streamSessionId, snapshotId } */
25
29
  OVERLAY: 'ext:dom-overlay',
26
30
  /** Native dialog mirroring. Payload: { dialog: DialogPayload } */
@@ -67,7 +71,7 @@ export const DIFF_OP = {
67
71
  ATTR: 'attr',
68
72
  /** { op:'text', nid, text } — character data change, addressed via parent nid */
69
73
  TEXT: 'text',
70
- /** { op:'value', nid, value?, checked?, selectedValues? } — live form state change */
74
+ /** { op:'value', nid, value?, checked?, selectedValues?, selectedIndexes? } — live form state change */
71
75
  VALUE: 'value',
72
76
  /** ShadowRootPayload plus op:'shadow-root' — replace/open an observed shadow root */
73
77
  SHADOW_ROOT: 'shadow-root',
@@ -171,7 +175,84 @@ export const NID_ATTR = 'data-fsb-nid';
171
175
  * @property {string} nid
172
176
  * @property {string} [value] Textual value for input/textarea/select-like controls
173
177
  * @property {boolean} [checked] Checked state for checkbox/radio controls
174
- * @property {string[]} [selectedValues] Selected option values for multi-select controls
178
+ * @property {string[]} [selectedValues] Selected option values for select controls (masked when maskInputs is on, so renderers must not treat these as a selection key)
179
+ * @property {number[]} [selectedIndexes] Authoritative positional identity of selected options; preferred over selectedValues because option indexes never carry page content and stay unambiguous under masking
180
+ */
181
+
182
+ /**
183
+ * Captured live playback state of a single <video>/<audio> element, keyed by
184
+ * nid. Models the DIFF_OP.VALUE side-channel-property-state precedent: live
185
+ * media properties travel as side-channel data, never serialized into the HTML
186
+ * clone (preserves the Phase 7 no-mutation invariant + HTML byte-identity).
187
+ *
188
+ * Live/Infinity-duration encoding: `duration` is present ONLY when finite;
189
+ * non-finite (streaming) durations are encoded as `live: true` instead, never
190
+ * both. This sidesteps the JSON Infinity -> null trap (JSON.stringify(Infinity)
191
+ * === "null") so the reconciler can branch on `live` before any duration math
192
+ * and never compute NaN.
193
+ *
194
+ * @typedef {Object} MediaBaselineEntry
195
+ * @property {string} nid Element nid the playback state addresses
196
+ * @property {number} currentTime Playback position in seconds
197
+ * @property {boolean} paused Whether the element is paused
198
+ * @property {boolean} muted Whether audio output is muted
199
+ * @property {number} volume Audio volume in [0, 1]
200
+ * @property {number} playbackRate Effective playback rate (1 = normal)
201
+ * @property {boolean} loop Whether the element loops
202
+ * @property {boolean} ended Whether playback reached the end
203
+ * @property {number} [duration] Media duration in seconds; present ONLY when finite
204
+ * @property {boolean} [live] true when duration is non-finite (stream); mutually exclusive with duration
205
+ */
206
+
207
+ /**
208
+ * One STREAM.MEDIA wire message: a MediaBaselineEntry enriched with the event
209
+ * that triggered emission, a capture-side monotonic timestamp for latency
210
+ * compensation, and the stream identity stamps every side channel carries.
211
+ *
212
+ * The reconciler predicts the expected position from `currentTime`,
213
+ * `playbackRate`, and `(now - sentAt)`; `streamSessionId`/`snapshotId` let the
214
+ * renderer reject stale cross-generation frames via isCurrentStream (Plan 03).
215
+ * One message is emitted per media element per tick (scroll-like granularity).
216
+ *
217
+ * @typedef {Object} MediaSyncPayload
218
+ * @property {string} nid Element nid the playback state addresses
219
+ * @property {'play'|'pause'|'seeked'|'ratechange'|'ended'|'volumechange'|'loadedmetadata'|'timeupdate'} event Triggering media event
220
+ * @property {number} currentTime Playback position in seconds at capture
221
+ * @property {boolean} paused Whether the element is paused
222
+ * @property {boolean} muted Whether audio output is muted
223
+ * @property {number} volume Audio volume in [0, 1]
224
+ * @property {number} playbackRate Effective playback rate (1 = normal)
225
+ * @property {boolean} loop Whether the element loops
226
+ * @property {boolean} ended Whether playback reached the end
227
+ * @property {number} [duration] Media duration in seconds; present ONLY when finite
228
+ * @property {boolean} [live] true when duration is non-finite (stream); mutually exclusive with duration
229
+ * @property {number} sentAt Capture-side monotonic ms stamp for latency compensation
230
+ * @property {string} streamSessionId Identity: minted per stream session
231
+ * @property {number} snapshotId Identity: minted per snapshot
232
+ */
233
+
234
+ /**
235
+ * One adaptive-manifest discovery hint surfaced by an adapter's opt-in network
236
+ * observation (Playwright `page.on('response')` / extension `chrome.webRequest`).
237
+ * The hint originates in the ADAPTER, never the capture core, so it adds no
238
+ * capture-wire divergence (no differential-oracle entry); it rides the existing
239
+ * raw relay + 1 MiB cap with the envelope byte-unchanged, and old viewers ignore
240
+ * the unknown STREAM.MEDIA_HINT type via the renderer dispatch default.
241
+ *
242
+ * Addressing is nid-scoped when manifest->element correlation is confident, else
243
+ * page-scoped (nid omitted, scope 'page'); a page hint is matched to an
244
+ * MSE-opaque media element on play by the viewer. Identity-stamped like every
245
+ * side channel; the viewer re-gates `manifestUrl` through the same fail-closed
246
+ * origin policy before any use.
247
+ *
248
+ * @typedef {Object} MediaHintPayload
249
+ * @property {string} [nid] Element nid when correlation is confident; omitted for page-level
250
+ * @property {'page'|'element'} scope 'element' (nid set) or 'page' (viewer matches on play)
251
+ * @property {string} manifestUrl Absolute manifest URL (https; viewer re-gates before use)
252
+ * @property {'hls'|'dash'} kind Derived from URL extension and/or content-type
253
+ * @property {string} [contentType] Observed response content-type (diagnostic)
254
+ * @property {string} streamSessionId Identity: minted per stream session
255
+ * @property {number} snapshotId Identity: minted per snapshot
175
256
  */
176
257
 
177
258
  /**
@@ -266,3 +347,65 @@ export function isCurrentStream(msg, active) {
266
347
  }
267
348
  return true;
268
349
  }
350
+
351
+ // HLS content-type tokens (lowercased, charset-stripped before compare). DASH
352
+ // is the single application/dash+xml token below. CDNs frequently serve
353
+ // extensionless or signed manifest URLs, so the content-type is the more
354
+ // robust of the two signals.
355
+ const HLS_CONTENT_TYPES = {
356
+ 'application/vnd.apple.mpegurl': true,
357
+ 'application/x-mpegurl': true,
358
+ 'audio/mpegurl': true,
359
+ 'audio/x-mpegurl': true,
360
+ };
361
+ const DASH_CONTENT_TYPE = 'application/dash+xml';
362
+
363
+ /**
364
+ * Extract a lowercased URL path, ignoring query/hash, defensively. A malformed
365
+ * url never throws: a `new URL()` failure falls back to a regex strip of the
366
+ * first `?`/`#` (mirrors the isHlsManifest defensiveness in 14-RESEARCH). A
367
+ * non-string url yields an empty path.
368
+ * @param {*} url
369
+ * @returns {string} lowercased path (or '' on failure)
370
+ */
371
+ function manifestPathOf(url) {
372
+ if (typeof url !== 'string' || url === '') return '';
373
+ try {
374
+ return new URL(url).pathname.toLowerCase();
375
+ } catch (e) {
376
+ // Not an absolute/parseable URL: strip query + hash, then lowercase.
377
+ return String(url).split('#')[0].split('?')[0].toLowerCase();
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Pure manifest classifier: is an observed response an adaptive-streaming
383
+ * manifest, and of which kind? Returns `'hls'` for an `.m3u8` path OR an HLS
384
+ * content-type; `'dash'` for an `.mpd` path OR `application/dash+xml`; `null`
385
+ * otherwise. URL-OR-content-type: either signal is independently sufficient.
386
+ *
387
+ * Never throws (T-14-03): a malformed/hostile url string is a guarded `null`
388
+ * (or a regex-fallback classification when the extension is still discernible),
389
+ * so it can never wedge the adapter. Project convention: a pure helper returns
390
+ * a primitive, not the `{ok,...}` fallible shape.
391
+ *
392
+ * @param {{url?: string, contentType?: string}} [input]
393
+ * @returns {'hls'|'dash'|null}
394
+ */
395
+ export function classifyManifest(input) {
396
+ if (!input) return null;
397
+ // Content-type first (the more robust signal): lowercase, drop the ;charset.
398
+ const ct = (typeof input.contentType === 'string' ? input.contentType : '')
399
+ .split(';')[0].trim().toLowerCase();
400
+ if (ct) {
401
+ if (HLS_CONTENT_TYPES[ct]) return 'hls';
402
+ if (ct === DASH_CONTENT_TYPE) return 'dash';
403
+ }
404
+ // URL path extension (query/hash ignored; malformed url -> guarded).
405
+ const path = manifestPathOf(input.url);
406
+ if (path) {
407
+ if (/\.m3u8$/.test(path)) return 'hls';
408
+ if (/\.mpd$/.test(path)) return 'dash';
409
+ }
410
+ return null;
411
+ }
@@ -0,0 +1,172 @@
1
+ // PhantomStream renderer: pure fail-closed asset-origin classifier.
2
+ //
3
+ // v2.0 (Phase 12, MSEC-01) changes the viewer's verb from render-inert to
4
+ // FETCH: a mirrored <img>/<source>/poster/background-image causes the
5
+ // viewer's own browser to issue a GET from the viewer's (possibly
6
+ // privileged) network. This module is the SEPARATE fetch control that
7
+ // decides which asset origins the viewer may reach. It is distinct from the
8
+ // injection control hasDangerousScheme (sanitize.js): that one asks "can
9
+ // this URL execute script?"; this one asks "is this origin safe for the
10
+ // viewer to FETCH?" -- http(s) to an internal host (169.254.169.254,
11
+ // 10.x, an unqualified intranet name) passes the injection check yet is a
12
+ // blind-SSRF/tracking surface, which is exactly what this classifier blocks.
13
+ //
14
+ // Pure by contract: no DOM access, no network, no module-level side effects.
15
+ // new URL(...) is the only platform dependency (already load-bearing in the
16
+ // capture core's absolutifyUrl). This purity is deliberate so Phase 15
17
+ // (asset/media URL masking) can reuse the very same classifier seam against
18
+ // which it completes the masking vocabulary.
19
+ //
20
+ // Fail-closed and loud: anything not provably public-https -- a parse error,
21
+ // a non-https scheme, a private/internal/loopback/link-local/ULA host, or an
22
+ // unqualified/.local name -- returns { allowed: false, reason }. The default
23
+ // posture is conservative; the host WIDENS it via the renderer's
24
+ // assetOriginPolicy hook / allowAssetOrigins allowlist (see index.js
25
+ // gateAssetUrl), never by relaxing this function.
26
+ //
27
+ // Denylist (12-CONTEXT, locked): scheme MUST be https:; deny localhost,
28
+ // 0.0.0.0/8 ("this host", RFC 1122 -- SSRF to loopback on Linux),
29
+ // 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16,
30
+ // ::1, fc00::/7 (fc.. or fd..), and .local / unqualified (dotless) hosts.
31
+
32
+ /**
33
+ * @typedef {Object} AssetOriginVerdict
34
+ * @property {boolean} allowed True only for a provably public https origin.
35
+ * @property {string} reason One of 'ok' | 'bad-scheme' | 'private-host'
36
+ * | 'unqualified-host' | 'parse-error'.
37
+ */
38
+
39
+ /**
40
+ * True when a (lowercased) hostname names a private, internal, loopback,
41
+ * link-local, or ULA address -- i.e. a host the viewer must never fetch from
42
+ * by default. Pure string/regex logic over the fixed, fully-enumerable
43
+ * denylist (RFC1918 + RFC3927 link-local + loopback + RFC4193 ULA + the
44
+ * mDNS .local suffix); a dependency-free hand-roll is preferred here over an
45
+ * IP library so the predicate stays Phase-15-reusable and table-testable.
46
+ *
47
+ * Bracketed IPv6 literals: WHATWG URL keeps the surrounding brackets on
48
+ * u.hostname (verified: new URL('https://[::1]/').hostname === '[::1]'), so
49
+ * the brackets are stripped here before the IPv6 checks match the bare
50
+ * address form. (.local is intentionally NOT handled here -- it is the
51
+ * unqualified-host branch's job in classifyAssetOrigin so a *.local name
52
+ * classifies as 'unqualified-host', not 'private-host'.)
53
+ *
54
+ * SELF-CONTAINED NORMALIZATION (Phase 12 review CR-01/WR-01): this predicate
55
+ * is an exported Phase-15-reusable seam, so it must NOT depend on the caller
56
+ * having pre-normalized the host through WHATWG `new URL()`. A single trailing
57
+ * dot (the FQDN root label -- 'localhost.', '127.0.0.1.') is stripped, the host
58
+ * is lowercased, and any IPv6 zone-id ('%eth0') is dropped here so a raw
59
+ * `Host:` header / CSS url() host / media URL host cannot bypass the deny
60
+ * decision. Beyond the IPv4 dotted-quad ranges this blocks IPv6 loopback
61
+ * (`::1`), the unspecified address (`::`), link-local fe80::/10, ULA fc00::/7,
62
+ * the NAT64 well-known prefix 64:ff9b::/96, and IPv4-mapped / IPv4-compatible
63
+ * IPv6 (`::ffff:a.b.c.d`, `::ffff:HHHH:HHHH`, `::a.b.c.d`) by extracting the
64
+ * embedded IPv4 and re-running the v4 ranges -- so the AWS/GCP/Azure metadata
65
+ * host 169.254.169.254 and 127.0.0.1 are blocked in every representation. The
66
+ * milestone has no use case for fetching from a raw IP literal, so this stays
67
+ * fail-closed: an IP-literal form it cannot confidently prove public is denied.
68
+ *
69
+ * @param {string} host Lowercased hostname (u.hostname) OR a raw host string.
70
+ * @returns {boolean}
71
+ */
72
+ export function isPrivateOrLocalHost(host) {
73
+ if (!host || typeof host !== 'string') return true; // fail closed on no host
74
+ // Normalize independent of any caller pre-normalization (CR-01/WR-01):
75
+ // lowercase, then strip a single trailing FQDN-root dot so 'localhost.' and
76
+ // '127.0.0.1.' cannot slip past the equality/regex checks below.
77
+ var normalized = host.toLowerCase();
78
+ if (normalized.length > 1 && normalized.charAt(normalized.length - 1) === '.') {
79
+ normalized = normalized.slice(0, -1);
80
+ }
81
+ if (normalized === 'localhost') return true;
82
+ // Strip the brackets WHATWG URL keeps on IPv6 literal hostnames so the
83
+ // bare-address IPv6 checks below match ('[::1]' -> '::1'), then drop any
84
+ // IPv6 zone-id ('fe80::1%eth0' -> 'fe80::1') so a scoped literal cannot
85
+ // bypass the prefix checks.
86
+ var bare = normalized.charAt(0) === '[' && normalized.charAt(normalized.length - 1) === ']'
87
+ ? normalized.slice(1, -1)
88
+ : normalized;
89
+ var zone = bare.indexOf('%');
90
+ if (zone !== -1) bare = bare.slice(0, zone);
91
+ // IPv4 dotted-quad ranges.
92
+ var m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(bare);
93
+ if (m) {
94
+ var a = +m[1], b = +m[2];
95
+ if (a === 0) return true; // 0.0.0.0/8 "this host" (RFC 1122) -- SSRF to loopback-bound services on Linux
96
+ if (a === 127) return true; // 127.0.0.0/8 loopback
97
+ if (a === 10) return true; // 10.0.0.0/8
98
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
99
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16
100
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local
101
+ return false;
102
+ }
103
+ // Everything below is an IPv6 literal (colon-bearing) or a name; only the
104
+ // IPv6 forms are denied here. A name with no colon falls through to false
105
+ // (the dotless/.local check lives in classifyAssetOrigin).
106
+ if (bare.indexOf(':') === -1) return false;
107
+ if (bare === '::1') return true; // IPv6 loopback
108
+ if (bare === '::') return true; // unspecified address
109
+ // IPv6 link-local fe80::/10 (first hextet fe80..febf).
110
+ if (/^fe[89ab][0-9a-f]*:/.test(bare)) return true;
111
+ // IPv6 ULA fc00::/7 (fc.. or fd.. prefix).
112
+ if (/^f[cd][0-9a-f]*:/.test(bare)) return true;
113
+ // NAT64 well-known prefix 64:ff9b::/96 -- a public resolver maps an embedded
114
+ // IPv4 (incl. the metadata host: 64:ff9b::a9fe:a9fe) here. Block the prefix
115
+ // outright; the milestone never fetches via NAT64 by raw literal.
116
+ if (/^64:ff9b:/.test(bare)) return true;
117
+ // IPv4-mapped / IPv4-compatible IPv6: ::ffff:a.b.c.d, ::ffff:HHHH:HHHH,
118
+ // or ::a.b.c.d. Extract the trailing embedded IPv4 (dotted, or the last two
119
+ // hextets) and re-run the v4 ranges so e.g. ::ffff:169.254.169.254 and
120
+ // ::ffff:7f00:1 (127.0.0.1) are denied through the same table.
121
+ var mapped = /^(?:::ffff:|::)(?:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|([0-9a-f]{1,4}):([0-9a-f]{1,4}))$/.exec(bare);
122
+ if (mapped) {
123
+ var v4 = mapped[1];
124
+ if (!v4 && mapped[2] && mapped[3]) {
125
+ var hi = parseInt(mapped[2], 16), lo = parseInt(mapped[3], 16);
126
+ v4 = (hi >> 8) + '.' + (hi & 255) + '.' + (lo >> 8) + '.' + (lo & 255);
127
+ }
128
+ // Re-run the v4 ranges on the embedded address; ::ffff:0:0/96 mapping a
129
+ // public v4 stays allowed only when that v4 is itself public.
130
+ if (v4 && isPrivateOrLocalHost(v4)) return true;
131
+ }
132
+ return false;
133
+ }
134
+
135
+ /**
136
+ * Classify an asset URL for viewer-side fetch (MSEC-01). Fail-closed: every
137
+ * branch that is not "a provably public https host" returns allowed:false
138
+ * with a machine-readable reason. The reasons are stable identifiers the
139
+ * renderer maps to a dimensioned blocked-origin placeholder and that the
140
+ * asset-policy table test pins.
141
+ *
142
+ * parse failure -> { allowed:false, reason:'parse-error' }
143
+ * protocol !== 'https:' -> { allowed:false, reason:'bad-scheme' }
144
+ * private/internal/ULA host -> { allowed:false, reason:'private-host' }
145
+ * dotless or *.local host -> { allowed:false, reason:'unqualified-host' }
146
+ * otherwise -> { allowed:true, reason:'ok' }
147
+ *
148
+ * Note this is a FETCH gate, not an injection gate; http: is blocked here
149
+ * (mixed-content / no-TLS) even though hasDangerousScheme would allow it.
150
+ *
151
+ * @param {string} url Absolute asset URL (already absolutified by capture).
152
+ * @returns {AssetOriginVerdict}
153
+ */
154
+ export function classifyAssetOrigin(url) {
155
+ var u;
156
+ try {
157
+ u = new URL(String(url));
158
+ } catch (e) {
159
+ return { allowed: false, reason: 'parse-error' };
160
+ }
161
+ if (u.protocol !== 'https:') return { allowed: false, reason: 'bad-scheme' };
162
+ var host = (u.hostname || '').toLowerCase();
163
+ if (isPrivateOrLocalHost(host)) return { allowed: false, reason: 'private-host' };
164
+ // A bracketed IPv6 literal is qualified by construction (any non-private
165
+ // IPv6 already fell through isPrivateOrLocalHost); only its dotless form
166
+ // would otherwise trip the unqualified check, so exempt it explicitly.
167
+ var isIpv6Literal = host.charAt(0) === '[' && host.charAt(host.length - 1) === ']';
168
+ if (!isIpv6Literal && (host.indexOf('.') === -1 || host.endsWith('.local'))) {
169
+ return { allowed: false, reason: 'unqualified-host' };
170
+ }
171
+ return { allowed: true, reason: 'ok' };
172
+ }