@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,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
+ }
@@ -37,7 +37,59 @@
37
37
  // injected identity hooks owned by createViewer.
38
38
 
39
39
  import { DIFF_OP } from '../protocol/messages.js';
40
- import { sanitizeFragment, sanitizeAttrValue } from './sanitize.js';
40
+ import { sanitizeFragment, sanitizeAttrValue, parseSrcsetCandidates } from './sanitize.js';
41
+ import { restoreParserSafePlaceholders } from './parser-safe.js';
42
+
43
+ var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
44
+ var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
45
+
46
+ /**
47
+ * True when any candidate in a srcset value is blocked by the injected fetch
48
+ * gate. Reuses the shared per-candidate parser so the ATTR branch gates srcset
49
+ * with the same vocabulary as the snapshot/fragment gates (review WR-03).
50
+ * Unparseable input fails closed (treated as blocked).
51
+ * @param {string} srcset
52
+ * @param {(url: string, kind: string) => { allow: boolean }} gateAssetUrl
53
+ * @returns {boolean}
54
+ */
55
+ function srcsetHasBlockedCandidate(srcset, gateAssetUrl) {
56
+ if (!srcset) return false;
57
+ try {
58
+ var candidates = parseSrcsetCandidates(srcset);
59
+ for (var i = 0; i < candidates.length; i++) {
60
+ var url = candidates[i].url;
61
+ if (!url) continue;
62
+ var verdict = gateAssetUrl(url, 'image');
63
+ if (!verdict || !verdict.allow) return true;
64
+ }
65
+ return false;
66
+ } catch (e) {
67
+ return true; // unparseable srcset: fail closed
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Foreign-content parse context for an ADD op (quick task 261202-jwf). A
73
+ * child of an SVG or MathML element must be parsed inside an <svg> or <math>
74
+ * wrapper, or the HTML <template> parse creates HTML elements (an HTML
75
+ * <clippath> instead of SVG <clipPath>). The HTML integration points
76
+ * (foreignObject, desc, title; mi, mo, mn, ms, mtext, annotation-xml) hold
77
+ * HTML content, so they need no wrapper.
78
+ * @param {Element} parent The resolved ADD parent.
79
+ * @returns {'svg'|'math'|''}
80
+ */
81
+ function foreignParseContextTag(parent) {
82
+ if (!parent || !parent.namespaceURI) return '';
83
+ var name = parent.localName;
84
+ if (parent.namespaceURI === SVG_NAMESPACE) {
85
+ return (name === 'foreignObject' || name === 'desc' || name === 'title') ? '' : 'svg';
86
+ }
87
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
88
+ return (name === 'mi' || name === 'mo' || name === 'mn' || name === 'ms'
89
+ || name === 'mtext' || name === 'annotation-xml') ? '' : 'math';
90
+ }
91
+ return '';
92
+ }
41
93
 
42
94
  function installShadowRootDirect(doc, host, payload, sanitizeCounters, logger, indexSubtree, removeSubtree) {
43
95
  var p = payload || {};
@@ -57,6 +109,7 @@ function installShadowRootDirect(doc, host, payload, sanitizeCounters, logger, i
57
109
 
58
110
  var tpl = doc.createElement('template');
59
111
  tpl.innerHTML = p.html || '';
112
+ restoreParserSafePlaceholders(tpl.content);
60
113
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
61
114
  shadowRoot.appendChild(doc.importNode(tpl.content, true));
62
115
  indexSubtree(shadowRoot, p.nodeIds || []);
@@ -135,6 +188,39 @@ export function applyMutations(doc, mutations, counters, hooks) {
135
188
  var removeStyleSource = typeof identity.removeStyleSource === 'function'
136
189
  ? function (sourceId, scope) { return identity.removeStyleSource(sourceId, scope); }
137
190
  : null;
191
+ // Phase 12 (MSEC-01) injected pre-write asset gate. createViewer injects the
192
+ // posture-bound closures; omitted hooks default to no-ops so the public
193
+ // applyMutations signature and every existing caller stay unchanged.
194
+ // gateFragmentAssets(node): pre-write gate over inert ADD template content
195
+ // (currentSrc pin + blocked-origin -> placeholder), run before importNode.
196
+ // gateAssetUrl(url, kind): per-URL verdict for the ATTR branch's src/poster,
197
+ // run before setAttribute (live-element mutation -> must gate pre-write).
198
+ var gateFragmentAssets = typeof identity.gateFragmentAssets === 'function'
199
+ ? function (node) { identity.gateFragmentAssets(node); }
200
+ : function () {};
201
+ var gateAssetUrl = typeof identity.gateAssetUrl === 'function'
202
+ ? function (url, kind) { return identity.gateAssetUrl(url, kind); }
203
+ : null;
204
+
205
+ // ADD-op parse: the renderer's single add-op innerHTML sink. TEMPLATE-context
206
+ // parse (03-RESEARCH Pattern 2, jsdom-29-verified): template content accepts
207
+ // any HTML, so context-dependent elements (<tr>, <td>, <col>, <option>, ...)
208
+ // do not drop. wrapTag is '' or a STATIC 'svg' / 'math' wrapper from
209
+ // foreignParseContextTag, so add ops under SVG or MathML parents keep their
210
+ // namespace (quick task 261202-jwf). Parser-safe placeholders are restored
211
+ // right after the parse; then the RENDER-SIDE CHOKEPOINT (SEC-02) scrubs the
212
+ // PARSED fragment -- DOM-fragment based, never string-scrub-then-reparse
213
+ // (mXSS) -- and the PRE-WRITE FETCH GATE (MSEC-01) gates the inert content
214
+ // before importNode. Returns the first parsed element, or null.
215
+ function parseAddOpNode(html, wrapTag) {
216
+ var tpl = doc.createElement('template');
217
+ tpl.innerHTML = wrapTag ? '<' + wrapTag + '>' + html + '</' + wrapTag + '>' : html;
218
+ restoreParserSafePlaceholders(tpl.content);
219
+ sanitizeFragment(tpl.content, sanitizeCounters, logger);
220
+ gateFragmentAssets(tpl.content);
221
+ var parsedRoot = wrapTag ? tpl.content.firstElementChild : tpl.content;
222
+ return parsedRoot ? parsedRoot.firstElementChild : null;
223
+ }
138
224
 
139
225
  // Shared miss path: count, warn, and escalate at the parity threshold.
140
226
  function recordStaleMiss(op, nid) {
@@ -199,20 +285,16 @@ export function applyMutations(doc, mutations, counters, hooks) {
199
285
  recordStaleMiss(DIFF_OP.ADD, m.parentNid);
200
286
  break;
201
287
  }
202
- // TEMPLATE-context parse (03-RESEARCH Pattern 2, jsdom-29-
203
- // verified): template content accepts any HTML, so context-
204
- // dependent elements (<tr>, <td>, <col>, <option>, ...) no
205
- // longer drop. This is one of the renderer's two sanctioned
288
+ // parseAddOpNode holds one of the renderer's two sanctioned
206
289
  // innerHTML sinks for wire content; the other is the Phase 8
207
- // shadow-root replacement parser above. Both are followed by
208
- // sanitizeFragment and pinned by the purity scan.
209
- var tpl = doc.createElement('template');
210
- tpl.innerHTML = m.html;
211
- // RENDER-SIDE CHOKEPOINT (SEC-02): scrub the PARSED fragment
212
- // before it gets anywhere near the mirror document -- DOM-
213
- // fragment based, never string-scrub-then-reparse (mXSS).
214
- sanitizeFragment(tpl.content, sanitizeCounters, logger);
215
- var newNode = tpl.content.firstElementChild;
290
+ // shadow-root replacement parser above. Both are followed by the
291
+ // parser-safe restore and sanitizeFragment, and pinned by the
292
+ // purity scan. Under an SVG or MathML parent the op parses inside
293
+ // a static wrapper; when that yields no element (an HTML breakout
294
+ // tag such as <div>), it parses again without the wrapper.
295
+ var wrapTag = foreignParseContextTag(parent);
296
+ var newNode = parseAddOpNode(m.html, wrapTag);
297
+ if (!newNode && wrapTag) newNode = parseAddOpNode(m.html, '');
216
298
  if (!newNode) {
217
299
  // Still possible: empty/whitespace-only m.html, or html whose
218
300
  // only element was a dropped hostile subtree. Never silent
@@ -318,6 +400,55 @@ export function applyMutations(doc, mutations, counters, hooks) {
318
400
  target.removeAttribute(m.attr);
319
401
  break;
320
402
  }
403
+ // PRE-WRITE FETCH GATE (MSEC-01): for fetchable attrs (src/poster)
404
+ // on a LIVE mirror element, gate before setAttribute so a blocked
405
+ // origin never reaches the live DOM (the browser would GET it
406
+ // immediately). Blocked -> drop the attribute (no fetchable src);
407
+ // the dimensioned placeholder is the snapshot/ADD path's job.
408
+ if (gateAssetUrl && (attrName === 'src' || attrName === 'poster')) {
409
+ // Kind must match the live element so the gate applies mode-aware
410
+ // policy (poster mode withholds playable media but keeps images):
411
+ // <video>/<audio> src -> 'media', <source> src -> 'source', any
412
+ // other src -> 'image'; a poster attr stays 'poster'. Mirrors
413
+ // gateOneMediaTag / gateFragmentMedia so a poster-mode <video src>
414
+ // (or <source src>) mutation is denied 'poster-mode-media' instead
415
+ // of slipping through gated as an image and fetching media bytes.
416
+ var assetKind;
417
+ if (attrName === 'poster') {
418
+ assetKind = 'poster';
419
+ } else if (targetTag === 'video' || targetTag === 'audio') {
420
+ assetKind = 'media';
421
+ } else if (targetTag === 'source') {
422
+ assetKind = 'source';
423
+ } else {
424
+ assetKind = 'image';
425
+ }
426
+ var assetVerdict = gateAssetUrl(scrubbed.value, assetKind);
427
+ if (!assetVerdict || !assetVerdict.allow) {
428
+ sanitizeCounters.blockedUrls += 1;
429
+ logger.warn('[Renderer] attr op asset blocked by origin gate', {
430
+ nid: m.nid || '', attr: m.attr || ''
431
+ });
432
+ target.removeAttribute(m.attr);
433
+ break;
434
+ }
435
+ }
436
+ // PRE-WRITE FETCH GATE (MSEC-01, review WR-03): srcset is a
437
+ // first-class multi-candidate fetchable attribute -- on a live
438
+ // <img> the browser may select and GET a candidate. Gate every
439
+ // candidate; if ANY is blocked, drop the whole srcset (the
440
+ // remaining src/placeholder path covers display) so no blocked
441
+ // origin reaches the live DOM.
442
+ if (gateAssetUrl && attrName === 'srcset') {
443
+ if (srcsetHasBlockedCandidate(scrubbed.value, gateAssetUrl)) {
444
+ sanitizeCounters.blockedUrls += 1;
445
+ logger.warn('[Renderer] attr op srcset candidate blocked by origin gate', {
446
+ nid: m.nid || '', attr: m.attr || ''
447
+ });
448
+ target.removeAttribute(m.attr);
449
+ break;
450
+ }
451
+ }
321
452
  target.setAttribute(m.attr, scrubbed.value);
322
453
  break;
323
454
  }
@@ -333,7 +464,19 @@ export function applyMutations(doc, mutations, counters, hooks) {
333
464
  if (Object.prototype.hasOwnProperty.call(m, 'checked')) {
334
465
  valueTarget.checked = !!m.checked;
335
466
  }
336
- if (Array.isArray(m.selectedValues) && valueTarget.options) {
467
+ if (Array.isArray(m.selectedIndexes) && valueTarget.options) {
468
+ // Index-addressed selection is unambiguous even when masking
469
+ // collapses distinct option values to the same masked string
470
+ // (capture omits the raw values from the wire), so it wins over
471
+ // selectedValues whenever the capture side provides it.
472
+ var selectedIndexes = new Set();
473
+ for (var si = 0; si < m.selectedIndexes.length; si++) {
474
+ selectedIndexes.add(Number(m.selectedIndexes[si]));
475
+ }
476
+ for (var ix = 0; ix < valueTarget.options.length; ix++) {
477
+ valueTarget.options[ix].selected = selectedIndexes.has(ix);
478
+ }
479
+ } else if (Array.isArray(m.selectedValues) && valueTarget.options) {
337
480
  var selectedValues = new Set();
338
481
  for (var sv = 0; sv < m.selectedValues.length; sv++) {
339
482
  selectedValues.add(String(m.selectedValues[sv]));