@botiverse/porthole 0.14.7 → 0.14.9

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 (87) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/bridge/bridge.d.ts +6 -0
  3. package/dist/bridge/bridge.js +5 -0
  4. package/dist/check/files.js +2 -0
  5. package/dist/check/lint.js +82 -3
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/compile/policy.d.ts +17 -6
  8. package/dist/compile/policy.js +22 -7
  9. package/dist/config/capabilities.d.ts +16 -2
  10. package/dist/config/capabilities.js +8 -0
  11. package/dist/config/schema.d.ts +13 -0
  12. package/dist/config/validate.js +15 -0
  13. package/dist/conformance/harness-source.js +1 -1
  14. package/dist/conformance/kit.d.ts +5 -0
  15. package/dist/conformance/kit.js +21 -0
  16. package/dist/conformance/limits.js +10 -5
  17. package/dist/conformance/probes.js +139 -28
  18. package/dist/conformance/served.js +25 -4
  19. package/dist/find/types.d.ts +83 -0
  20. package/dist/find/types.js +29 -0
  21. package/dist/find/validate.d.ts +17 -0
  22. package/dist/find/validate.js +82 -0
  23. package/dist/guide/guide.js +2 -1
  24. package/dist/guide/limits.js +8 -1
  25. package/dist/host/create-host.js +249 -4
  26. package/dist/host/pass-on.js +3 -2
  27. package/dist/host/types.d.ts +51 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.js +4 -1
  30. package/dist/presets/presets.d.ts +6 -0
  31. package/dist/presets/presets.js +6 -0
  32. package/dist/react/frame.d.ts +43 -0
  33. package/dist/react/frame.js +107 -3
  34. package/dist/react/view.js +2 -0
  35. package/dist/runtime/contract.d.ts +1 -1
  36. package/dist/runtime/contract.js +1 -1
  37. package/dist/server/files.js +4 -3
  38. package/dist/server/server.js +4 -1
  39. package/dist/shell/annotate.js +2 -95
  40. package/dist/shell/document.d.ts +3 -3
  41. package/dist/shell/document.js +5 -3
  42. package/dist/shell/find.d.ts +82 -0
  43. package/dist/shell/find.js +725 -0
  44. package/dist/shell/plan.d.ts +5 -0
  45. package/dist/shell/plan.js +2 -0
  46. package/dist/shell/runtime.d.ts +30 -1
  47. package/dist/shell/runtime.js +789 -105
  48. package/dist/shell/text.d.ts +17 -0
  49. package/dist/shell/text.js +140 -0
  50. package/docs/ADOPTING.md +103 -0
  51. package/docs/ARCHITECTURE.md +10 -3
  52. package/docs/DECISIONS.md +513 -1
  53. package/docs/DESIGN.md +40 -4
  54. package/docs/THREAT_MODEL.md +75 -6
  55. package/docs/insertion-entry-points.md +112 -0
  56. package/package.json +1 -1
  57. package/src/bridge/bridge.ts +7 -0
  58. package/src/check/files.ts +2 -0
  59. package/src/check/lint.ts +97 -8
  60. package/src/compile/policy.ts +23 -6
  61. package/src/config/capabilities.ts +13 -1
  62. package/src/config/schema.ts +13 -0
  63. package/src/config/validate.ts +16 -0
  64. package/src/conformance/kit.ts +22 -0
  65. package/src/conformance/limits.ts +10 -5
  66. package/src/conformance/probes.ts +149 -28
  67. package/src/conformance/served.ts +24 -4
  68. package/src/find/types.ts +86 -0
  69. package/src/find/validate.ts +101 -0
  70. package/src/guide/guide.ts +3 -1
  71. package/src/guide/limits.ts +9 -1
  72. package/src/host/create-host.ts +267 -4
  73. package/src/host/pass-on.ts +3 -2
  74. package/src/host/types.ts +52 -0
  75. package/src/index.ts +13 -0
  76. package/src/presets/presets.ts +15 -0
  77. package/src/react/frame.tsx +160 -1
  78. package/src/react/view.tsx +3 -0
  79. package/src/runtime/contract.ts +1 -1
  80. package/src/server/files.ts +8 -2
  81. package/src/server/server.ts +4 -1
  82. package/src/shell/annotate.ts +3 -95
  83. package/src/shell/document.ts +5 -3
  84. package/src/shell/find.ts +731 -0
  85. package/src/shell/plan.ts +7 -0
  86. package/src/shell/runtime.ts +792 -105
  87. package/src/shell/text.ts +140 -0
@@ -8,6 +8,90 @@ export const HELD_BACK = String.raw`(html) => {
8
8
  return at !== -1 && /^\/?(?:[A-Za-z][^>]*)?$/.test(html.slice(at + 1)) ? html.slice(0, at) : html;
9
9
  }`;
10
10
 
