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