11
+ /**
12
+ * Which `<iframe>` the shell keeps under `nestedFrames: "own"` (P128), spliced into the runtime:
13
+ * one with a `srcdoc` attribute (which wins over any `src`), or one whose `src`, resolved by the
14
+ * platform's own URL parser (`resolve`, which normalizes `..`, `%2e` and backslashes), is under the
15
+ * version's own files' address (`filesBase`, ending in `/`). Nothing else: no `src` or a blank one
16
+ * (`about:blank`), another path of the origin, another origin, `data:`, `blob:`, `javascript:`.
17
+ * Only comparisons and indexing, which content can't replace (no String.prototype method).
18
+ */
19
+ export const OWN_FRAME = String.raw`(hasSrcdoc, src, filesBase, resolve) => {
20
+ if (hasSrcdoc === true) {
21
+ return true;
22
+ }
23
+ if (typeof src !== "string" || typeof filesBase !== "string" || filesBase.length === 0 || filesBase[filesBase.length - 1] !== "/") {
24
+ return false;
25
+ }
26
+ let blank = true;
27
+ for (let i = 0; i < src.length && blank; i += 1) {
28
+ const c = src[i];
29
+ blank = c === " " || c === "\t" || c === "\n" || c === "\f" || c === "\r";
30
+ }
31
+ if (blank) {
32
+ return false;
33
+ }
34
+ let target = null;
35
+ try {
36
+ target = resolve(src);
37
+ } catch (_) {
38
+ return false;
39
+ }
40
+ if (typeof target !== "string" || target.length < filesBase.length) {
41
+ return false;
42
+ }
43
+ for (let i = 0; i < filesBase.length; i += 1) {
44
+ if (target[i] !== filesBase[i]) {
45
+ return false;
46
+ }
47
+ }
48
+ return true;
49
+ }`;
50
+
51
+ /**
52
+ * Which values a guard forwards as they are (P129, P130), spliced into the runtime: those that are
53
+ * their own single reading. A string, a number, a boolean, a bigint, `null`, and a genuine
54
+ * `undefined` (`value === undefined`: an object whose `typeof` is "undefined" isn't one). Nothing
55
+ * here can throw or run content's code (`typeof` and `===` read no property).
56
+ */
57
+ export const PASSES_AS_IS = String.raw`(value) => {
58
+ if (value === null || value === undefined) {
59
+ return true;
60
+ }
61
+ const kind = typeof value;
62
+ return kind === "string" || kind === "number" || kind === "boolean" || kind === "bigint";
63
+ }`;
64
+
65
+ /**
66
+ * A name or value a guard inspects and then forwards, pinned to one reading (P129, P130), spliced
67
+ * into the runtime as `ONCE(passesAsIs, toText)`: a value `passesAsIs` lets through goes on
68
+ * unchanged; anything else is turned into its string once, by `toText` (the platform's own
69
+ * `String`, kept before content runs), and that string is what is both checked and forwarded. A
70
+ * symbol, a conversion that throws, or one that doesn't give a string is refused (the guard throws
71
+ * and nothing is forwarded): fail closed.
72
+ */
73
+ export const ONCE = String.raw`(passesAsIs, toText) => (value) => {
74
+ let pass = false;
75
+ try {
76
+ pass = passesAsIs(value) === true;
77
+ } catch (_) {
78
+ pass = false;
79
+ }
80
+ if (pass) {
81
+ return value;
82
+ }
83
+ let text = null;
84
+ try {
85
+ text = typeof value === "symbol" ? null : toText(value);
86
+ } catch (_) {
87
+ text = null;
88
+ }
89
+ if (typeof text !== "string") {
90
+ throw new TypeError("This value can't be used here");
91
+ }
92
+ return text;
93
+ }`;
94
+
11
95
  /**
12
96
  * The shell's runtime: the code that runs first in the frame, before any content. Plain ES2020,
13
97
  * no imports and no build step, so every engine (a browser frame now, a native web view later)
@@ -21,7 +105,11 @@ export const HELD_BACK = String.raw`(html) => {
21
105
  * 3. removes every frame-like element content adds, wherever it adds it (the document, any shadow
22
106
  * root), since a nested frame runs in a fresh realm where step 2 never happened (and not every
23
107
  * engine enforces `frame-src 'none'` for `srcdoc`/`about:blank` children); and the resource
24
- * hints and refreshes a CSP doesn't govern;
108
+ * hints and refreshes a CSP doesn't govern. Where the config opts in (`nestedFrames: "own"`,
109
+ * P128), an `<iframe>` of the page's own files or with `srcdoc` is kept (`OWN_FRAME`), and
110
+ * one that is kept leaves the document before a change would make it any other; in such a
111
+ * child realm steps 1, 2, 5 and 6 never ran (a page of the set has its own shell there), which
112
+ * the host accepted by opting in;
25
113
  * 4. closes the parser entry points that could build a shadow root step 3 can't see (declarative
26
114
  * shadow DOM through `setHTMLUnsafe`, `parseHTMLUnsafe`, `document.write`);
27
115
  * 5. keeps content off the clipboard: the async Clipboard API refuses, `execCommand` won't copy or
@@ -46,6 +134,11 @@ export const HELD_BACK = String.raw`(html) => {
46
134
  export const SHELL_RUNTIME = String.raw`(() => {
47
135
  "use strict";
48
136
  const plan = __PLAN__;
137
+ // Every built-in a guard calls is called through callOf, which is Reflect.apply itself, kept
138
+ // now, before any content runs: a direct call of it never reads Function.prototype's call,
139
+ // apply or bind, so nothing content later puts there sees what the shell calls or with what.
140
+ const callOf = Reflect.apply;
141
+ const hasOwn = Object.prototype.hasOwnProperty;
49
142
  // A page that came with files, answered at its ticket's address (P083): its own address first,
50
143
  // before anything loads, so its relative addresses are its files' (and the ticket leaves).
51
144
  if (plan.files && typeof plan.files.address === "string" && location.href !== plan.files.address) {
@@ -56,7 +149,7 @@ export const SHELL_RUNTIME = String.raw`(() => {
56
149
  // The embedding page's nonce, where it gave one (a srcdoc frame inherits its policy): every
57
150
  // script the shell runs for the content carries it.
58
151
  const nonce = document.currentScript && document.currentScript.nonce ? document.currentScript.nonce : "";
59
- const declared = (name) => Object.prototype.hasOwnProperty.call(plan.capabilities, name);
152
+ const declared = (name) => callOf(hasOwn, plan.capabilities, [name]);
60
153
  // Fixed in place: content can neither restore what is removed nor replace what is wrapped. A
61
154
  // property something fixed before the shell ran (an extension, an engine's own) can't be: each
62
155
  // such name goes on the shell's own script element (data-porthole-unfixed, for a test or a
@@ -155,7 +248,6 @@ export const SHELL_RUNTIME = String.raw`(() => {
155
248
  // The platform's own string and URL functions, kept now (P099): the rules that decide where this
156
249
  // document may go must read an address as the platform does, whatever content later puts on
157
250
  // String.prototype, URL or Reflect.
158
- const callOf = Reflect.apply;
159
251
  const NativeString = String;
160
252
  const NativeURL = URL;
161
253
  const urlHref = Object.getOwnPropertyDescriptor(URL.prototype, "href").get;
@@ -198,7 +290,7 @@ export const SHELL_RUNTIME = String.raw`(() => {
198
290
  navigationApi.addEventListener("navigate", (event) => {
199
291
  const destination = applyOf(destinationOf, event, []);
200
292
  if (!applyOf(sameDocumentOf, destination, []) && applyOf(navigationTypeOf, event, []) !== "reload") {
201
- const url = urlOf === null ? "" : String(applyOf(urlOf, destination, []));
293
+ const url = urlOf === null ? "" : NativeString(applyOf(urlOf, destination, []));
202
294
  if (ownPage(url)) {
203
295
  navigating(url);
204
296
  return;
@@ -462,47 +554,232 @@ export const SHELL_RUNTIME = String.raw`(() => {
462
554
 
463
555
  // No nested frames (each would be a fresh realm with WebRTC intact), no resource hints and no
464
556
  // refreshes (they reach the network outside the CSP's fetch directives). Removed as they are
465
- // added: a mutation observer's microtask runs before a child frame's document loads.
557
+ // added: a mutation observer's microtask runs before a child frame's document loads. Under
558
+ // nestedFrames "own" (P128), a page's own iframes stay (keptFrame, below).
466
559
  const FRAMES = "iframe,frame,frameset,object,embed,portal,fencedframe";
467
560
  const HINTS = 'link[rel~="dns-prefetch" i],link[rel~="preconnect" i],link[rel~="prefetch" i],link[rel~="prerender" i],script[type="speculationrules" i],meta[http-equiv="refresh" i],meta[http-equiv="x-dns-prefetch-control" i]';
468
561
  const GUARDED = FRAMES + "," + HINTS;
469
- const guardedRoots = new WeakSet();
470
- let guardRoot = null;
471
- const strip = (node) => {
472
- if (node === null || (node.nodeType !== 1 && node.nodeType !== 9 && node.nodeType !== 11)) {
473
- return;
562
+ // A page's own frames (P128), where the config opts in: an iframe of its version's files, or a
563
+ // srcdoc one, read through the platform's own getters (kept now) and OWN_FRAME's rule. Every
564
+ // other frame-like element is removed as before; the CSP's frame-src is the wall behind this.
565
+ const ownFrames = plan.nestedFrames === "own";
566
+ const ownFrame = ${OWN_FRAME};
567
+ const localNameOf = getterOf(Element.prototype, "localName");
568
+ const namespaceOf = getterOf(Element.prototype, "namespaceURI");
569
+ const baseOf = getterOf(Node.prototype, "baseURI");
570
+ const hasAttributeIn = Element.prototype.hasAttribute;
571
+ const getAttributeIn = Element.prototype.getAttribute;
572
+ const resolveHere = (text) => callOf(urlHref, new NativeURL(NativeString(text), callOf(baseOf, document, [])), []);
573
+ const keptFrame = (element) => {
574
+ if (!ownFrames || localNameOf === null || namespaceOf === null || baseOf === null) {
575
+ return false;
474
576
  }
475
- if (node.nodeType === 1 && node.matches(GUARDED)) {
476
- node.remove();
477
- return;
577
+ try {
578
+ if (callOf(localNameOf, element, []) !== "iframe" || callOf(namespaceOf, element, []) !== "http://www.w3.org/1999/xhtml") {
579
+ return false;
580
+ }
581
+ return ownFrame(callOf(hasAttributeIn, element, ["srcdoc"]) === true, callOf(getAttributeIn, element, ["src"]), filesBase, resolveHere);
582
+ } catch (_) {
583
+ return false;
478
584
  }
479
- for (const element of Array.from(node.querySelectorAll(GUARDED))) {
480
- element.remove();
585
+ };
586
+ const matchesIn = Element.prototype.matches;
587
+ const guarded = (element) => callOf(matchesIn, element, [GUARDED]) && !keptFrame(element);
588
+ // The built-ins step 3's guard and its observer use, captured before content runs and called
589
+ // only through these references (as the rule above reads matches, localName, namespaceURI,
590
+ // baseURI, src and srcdoc): a page that replaces a prototype method, a getter, or the global
591
+ // Array.from can't make the guard or its observer walk past a frame they must remove.
592
+ const nodeTypeOf = getterOf(Node.prototype, "nodeType");
593
+ const isConnectedOf = getterOf(Node.prototype, "isConnected");
594
+ const parentNodeOf = getterOf(Node.prototype, "parentNode");
595
+ const shadowRootOfNode = getterOf(Element.prototype, "shadowRoot");
596
+ const childNodesOf = getterOf(Node.prototype, "childNodes");
597
+ const removeIn = Element.prototype.remove;
598
+ const cloneNodeIn = Node.prototype.cloneNode;
599
+ const queryAllElement = Element.prototype.querySelectorAll;
600
+ const queryAllDocument = Document.prototype.querySelectorAll;
601
+ const queryAllFragment = DocumentFragment.prototype.querySelectorAll;
602
+ const nodeListLengthOf = getterOf(NodeList.prototype, "length");
603
+ const weakSetHas = WeakSet.prototype.has;
604
+ const weakSetAdd = WeakSet.prototype.add;
605
+ const observeIn = MutationObserver.prototype.observe;
606
+ const makeText = Document.prototype.createTextNode;
607
+ const recordProto = typeof MutationRecord === "function" ? MutationRecord.prototype : null;
608
+ const addedNodesOf = getterOf(recordProto, "addedNodes");
609
+ const recordTypeOf = getterOf(recordProto, "type");
610
+ const recordTargetOf = getterOf(recordProto, "target");
611
+ const attrProto = typeof Attr === "function" ? Attr.prototype : null;
612
+ const ownerElementOf = getterOf(attrProto, "ownerElement");
613
+ const attrNameOf = getterOf(attrProto, "name");
614
+ const attrNamespaceOf = getterOf(attrProto, "namespaceURI");
615
+ const attrValueOf = getterOf(attrProto, "value");
616
+ const setAttributeNSIn = Element.prototype.setAttributeNS;
617
+ const removeAttributeIn = Element.prototype.removeAttribute;
618
+ const createIn = Document.prototype.createElement;
619
+ const createNSIn = Document.prototype.createElementNS;
620
+ const weakMapGet = WeakMap.prototype.get;
621
+ const weakMapSet = WeakMap.prototype.set;
622
+ // A template's content, read natively: the walk below goes into it (P130), and content's own
623
+ // reads of it are stripped first (the content getter, below).
624
+ const templateContentOf = typeof HTMLTemplateElement === "function" ? getterOf(HTMLTemplateElement.prototype, "content") : null;
625
+ const NativeDOMException = DOMException;
626
+ const XHTML = "http://www.w3.org/1999/xhtml";
627
+ // A list the shell builds (arguments to pass on, nodes to move): an object with no prototype,
628
+ // so neither writing nor reading an index or its length reaches anything on Array.prototype or
629
+ // Object.prototype. callOf takes it as its arguments.
630
+ const bare = Object.create;
631
+ const listOf = () => {
632
+ const list = bare(null);
633
+ list.length = 0;
634
+ return list;
635
+ };
636
+ const pushTo = (list, value) => {
637
+ list[list.length] = value;
638
+ list.length += 1;
639
+ };
640
+ // FRAMES's names as a lookup with no prototype, decided now: an element of one of these names,
641
+ // in any namespace and any case, is one content can't create under the default config (P130).
642
+ const frameTags = bare(null);
643
+ for (const tag of FRAMES.split(",")) {
644
+ frameTags[tag] = true;
645
+ }
646
+ const frameCapableName = (name) => {
647
+ const text = callOf(lowerOf, name, []);
648
+ const first = callOf(indexIn, text, [":"]);
649
+ const last = callOf(lastIndexIn, text, [":"]);
650
+ return frameTags[text] === true || (first !== -1 && frameTags[callOf(sliceOf, text, [first + 1])] === true) || (last !== -1 && frameTags[callOf(sliceOf, text, [last + 1])] === true);
651
+ };
652
+ // An attribute's name, namespace and value, read through the kept getters.
653
+ const attrParts = (attribute) => ({
654
+ namespace: callOf(attrNamespaceOf, attribute, []),
655
+ name: callOf(attrNameOf, attribute, []),
656
+ value: callOf(attrValueOf, attribute, []),
657
+ });
658
+ // A name or value a guard inspects and then passes on, pinned to one reading (PASSES_AS_IS,
659
+ // ONCE): anything but a primitive that is its own single reading (a string, number, boolean,
660
+ // bigint, null, or undefined itself) is turned into its string once, here, so the guard checks
661
+ // and the platform acts on the same text (a value whose toString answers differently the second
662
+ // time can't slip past). null and booleans are kept as they are, for the setters that treat them
663
+ // specially. A value that can't be read once (a symbol, a conversion that throws) is refused.
664
+ const passesAsIs = ${PASSES_AS_IS};
665
+ const once = (${ONCE})(passesAsIs, NativeString);
666
+ // An object (a dictionary to read once), by the same rule: anything once wouldn't pass as it is.
667
+ const objectLike = (value) => !passesAsIs(value) && typeof value !== "symbol";
668
+ // A node's type (and whether it is connected), read through the kept getters; anything that
669
+ // isn't a node reads as -1 / false, never throws, so the insertion guards can ask of any value.
670
+ const typeOf = (node) => {
671
+ if (node === null || typeof node !== "object" || nodeTypeOf === null) {
672
+ return -1;
481
673
  }
482
- // Open shadow roots made without attachShadow (declarative ones the parser built elsewhere).
483
- if (node.nodeType === 1 && node.shadowRoot) {
484
- guardRoot(node.shadowRoot);
674
+ try {
675
+ return callOf(nodeTypeOf, node, []);
676
+ } catch (_) {
677
+ return -1;
485
678
  }
486
- for (const element of Array.from(node.querySelectorAll("*"))) {
487
- if (element.shadowRoot) {
488
- guardRoot(element.shadowRoot);
679
+ };
680
+ const connected = (node) => {
681
+ if (isConnectedOf === null) {
682
+ return false;
683
+ }
684
+ try {
685
+ return callOf(isConnectedOf, node, []) === true;
686
+ } catch (_) {
687
+ return false;
688
+ }
689
+ };
690
+ const countOf = (list) => (nodeListLengthOf === null ? 0 : callOf(nodeListLengthOf, list, []));
691
+ const shadowOf = (element) => (shadowRootOfNode === null ? null : callOf(shadowRootOfNode, element, []));
692
+ const queryAllOf = (node, type, selector) => callOf(type === 1 ? queryAllElement : type === 9 ? queryAllDocument : queryAllFragment, node, [selector]);
693
+ // An HTML template (its content is what the walk enters), by the kept getters: the selector
694
+ // "template" also matches an HTML-namespace element named "TEMPLATE" in any case, which isn't one.
695
+ const isTemplate =
696
+ templateContentOf === null || localNameOf === null || namespaceOf === null
697
+ ? null
698
+ : (element) => callOf(localNameOf, element, []) === "template" && callOf(namespaceOf, element, []) === XHTML;
699
+ const guardedRoots = new WeakSet();
700
+ let watchRoot = null;
701
+ // Every subtree the walk reaches is stripped: the node's own tree (querySelectorAll's reach), and
702
+ // what that never enters, each template's content and each open shadow root's tree (P130),
703
+ // however deep they nest. A list of what is left to walk, not recursion: no depth runs it out of
704
+ // stack. A shadow root found is watched by the observer too (declarative ones the parser built
705
+ // elsewhere, made without attachShadow).
706
+ const strip = (start) => {
707
+ const pending = listOf();
708
+ pushTo(pending, start);
709
+ for (let at = 0; at < pending.length; at += 1) {
710
+ const node = pending[at];
711
+ const type = typeOf(node);
712
+ if (type !== 1 && type !== 9 && type !== 11) {
713
+ continue;
714
+ }
715
+ if (type === 1 && guarded(node)) {
716
+ callOf(removeIn, node, []);
717
+ continue;
718
+ }
719
+ const framed = queryAllOf(node, type, GUARDED);
720
+ for (let i = 0, n = countOf(framed); i < n; i += 1) {
721
+ const element = framed[i];
722
+ if (!keptFrame(element)) {
723
+ callOf(removeIn, element, []);
724
+ }
725
+ }
726
+ if (isTemplate !== null) {
727
+ const templates = queryAllOf(node, type, "template");
728
+ for (let i = 0, n = countOf(templates); i < n; i += 1) {
729
+ if (isTemplate(templates[i])) {
730
+ pushTo(pending, callOf(templateContentOf, templates[i], []));
731
+ }
732
+ }
733
+ if (type === 1 && isTemplate(node)) {
734
+ pushTo(pending, callOf(templateContentOf, node, []));
735
+ }
736
+ }
737
+ if (type === 1) {
738
+ const root = shadowOf(node);
739
+ if (root) {
740
+ watchRoot(root);
741
+ pushTo(pending, root);
742
+ }
743
+ }
744
+ const all = queryAllOf(node, type, "*");
745
+ for (let i = 0, n = countOf(all); i < n; i += 1) {
746
+ const root = shadowOf(all[i]);
747
+ if (root) {
748
+ watchRoot(root);
749
+ pushTo(pending, root);
750
+ }
489
751
  }
490
752
  }
491
753
  };
492
754
  const frameGuard = new MutationObserver((records) => {
493
- for (const record of records) {
494
- for (const node of Array.from(record.addedNodes)) {
495
- strip(node);
755
+ for (let i = 0; i < records.length; i += 1) {
756
+ const record = records[i];
757
+ // A kept frame whose src or srcdoc changed another way (P128): the backstop of the
758
+ // synchronous guard below (beforeChange), as the rest of this observer is.
759
+ if ((recordTypeOf === null ? record.type : callOf(recordTypeOf, record, [])) === "attributes") {
760
+ const target = recordTargetOf === null ? record.target : callOf(recordTargetOf, record, []);
761
+ if (connected(target) && guarded(target)) {
762
+ callOf(removeIn, target, []);
763
+ }
764
+ continue;
765
+ }
766
+ const added = addedNodesOf === null ? record.addedNodes : callOf(addedNodesOf, record, []);
767
+ for (let j = 0, n = countOf(added); j < n; j += 1) {
768
+ strip(added[j]);
496
769
  }
497
770
  }
498
771
  });
499
- guardRoot = (root) => {
500
- if (guardedRoots.has(root)) {
772
+ const observed = ownFrames ? { childList: true, subtree: true, attributes: true, attributeFilter: ["src", "srcdoc"] } : { childList: true, subtree: true };
773
+ watchRoot = (root) => {
774
+ if (callOf(weakSetHas, guardedRoots, [root])) {
501
775
  return;
502
776
  }
503
- guardedRoots.add(root);
777
+ callOf(weakSetAdd, guardedRoots, [root]);
778
+ callOf(observeIn, frameGuard, [root, observed]);
779
+ };
780
+ const guardRoot = (root) => {
504
781
  strip(root);
505
- frameGuard.observe(root, { childList: true, subtree: true });
782
+ watchRoot(root);
506
783
  };
507
784
  guardRoot(document);
508
785
 
@@ -513,22 +790,37 @@ export const SHELL_RUNTIME = String.raw`(() => {
513
790
  const attachShadow = Element.prototype.attachShadow;
514
791
  const shownOpen = new WeakSet();
515
792
  const addShown = WeakSet.prototype.add;
793
+ // The init dictionary is read once (P130): each field, once, into a fresh object with no
794
+ // prototype, which is all the platform is given; the mode that decides the closed-to-open turn
795
+ // is the same pinned text the platform reads. A field this list doesn't name isn't passed on.
796
+ const SHADOW_FIELDS = ["mode", "delegatesFocus", "slotAssignment", "clonable", "serializable", "customElementRegistry", "referenceTarget"];
797
+ const SHADOW_TEXT = bare(null);
798
+ SHADOW_TEXT.mode = true;
799
+ SHADOW_TEXT.slotAssignment = true;
800
+ SHADOW_TEXT.referenceTarget = true;
516
801
  const shadowInit = (init) => {
517
- if (window.top !== window || init === null || typeof init !== "object" || init.mode !== "closed") {
518
- return { init, closed: false };
519
- }
520
- const copy = { mode: "open" };
521
- for (const key of ["delegatesFocus", "slotAssignment", "clonable", "serializable", "customElementRegistry", "referenceTarget"]) {
522
- if (init[key] !== undefined) {
523
- copy[key] = init[key];
802
+ const copy = bare(null);
803
+ if (objectLike(init)) {
804
+ for (let i = 0; i < SHADOW_FIELDS.length; i += 1) {
805
+ const field = SHADOW_FIELDS[i];
806
+ const value = init[field];
807
+ if (value !== undefined) {
808
+ copy[field] = SHADOW_TEXT[field] === true ? once(value) : value;
809
+ }
524
810
  }
525
811
  }
526
- return { init: copy, closed: true };
812
+ const asked = bare(null);
813
+ asked.closed = window.top === window && copy.mode === "closed";
814
+ if (asked.closed) {
815
+ copy.mode = "open";
816
+ }
817
+ asked.init = copy;
818
+ return asked;
527
819
  };
528
820
  lock(Element.prototype, "attachShadow", function (init) {
529
821
  const asked = shadowInit(init);
530
822
  init = asked.init;
531
- const root = attachShadow.call(this, init);
823
+ const root = callOf(attachShadow, this, [init]);
532
824
  guardRoot(root);
533
825
  if (asked.closed) {
534
826
  callOf(addShown, shownOpen, [root]);
@@ -566,19 +858,29 @@ export const SHELL_RUNTIME = String.raw`(() => {
566
858
  // a closed one is out of the guard's reach. Fragment parsing doesn't build them, so the entry
567
859
  // points that would are given fragment parsing's behavior, and a document can't be rewritten.
568
860
  const parseInert = (html) => {
569
- const template = document.createElement("template");
570
- template.innerHTML = String(html);
861
+ const template = callOf(createIn, document, ["template"]);
862
+ template.innerHTML = NativeString(html);
571
863
  return template.content;
572
864
  };
573
865
  for (const proto of [Element.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null]) {
574
866
  if (proto !== null && "setHTMLUnsafe" in proto) {
575
867
  lock(proto, "setHTMLUnsafe", function (html) {
576
- this.innerHTML = String(html);
868
+ this.innerHTML = NativeString(html);
577
869
  });
578
870
  }
579
871
  }
580
- if (typeof Document.parseHTMLUnsafe === "function") {
581
- lock(Document, "parseHTMLUnsafe", (html) => new DOMParser().parseFromString(String(html), "text/html"));
872
+ // Document.parseHTMLUnsafe and the Sanitizer API's Document.parseHTML: DOMParser's parse (no
873
+ // declarative shadow DOM), through the platform's own parser, stripped before it is returned.
874
+ const NativeDOMParser = DOMParser;
875
+ const parseFromStringIn = DOMParser.prototype.parseFromString;
876
+ for (const name of ["parseHTMLUnsafe", "parseHTML"]) {
877
+ if (typeof Document[name] === "function") {
878
+ lock(Document, name, (html) => {
879
+ const parsed = callOf(parseFromStringIn, new NativeDOMParser(), [NativeString(html), "text/html"]);
880
+ strip(parsed);
881
+ return parsed;
882
+ });
883
+ }
582
884
  }
583
885
  const noRewrite = function () {
584
886
  throw new Error("document.open and document.write aren't available here: build the page with DOM methods");
@@ -592,24 +894,36 @@ export const SHELL_RUNTIME = String.raw`(() => {
592
894
  // node drops guarded elements first, synchronously, and a connected link or meta can't be
593
895
  // changed into one. The observer stays as the backstop for anything these miss.
594
896
  const admit = (node) => {
595
- if (node === null || typeof node !== "object" || typeof node.nodeType !== "number") {
897
+ const type = typeOf(node);
898
+ if (type === -1) {
596
899
  return true;
597
900
  }
598
- if (node.nodeType === 1 && node.matches(GUARDED)) {
901
+ if (type === 1 && guarded(node)) {
599
902
  return false;
600
903
  }
601
904
  strip(node);
602
905
  return true;
603
906
  };
604
- const admitted = (args) => args.map((arg) => (admit(arg) ? arg : document.createTextNode("")));
605
907
  const wrapInsert = (proto, name, positions) => {
606
908
  const original = proto && proto[name];
607
909
  if (typeof original !== "function") {
608
910
  return;
609
911
  }
912
+ // Which arguments are nodes to check, decided now (before content runs), as a lookup that has
913
+ // no prototype: nothing content later puts on Array.prototype takes part in the decision.
914
+ const all = positions === "all";
915
+ const checks = bare(null);
916
+ if (!all) {
917
+ for (let i = 0; i < positions.length; i += 1) {
918
+ checks[positions[i]] = true;
919
+ }
920
+ }
610
921
  lock(proto, name, function (...args) {
611
- const checked = positions === "all" ? admitted(args) : args.map((arg, index) => (positions.indexOf(index) !== -1 && !admit(arg) ? document.createTextNode("") : arg));
612
- return original.apply(this, checked);
922
+ const checked = listOf();
923
+ for (let i = 0; i < args.length; i += 1) {
924
+ pushTo(checked, (all || checks[i] === true) && !admit(args[i]) ? callOf(makeText, document, [""]) : args[i]);
925
+ }
926
+ return callOf(original, this, checked);
613
927
  });
614
928
  };
615
929
  for (const proto of [Node.prototype]) {
@@ -630,44 +944,112 @@ export const SHELL_RUNTIME = String.raw`(() => {
630
944
  wrapInsert(Element.prototype, "insertAdjacentElement", [1]);
631
945
  wrapInsert(Range.prototype, "insertNode", [0]);
632
946
  wrapInsert(Range.prototype, "surroundContents", [0]);
947
+ // A select's add and its options' add (P130), and moveBefore wherever the engine defines it.
948
+ wrapInsert(typeof HTMLSelectElement === "function" ? HTMLSelectElement.prototype : null, "add", [0]);
949
+ wrapInsert(typeof HTMLOptionsCollection === "function" ? HTMLOptionsCollection.prototype : null, "add", [0]);
950
+ for (const proto of [Node.prototype, Element.prototype, Document.prototype, DocumentFragment.prototype]) {
951
+ if (callOf(hasOwn, proto, ["moveBefore"])) {
952
+ wrapInsert(proto, "moveBefore", [0]);
953
+ }
954
+ }
955
+ // The setters that put a node in place (P130): document.body, a table's tHead, tFoot and
956
+ // caption. The value is admitted as the insertion methods' arguments are, and a refused one
957
+ // refuses the set (the setter has no harmless stand-in: null would remove the table's own).
958
+ const refuseInsert = () => {
959
+ throw new NativeDOMException("This element can't be inserted here", "HierarchyRequestError");
960
+ };
961
+ const wrapNodeSetter = (proto, name) => {
962
+ const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined;
963
+ if (!descriptor || typeof descriptor.set !== "function") {
964
+ return;
965
+ }
966
+ try {
967
+ Object.defineProperty(proto, name, {
968
+ configurable: false,
969
+ enumerable: descriptor.enumerable,
970
+ get: descriptor.get,
971
+ set(value) {
972
+ if (!admit(value)) {
973
+ refuseInsert();
974
+ }
975
+ callOf(descriptor.set, this, [value]);
976
+ },
977
+ });
978
+ } catch (_) {
979
+ unfixed.push(name);
980
+ }
981
+ };
982
+ for (const proto of [Document.prototype, typeof HTMLDocument === "function" ? HTMLDocument.prototype : null]) {
983
+ if (proto !== null && callOf(hasOwn, proto, ["body"])) {
984
+ wrapNodeSetter(proto, "body");
985
+ }
986
+ }
987
+ for (const name of ["tHead", "tFoot", "caption"]) {
988
+ wrapNodeSetter(typeof HTMLTableElement === "function" ? HTMLTableElement.prototype : null, name);
989
+ }
990
+ // The insertion methods the HTML-parse wrappers below call: the locked wrappers just installed
991
+ // (admit runs inside them), taken now so an element can't shadow them with an own property and
992
+ // no spread reads a replaceable array iterator; each is given a prototype-less argument list.
993
+ const replaceChildrenElIn = Element.prototype.replaceChildren;
994
+ const replaceChildrenFragIn = DocumentFragment.prototype.replaceChildren;
995
+ const replaceWithIn = Element.prototype.replaceWith;
996
+ const beforeIn = Element.prototype.before;
997
+ const afterIn = Element.prototype.after;
998
+ const prependIn = Element.prototype.prepend;
999
+ const appendIn = Element.prototype.append;
633
1000
 
634
1001
  // Markup parsed in place: parsed first in a detached element of the same kind (so it parses as it
635
1002
  // would in place, and nothing in it is connected yet), guarded, then moved in.
636
1003
  const accessor = (proto, name) => (proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined);
637
1004
  const contextFor = (element) => {
638
- if (element === null || element.nodeType !== 1) {
639
- return document.createElement("div");
1005
+ if (typeOf(element) !== 1 || localNameOf === null || namespaceOf === null) {
1006
+ return callOf(createIn, document, ["div"]);
640
1007
  }
641
1008
  // A fresh element of the same kind; a custom element's own class is not run again.
642
- const name = element.localName.indexOf("-") === -1 ? element.localName : "div";
643
- return document.createElementNS(element.namespaceURI, name);
1009
+ const local = callOf(localNameOf, element, []);
1010
+ const name = callOf(indexIn, local, ["-"]) === -1 ? local : "div";
1011
+ return callOf(createNSIn, document, [callOf(namespaceOf, element, []), name]);
644
1012
  };
645
1013
  const innerHTMLs = [accessor(Element.prototype, "innerHTML"), accessor(typeof ShadowRoot === "function" ? ShadowRoot.prototype : null, "innerHTML")];
646
1014
  const setInner = (innerHTMLs[0] || innerHTMLs[1]).set;
647
1015
  const parseIn = (contextElement, html) => {
648
1016
  const box = contextFor(contextElement);
649
- setInner.call(box, String(html));
1017
+ callOf(setInner, box, [NativeString(html)]);
650
1018
  strip(box);
651
- return Array.from(box.childNodes);
1019
+ const children = childNodesOf === null ? box.childNodes : callOf(childNodesOf, box, []);
1020
+ const nodes = listOf();
1021
+ for (let i = 0, n = countOf(children); i < n; i += 1) {
1022
+ pushTo(nodes, children[i]);
1023
+ }
1024
+ return nodes;
652
1025
  };
653
- [Element.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null].forEach((proto, index) => {
1026
+ const innerHTMLProtos = [Element.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null];
1027
+ for (let index = 0; index < innerHTMLProtos.length; index += 1) {
1028
+ const proto = innerHTMLProtos[index];
654
1029
  const descriptor = innerHTMLs[index];
655
1030
  if (!proto || !descriptor || !descriptor.set) {
656
- return;
1031
+ continue;
657
1032
  }
658
1033
  Object.defineProperty(proto, "innerHTML", {
659
1034
  configurable: false,
660
1035
  enumerable: descriptor.enumerable,
661
1036
  get: descriptor.get,
662
1037
  set(html) {
663
- if (this.nodeType === 1 && this.localName === "template") {
664
- descriptor.set.call(this, html);
1038
+ // Which branch runs is read through the kept getters, so a replaced nodeType or localName
1039
+ // can't route a connected element past parseIn (and its strip) by posing as a template
1040
+ // whose markup goes in inert.
1041
+ if (typeOf(this) === 1 && isTemplate !== null && isTemplate(this)) {
1042
+ // An HTML template's markup goes into its inert content, stripped before the setter
1043
+ // returns (P130), as every read of the content is.
1044
+ callOf(descriptor.set, this, [html]);
1045
+ strip(callOf(templateContentOf, this, []));
665
1046
  return;
666
1047
  }
667
- this.replaceChildren(...parseIn(this.nodeType === 11 ? this.host || null : this, html));
1048
+ const forFragment = typeOf(this) === 11;
1049
+ callOf(forFragment ? replaceChildrenFragIn : replaceChildrenElIn, this, parseIn(forFragment ? this.host || null : this, html));
668
1050
  },
669
1051
  });
670
- });
1052
+ }
671
1053
  const outer = accessor(Element.prototype, "outerHTML");
672
1054
  if (outer && outer.set) {
673
1055
  Object.defineProperty(Element.prototype, "outerHTML", {
@@ -675,44 +1057,299 @@ export const SHELL_RUNTIME = String.raw`(() => {
675
1057
  enumerable: outer.enumerable,
676
1058
  get: outer.get,
677
1059
  set(html) {
678
- const parent = this.parentNode;
679
- if (parent === null || parent.nodeType === 9) {
680
- outer.set.call(this, html);
1060
+ const parent = parentNodeOf === null ? this.parentNode : callOf(parentNodeOf, this, []);
1061
+ if (parent === null || typeOf(parent) === 9) {
1062
+ callOf(outer.set, this, [html]);
681
1063
  return;
682
1064
  }
683
- this.replaceWith(...parseIn(parent.nodeType === 1 ? parent : null, html));
1065
+ callOf(replaceWithIn, this, parseIn(typeOf(parent) === 1 ? parent : null, html));
684
1066
  },
685
1067
  });
686
1068
  }
687
1069
  const insertAdjacentHTML = Element.prototype.insertAdjacentHTML;
688
1070
  lock(Element.prototype, "insertAdjacentHTML", function (position, html) {
689
- insertAdjacentHTML.call(this, position, "");
690
- const where = String(position).toLowerCase();
1071
+ // The position is read once: the empty insert that validates it and the branch that places the
1072
+ // parsed nodes use the same reading.
1073
+ const where = callOf(lowerOf, NativeString(position), []);
1074
+ callOf(insertAdjacentHTML, this, [where, ""]);
691
1075
  const outside = where === "beforebegin" || where === "afterend";
692
1076
  const nodes = parseIn(outside ? this.parentElement : this, html);
693
1077
  if (where === "beforebegin") {
694
- this.before(...nodes);
1078
+ callOf(beforeIn, this, nodes);
695
1079
  } else if (where === "afterbegin") {
696
- this.prepend(...nodes);
1080
+ callOf(prependIn, this, nodes);
697
1081
  } else if (where === "beforeend") {
698
- this.append(...nodes);
1082
+ callOf(appendIn, this, nodes);
699
1083
  } else {
700
- this.after(...nodes);
1084
+ callOf(afterIn, this, nodes);
701
1085
  }
702
1086
  });
703
- if (typeof Element.prototype.setHTML === "function") {
704
- lock(Element.prototype, "setHTML", function (html) {
705
- this.innerHTML = String(html);
1087
+ for (const proto of [Element.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null]) {
1088
+ if (proto !== null && callOf(hasOwn, proto, ["setHTML"]) && typeof proto.setHTML === "function") {
1089
+ lock(proto, "setHTML", function (html) {
1090
+ this.innerHTML = NativeString(html);
1091
+ });
1092
+ }
1093
+ }
1094
+ // A parser method this shell doesn't know (a later engine's) is refused rather than left open:
1095
+ // every name with "HTML" in it on the interfaces that take markup, other than the ones above.
1096
+ const KNOWN_HTML = bare(null);
1097
+ for (const name of ["innerHTML", "outerHTML", "insertAdjacentHTML", "setHTML", "setHTMLUnsafe", "getHTML", "parseHTMLUnsafe", "parseHTML"]) {
1098
+ KNOWN_HTML[name] = true;
1099
+ }
1100
+ const unknownMarkup = function () {
1101
+ throw new NativeDOMException("This way to add markup isn't available here: use innerHTML or DOM methods", "NotSupportedError");
1102
+ };
1103
+ for (const target of [Element.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null, Document.prototype, DocumentFragment.prototype, Document, Range.prototype]) {
1104
+ for (const name of target === null ? [] : Object.getOwnPropertyNames(target)) {
1105
+ const descriptor = Object.getOwnPropertyDescriptor(target, name);
1106
+ if (KNOWN_HTML[name] !== true && /HTML/.test(name) && descriptor && typeof descriptor.value === "function") {
1107
+ lock(target, name, unknownMarkup);
1108
+ }
1109
+ }
1110
+ }
1111
+
1112
+ // Every API that hands content a subtree it can insert later strips it before it returns it
1113
+ // (P130): a parsed document, a template's content, a contextual fragment, a transform's output,
1114
+ // an XHR's document, an imported or adopted node. A producer whose result is itself a frame-like
1115
+ // element (one importNode or adoptNode would return) refuses instead: there is nothing to strip
1116
+ // it from.
1117
+ const framedElement = (node) => typeOf(node) === 1 && callOf(matchesIn, node, [FRAMES]) && !keptFrame(node);
1118
+ const refuseFrame = () => {
1119
+ throw new NativeDOMException("Frame elements aren't available here", "NotSupportedError");
1120
+ };
1121
+ const argumentsOf = (args) => {
1122
+ const list = listOf();
1123
+ for (let i = 0; i < args.length; i += 1) {
1124
+ pushTo(list, args[i]);
1125
+ }
1126
+ return list;
1127
+ };
1128
+ const wrapProducer = (proto, name) => {
1129
+ const original = proto && callOf(hasOwn, proto, [name]) ? proto[name] : null;
1130
+ if (typeof original !== "function") {
1131
+ return;
1132
+ }
1133
+ lock(proto, name, function (...args) {
1134
+ const made = callOf(original, this, argumentsOf(args));
1135
+ strip(made);
1136
+ if (framedElement(made)) {
1137
+ refuseFrame();
1138
+ }
1139
+ return made;
1140
+ });
1141
+ };
1142
+ wrapProducer(DOMParser.prototype, "parseFromString");
1143
+ wrapProducer(typeof DOMImplementation === "function" ? DOMImplementation.prototype : null, "createHTMLDocument");
1144
+ wrapProducer(typeof DOMImplementation === "function" ? DOMImplementation.prototype : null, "createDocument");
1145
+ wrapProducer(Range.prototype, "createContextualFragment");
1146
+ wrapProducer(typeof XSLTProcessor === "function" ? XSLTProcessor.prototype : null, "transformToFragment");
1147
+ wrapProducer(typeof XSLTProcessor === "function" ? XSLTProcessor.prototype : null, "transformToDocument");
1148
+ // importNode's clone is stripped (where an engine has it on a shadow root too, there as well).
1149
+ wrapProducer(Document.prototype, "importNode");
1150
+ wrapProducer(typeof ShadowRoot === "function" ? ShadowRoot.prototype : null, "importNode");
1151
+ // adoptNode's node is stripped before it is adopted.
1152
+ const adoptNodeIn = Document.prototype.adoptNode;
1153
+ if (typeof adoptNodeIn === "function") {
1154
+ lock(Document.prototype, "adoptNode", function (...args) {
1155
+ if (framedElement(args[0])) {
1156
+ refuseFrame();
1157
+ }
1158
+ strip(args[0]);
1159
+ return callOf(adoptNodeIn, this, argumentsOf(args));
706
1160
  });
707
1161
  }
1162
+ const strippedGetter = (proto, name, documentsOnly) => {
1163
+ const descriptor = accessor(proto, name);
1164
+ if (!descriptor || typeof descriptor.get !== "function") {
1165
+ return;
1166
+ }
1167
+ try {
1168
+ Object.defineProperty(proto, name, {
1169
+ configurable: false,
1170
+ enumerable: descriptor.enumerable,
1171
+ get() {
1172
+ const value = callOf(descriptor.get, this, []);
1173
+ if (!documentsOnly || typeOf(value) === 9) {
1174
+ strip(value);
1175
+ }
1176
+ return value;
1177
+ },
1178
+ set: descriptor.set,
1179
+ });
1180
+ } catch (_) {
1181
+ unfixed.push(name);
1182
+ }
1183
+ };
1184
+ strippedGetter(typeof HTMLTemplateElement === "function" ? HTMLTemplateElement.prototype : null, "content", false);
1185
+ strippedGetter(typeof XMLHttpRequest === "function" ? XMLHttpRequest.prototype : null, "responseXML", true);
1186
+ strippedGetter(typeof XMLHttpRequest === "function" ? XMLHttpRequest.prototype : null, "response", true);
1187
+
1188
+ // Under the default config (no nested frames) no frame-like element exists anywhere content
1189
+ // reaches (P130): the parser's are stripped (above), and none can be made. createElement and
1190
+ // createElementNS refuse a FRAMES name, in any case and any namespace (the local name after a
1191
+ // prefix included), as document.write is refused; so does a customized built-in that extends
1192
+ // one (its constructor would make one). The name is read once, and that reading is what the
1193
+ // platform is given. Under nestedFrames "own" (P128) these stay as they are: an iframe is made,
1194
+ // and the guards above decide when it is connected or changed.
1195
+ const refuseFrameCreation = (proto, name, nameAt) => {
1196
+ const original = proto && callOf(hasOwn, proto, [name]) ? proto[name] : null;
1197
+ if (typeof original !== "function") {
1198
+ return;
1199
+ }
1200
+ lock(proto, name, function (...args) {
1201
+ const fixed = listOf();
1202
+ for (let i = 0; i < args.length; i += 1) {
1203
+ pushTo(fixed, i === nameAt ? NativeString(once(args[i])) : i < nameAt ? once(args[i]) : args[i]);
1204
+ }
1205
+ if (fixed.length > nameAt && frameCapableName(fixed[nameAt])) {
1206
+ refuseFrame();
1207
+ }
1208
+ return callOf(original, this, fixed);
1209
+ });
1210
+ };
1211
+ if (!ownFrames) {
1212
+ for (const proto of [Document.prototype, typeof ShadowRoot === "function" ? ShadowRoot.prototype : null]) {
1213
+ refuseFrameCreation(proto, "createElement", 0);
1214
+ refuseFrameCreation(proto, "createElementNS", 1);
1215
+ }
1216
+ const registry = typeof CustomElementRegistry === "function" ? CustomElementRegistry.prototype : null;
1217
+ const defineIn = registry === null ? null : registry.define;
1218
+ if (typeof defineIn === "function") {
1219
+ lock(registry, "define", function (...args) {
1220
+ const fixed = argumentsOf(args);
1221
+ if (fixed.length > 2 && objectLike(fixed[2])) {
1222
+ // The options are read once, into a fresh object with no prototype (extends, its one
1223
+ // field), which is what the platform is given.
1224
+ const read = fixed[2].extends;
1225
+ const options = bare(null);
1226
+ if (read !== undefined) {
1227
+ options.extends = NativeString(once(read));
1228
+ if (frameCapableName(options.extends)) {
1229
+ refuseFrame();
1230
+ }
1231
+ }
1232
+ fixed[2] = options;
1233
+ }
1234
+ return callOf(defineIn, this, fixed);
1235
+ });
1236
+ }
1237
+ }
708
1238
  // insertHTML parses markup outside these guards; copy, cut and paste reach the clipboard (P051).
709
1239
  const REFUSED_COMMANDS = ["inserthtml", "copy", "cut", "paste"];
710
1240
  const execCommand = Document.prototype.execCommand;
711
1241
  if (typeof execCommand === "function") {
1242
+ const refused = bare(null);
1243
+ for (let i = 0; i < REFUSED_COMMANDS.length; i += 1) {
1244
+ refused[REFUSED_COMMANDS[i]] = true;
1245
+ }
712
1246
  lock(Document.prototype, "execCommand", function (command, ...rest) {
713
- return REFUSED_COMMANDS.indexOf(String(command).toLowerCase()) !== -1 ? false : execCommand.call(this, command, ...rest);
1247
+ // The command is read once, here, and that same text is both the one checked and the one run:
1248
+ // a command whose name reads "bold" when checked and "insertHTML" when the platform reads it
1249
+ // can't get past the refusal.
1250
+ const cmd = NativeString(command);
1251
+ if (refused[callOf(lowerOf, cmd, [])] === true) {
1252
+ return false;
1253
+ }
1254
+ const args = listOf();
1255
+ pushTo(args, cmd);
1256
+ for (let i = 0; i < rest.length; i += 1) {
1257
+ pushTo(args, rest[i]);
1258
+ }
1259
+ return callOf(execCommand, this, args);
714
1260
  });
715
1261
  }
1262
+ // Editing that brings markup in (P130): a paste, a drop, a replacement or a yank whose data
1263
+ // carries any type but plain text (text/html above all) is cancelled before the editor acts on
1264
+ // it, and only its plain text goes in, through the editor's own insertText, which carries no
1265
+ // markup. The first listener there is (the shell's, on window, capturing), on the platform's
1266
+ // own getters, kept now; only the browser's own events (isTrusted) are acted on. Composition
1267
+ // (insertCompositionText) can't be cancelled, and is text alone.
1268
+ const RICH_INPUTS = bare(null);
1269
+ for (const name of ["insertFromPaste", "insertFromPasteAsQuotation", "insertFromDrop", "insertReplacementText", "insertFromYank"]) {
1270
+ RICH_INPUTS[name] = true;
1271
+ }
1272
+ const listenIn = EventTarget.prototype.addEventListener;
1273
+ const inputProto = typeof InputEvent === "function" ? InputEvent.prototype : null;
1274
+ const inputTypeOf = getterOf(inputProto, "inputType");
1275
+ const dataTransferOf = getterOf(inputProto, "dataTransfer");
1276
+ const targetRangesIn = inputProto !== null && typeof inputProto.getTargetRanges === "function" ? inputProto.getTargetRanges : null;
1277
+ const transferProto = typeof DataTransfer === "function" ? DataTransfer.prototype : null;
1278
+ const transferTypesOf = getterOf(transferProto, "types");
1279
+ const transferDataIn = transferProto !== null && typeof transferProto.getData === "function" ? transferProto.getData : null;
1280
+ const cancelableOf = getterOf(Event.prototype, "cancelable");
1281
+ const rangeProto = typeof AbstractRange === "function" ? AbstractRange.prototype : typeof StaticRange === "function" ? StaticRange.prototype : null;
1282
+ const rangeEnds = [getterOf(rangeProto, "startContainer"), getterOf(rangeProto, "startOffset"), getterOf(rangeProto, "endContainer"), getterOf(rangeProto, "endOffset")];
1283
+ const selectionProto = typeof Selection === "function" ? Selection.prototype : null;
1284
+ const removeAllRangesIn = selectionProto === null ? null : selectionProto.removeAllRanges;
1285
+ const addRangeIn = selectionProto === null ? null : selectionProto.addRange;
1286
+ const getSelectionIn = Document.prototype.getSelection;
1287
+ const createRangeIn = Document.prototype.createRange;
1288
+ const setStartIn = Range.prototype.setStart;
1289
+ const setEndIn = Range.prototype.setEnd;
1290
+ // Where the editor would have put it (a drop's point, a replaced word): the event's first target
1291
+ // range, made the selection, so insertText puts the text there.
1292
+ const placeAt = (event) => {
1293
+ if (targetRangesIn === null || typeof removeAllRangesIn !== "function" || typeof addRangeIn !== "function" || rangeEnds[0] === null || rangeEnds[1] === null || rangeEnds[2] === null || rangeEnds[3] === null) {
1294
+ return;
1295
+ }
1296
+ try {
1297
+ const ranges = callOf(targetRangesIn, event, []);
1298
+ if (ranges.length === 0) {
1299
+ return;
1300
+ }
1301
+ const target = ranges[0];
1302
+ const range = callOf(createRangeIn, document, []);
1303
+ callOf(setStartIn, range, [callOf(rangeEnds[0], target, []), callOf(rangeEnds[1], target, [])]);
1304
+ callOf(setEndIn, range, [callOf(rangeEnds[2], target, []), callOf(rangeEnds[3], target, [])]);
1305
+ const selection = callOf(getSelectionIn, document, []);
1306
+ callOf(removeAllRangesIn, selection, []);
1307
+ callOf(addRangeIn, selection, [range]);
1308
+ } catch (_) {}
1309
+ };
1310
+ if (inputTypeOf !== null && dataTransferOf !== null && transferTypesOf !== null && transferDataIn !== null) {
1311
+ callOf(listenIn, window, [
1312
+ "beforeinput",
1313
+ (event) => {
1314
+ if (event.isTrusted !== true) {
1315
+ return;
1316
+ }
1317
+ let rich = false;
1318
+ let text = "";
1319
+ try {
1320
+ if (RICH_INPUTS[callOf(inputTypeOf, event, [])] !== true) {
1321
+ return;
1322
+ }
1323
+ const data = callOf(dataTransferOf, event, []);
1324
+ if (data === null) {
1325
+ return;
1326
+ }
1327
+ const types = callOf(transferTypesOf, data, []);
1328
+ for (let i = 0; i < types.length; i += 1) {
1329
+ if (types[i] !== "text/plain") {
1330
+ rich = true;
1331
+ }
1332
+ }
1333
+ if (!rich) {
1334
+ return;
1335
+ }
1336
+ text = NativeString(callOf(transferDataIn, data, ["text/plain"]));
1337
+ } catch (_) {
1338
+ // Unreadable: it is cancelled, and nothing of it goes in.
1339
+ text = "";
1340
+ }
1341
+ if (cancelableOf !== null && callOf(cancelableOf, event, []) !== true) {
1342
+ return;
1343
+ }
1344
+ callOf(preventNavigation, event, []);
1345
+ if (text !== "" && typeof execCommand === "function") {
1346
+ placeAt(event);
1347
+ callOf(execCommand, document, ["insertText", false, text]);
1348
+ }
1349
+ },
1350
+ true,
1351
+ ]);
1352
+ }
716
1353
 
717
1354
  // The clipboard is the host's to write (P051): content can neither write nor read it. A copy
718
1355
  // the person makes (their keys, their menu) copies their selection as the browser makes it: no
@@ -733,36 +1370,61 @@ export const SHELL_RUNTIME = String.raw`(() => {
733
1370
 
734
1371
  // A connected link or meta can't become a guarded one: the change is tried on a detached copy
735
1372
  // first, and if the copy would be guarded, the element leaves the document before it changes.
736
- const watched = (element) => element && element.nodeType === 1 && (element.localName === "link" || element.localName === "meta");
1373
+ // Nor can a kept iframe (P128) become one that isn't the page's own (a src elsewhere, its
1374
+ // srcdoc dropped).
1375
+ const watched = (element) => {
1376
+ if (typeOf(element) !== 1 || localNameOf === null) {
1377
+ return false;
1378
+ }
1379
+ const name = callOf(localNameOf, element, []);
1380
+ return name === "link" || name === "meta" || (ownFrames && name === "iframe");
1381
+ };
737
1382
  const beforeChange = (element, change) => {
738
- if (!watched(element) || !element.isConnected) {
1383
+ if (!watched(element) || !connected(element)) {
739
1384
  return;
740
1385
  }
741
- const copy = element.cloneNode(false);
1386
+ const copy = callOf(cloneNodeIn, element, [false]);
742
1387
  try {
743
1388
  change(copy);
744
1389
  } catch (_) {
745
1390
  return;
746
1391
  }
747
- if (copy.matches(GUARDED)) {
748
- element.remove();
1392
+ if (guarded(copy)) {
1393
+ callOf(removeIn, element, []);
749
1394
  }
750
1395
  };
751
- const guardMethod = (proto, name, change) => {
1396
+ // The names and values the check tests are pinned (once) before the check, and the same pinned
1397
+ // list is what the platform's own method is then given: the copy the guard inspects and the real
1398
+ // element can't be set from two different readings of the same argument. The strings parameter
1399
+ // names the DOMString positions to pin (an element or a boolean goes on as it is).
1400
+ const guardMethod = (proto, name, strings, change) => {
752
1401
  const original = proto && proto[name];
753
1402
  if (typeof original !== "function") {
754
1403
  return;
755
1404
  }
1405
+ const pin = bare(null);
1406
+ for (let i = 0; i < strings.length; i += 1) {
1407
+ pin[strings[i]] = true;
1408
+ }
756
1409
  lock(proto, name, function (...args) {
757
- beforeChange(this, (copy) => change(copy, args, original));
758
- return original.apply(this, args);
1410
+ const fixed = listOf();
1411
+ for (let i = 0; i < args.length; i += 1) {
1412
+ pushTo(fixed, pin[i] === true ? once(args[i]) : args[i]);
1413
+ }
1414
+ beforeChange(this, (copy) => change(copy, fixed, original));
1415
+ return callOf(original, this, fixed);
759
1416
  });
760
1417
  };
761
- for (const name of ["setAttribute", "setAttributeNS", "toggleAttribute", "removeAttribute", "removeAttributeNS"]) {
762
- guardMethod(Element.prototype, name, (copy, args, original) => original.apply(copy, args));
1418
+ for (const [name, strings] of [["setAttribute", [0, 1]], ["setAttributeNS", [0, 1, 2]], ["toggleAttribute", [0]], ["removeAttribute", [0]], ["removeAttributeNS", [0, 1]]]) {
1419
+ guardMethod(Element.prototype, name, strings, (copy, args, original) => callOf(original, copy, args));
763
1420
  }
764
1421
  for (const name of ["setAttributeNode", "setAttributeNodeNS"]) {
765
- guardMethod(Element.prototype, name, (copy, args) => copy.setAttributeNS(args[0].namespaceURI, args[0].name, args[0].value));
1422
+ // The attribute node's own name, namespace and value are read through the kept getters (one
1423
+ // stored string each), both to check the copy and to set it; the real call takes the node.
1424
+ guardMethod(Element.prototype, name, [], (copy, args) => {
1425
+ const part = attrParts(args[0]);
1426
+ callOf(setAttributeNSIn, copy, [part.namespace, part.name, part.value]);
1427
+ });
766
1428
  }
767
1429
  for (const [proto, name] of [[Attr.prototype, "value"], [Node.prototype, "nodeValue"], [Node.prototype, "textContent"]]) {
768
1430
  const descriptor = accessor(proto, name);
@@ -774,11 +1436,13 @@ export const SHELL_RUNTIME = String.raw`(() => {
774
1436
  enumerable: descriptor.enumerable,
775
1437
  get: descriptor.get,
776
1438
  set(value) {
777
- if (this.nodeType === 2 && this.ownerElement) {
778
- const attribute = this;
779
- beforeChange(attribute.ownerElement, (copy) => copy.setAttributeNS(attribute.namespaceURI, attribute.name, String(value)));
1439
+ const v = once(value);
1440
+ const owner = typeOf(this) === 2 && ownerElementOf !== null ? callOf(ownerElementOf, this, []) : null;
1441
+ if (owner !== null) {
1442
+ const part = attrParts(this);
1443
+ beforeChange(owner, (copy) => callOf(setAttributeNSIn, copy, [part.namespace, part.name, NativeString(v)]));
780
1444
  }
781
- descriptor.set.call(this, value);
1445
+ callOf(descriptor.set, this, [v]);
782
1446
  },
783
1447
  });
784
1448
  }
@@ -793,17 +1457,18 @@ export const SHELL_RUNTIME = String.raw`(() => {
793
1457
  configurable: false,
794
1458
  enumerable: descriptor.enumerable,
795
1459
  get() {
796
- const value = descriptor.get.call(this);
1460
+ const value = callOf(descriptor.get, this, []);
797
1461
  if (value !== null && typeof value === "object") {
798
- owners.set(value, this);
1462
+ callOf(weakMapSet, owners, [value, this]);
799
1463
  }
800
1464
  return value;
801
1465
  },
802
1466
  // relList = "…" forwards to the list's value, natively: guarded here instead.
803
1467
  set: descriptor.set
804
1468
  ? function (value) {
805
- beforeChange(this, (copy) => descriptor.set.call(copy, value));
806
- descriptor.set.call(this, value);
1469
+ const v = once(value);
1470
+ beforeChange(this, (copy) => callOf(descriptor.set, copy, [v]));
1471
+ callOf(descriptor.set, this, [v]);
807
1472
  }
808
1473
  : undefined,
809
1474
  });
@@ -812,6 +1477,8 @@ export const SHELL_RUNTIME = String.raw`(() => {
812
1477
  for (const proto of [
813
1478
  typeof HTMLLinkElement === "function" ? HTMLLinkElement.prototype : null,
814
1479
  typeof HTMLMetaElement === "function" ? HTMLMetaElement.prototype : null,
1480
+ // A kept iframe's src and srcdoc, set through their properties (P128).
1481
+ ownFrames && typeof HTMLIFrameElement === "function" ? HTMLIFrameElement.prototype : null,
815
1482
  ]) {
816
1483
  remember(proto, "relList");
817
1484
  for (const name of Object.getOwnPropertyNames(proto || {})) {
@@ -822,8 +1489,9 @@ export const SHELL_RUNTIME = String.raw`(() => {
822
1489
  enumerable: descriptor.enumerable,
823
1490
  get: descriptor.get,
824
1491
  set(value) {
825
- beforeChange(this, (copy) => descriptor.set.call(copy, value));
826
- descriptor.set.call(this, value);
1492
+ const v = once(value);
1493
+ beforeChange(this, (copy) => callOf(descriptor.set, copy, [v]));
1494
+ callOf(descriptor.set, this, [v]);
827
1495
  },
828
1496
  });
829
1497
  }
@@ -834,15 +1502,24 @@ export const SHELL_RUNTIME = String.raw`(() => {
834
1502
  if (typeof original !== "function") {
835
1503
  continue;
836
1504
  }
1505
+ const isSet = callOf(indexIn, name, ["set"]) === 0;
837
1506
  lock(NamedNodeMap.prototype, name, function (...args) {
838
- beforeChange(owners.get(this), (copy) => {
839
- if (name.indexOf("set") === 0) {
840
- copy.setAttributeNS(args[0].namespaceURI, args[0].name, args[0].value);
1507
+ // A removal names an attribute by a string pinned once; a set takes a node, whose own name,
1508
+ // namespace and value are read once through the kept getters. The copy and the real map act
1509
+ // on the same readings.
1510
+ const fixed = listOf();
1511
+ for (let i = 0; i < args.length; i += 1) {
1512
+ pushTo(fixed, isSet ? args[i] : once(args[i]));
1513
+ }
1514
+ beforeChange(callOf(weakMapGet, owners, [this]), (copy) => {
1515
+ if (isSet) {
1516
+ const part = attrParts(fixed[0]);
1517
+ callOf(setAttributeNSIn, copy, [part.namespace, part.name, part.value]);
841
1518
  } else {
842
- copy.removeAttribute(args[args.length - 1]);
1519
+ callOf(removeAttributeIn, copy, [fixed[fixed.length - 1]]);
843
1520
  }
844
1521
  });
845
- return original.apply(this, args);
1522
+ return callOf(original, this, fixed);
846
1523
  });
847
1524
  }
848
1525
  const tokens = typeof DOMTokenList === "function" ? DOMTokenList.prototype : null;
@@ -850,9 +1527,15 @@ export const SHELL_RUNTIME = String.raw`(() => {
850
1527
  const original = tokens && tokens[name];
851
1528
  if (typeof original === "function") {
852
1529
  lock(tokens, name, function (...args) {
853
- const element = owners.get(this);
854
- beforeChange(element, (copy) => original.apply(copy.relList, args));
855
- return original.apply(this, args);
1530
+ // Each token is pinned once; the copy's list and the real list are changed by the same
1531
+ // tokens (a token that reads one way when checked and another when applied can't slip in).
1532
+ const fixed = listOf();
1533
+ for (let i = 0; i < args.length; i += 1) {
1534
+ pushTo(fixed, once(args[i]));
1535
+ }
1536
+ const element = callOf(weakMapGet, owners, [this]);
1537
+ beforeChange(element, (copy) => callOf(original, copy.relList, fixed));
1538
+ return callOf(original, this, fixed);
856
1539
  });
857
1540
  }
858
1541
  }
@@ -863,8 +1546,9 @@ export const SHELL_RUNTIME = String.raw`(() => {
863
1546
  enumerable: tokenValue.enumerable,
864
1547
  get: tokenValue.get,
865
1548
  set(value) {
866
- beforeChange(owners.get(this), (copy) => tokenValue.set.call(copy.relList, value));
867
- tokenValue.set.call(this, value);
1549
+ const v = once(value);
1550
+ beforeChange(callOf(weakMapGet, owners, [this]), (copy) => callOf(tokenValue.set, copy.relList, [v]));
1551
+ callOf(tokenValue.set, this, [v]);
868
1552
  },
869
1553
  });
870
1554
  }
@@ -1096,6 +1780,8 @@ export const SHELL_RUNTIME = String.raw`(() => {
1096
1780
 
1097
1781
  __ANNOTATE__
1098
1782
 
1783
+ __FIND__
1784
+
1099
1785
  if (plan.protocol !== "shell") {
1100
1786
  // A view that speaks for itself.
1101
1787
  if (typeof plan.document === "string") {
@@ -1529,7 +2215,8 @@ export const SHELL_RUNTIME = String.raw`(() => {
1529
2215
  }
1530
2216
  break;
1531
2217
  default:
1532
- if (data.id !== undefined) {
2218
+ // Find's own request is answered by the find runtime (P131), where the config declares it.
2219
+ if (data.id !== undefined && !(data.method === "porthole/find.query" && declared("find"))) {
1533
2220
  send({ id: data.id, error: { code: -32601, message: String(data.method) + " isn't offered here" } });
1534
2221
  }
1535
2222
  break;