@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
@@ -3,7 +3,7 @@ import type { LimitId } from "../guide/limits.ts";
3
3
  import type { LaunchedDisplay } from "./index.ts";
4
4
  import { presets } from "../presets/presets.ts";
5
5
  import { resolveTheme } from "../theme/variables.ts";
6
- import { attack, inline, js, type Probe } from "./kit.ts";
6
+ import { attack, inline, js, noteRefused, type Probe } from "./kit.ts";
7
7
  import { settle } from "./oracles.ts";
8
8
 
9
9
  /**
@@ -660,8 +660,10 @@ export const LIMIT_PROBES: readonly Probe[] = [
660
660
  document.getElementById("go").addEventListener("click", async () => {
661
661
  try { document.write("<p>x</p>"); r.write = "wrote"; } catch (e) { r.write = "throws"; }
662
662
  try { document.open(); r.open = "opened"; } catch (e) { r.open = "throws"; }
663
- const frame = document.createElement("iframe");
664
- document.body.append(frame);
663
+ // Refused at creation under the default config (P130): the frame can't exist.
664
+ let frame = null;
665
+ try { frame = document.createElement("iframe"); } catch (e) { if (!e || e.name !== "NotSupportedError") throw e; r.refused = ["iframe"]; }
666
+ if (frame) document.body.append(frame);
665
667
  await new Promise((resolve) => setTimeout(resolve, 100));
666
668
  r.frames = document.querySelectorAll("iframe, object, embed").length;
667
669
  r.fullscreen = await document.documentElement.requestFullscreen().then(() => "entered", (e) => "rejected");
@@ -671,8 +673,9 @@ export const LIMIT_PROBES: readonly Probe[] = [
671
673
  </script>`,
672
674
  });
673
675
  await click(display, "#go");
676
+ const shell = await replacedOrRecorded(display, "#go");
674
677
  expect(
675
- await replacedOrRecorded(display, "#go"),
678
+ shell,
676
679
  "probe: write and open throw, nested frames are removed, full screen is closed",
677
680
  ).toMatchObject({
678
681
  write: "throws",
@@ -683,6 +686,7 @@ export const LIMIT_PROBES: readonly Probe[] = [
683
686
  expect(["rejected", "absent"], "probe: the clipboard was written").toContain(
684
687
  (await recorded(display)).clipboard,
685
688
  );
689
+ noteRefused(context, shell);
686
690
  },
687
691
  },
688
692
  {
@@ -731,6 +735,7 @@ export const LIMIT_CHECKS: { readonly [Id in LimitId]: readonly string[] } = {
731
735
  workers: ["14.workers", "3.webrtc"],
732
736
  sound: ["14.sound"],
733
737
  address: ["14.address", "served.domain.address"],
734
- shell: ["14.shell", "4.document-write", "4.light-dom"],
738
+ // A page's own frames, where the config opts in (P128): what loads, and what still doesn't.
739
+ shell: ["14.shell", "4.document-write", "4.light-dom", "4.own-external"],
735
740
  storage: ["14.storage", "served.domain.storage-scope"],
736
741
  };
@@ -11,7 +11,7 @@ import {
11
11
  import { presets } from "../presets/presets.ts";
12
12
  import { resolveTheme } from "../theme/variables.ts";
13
13
  import type { ConformanceHost, LaunchedDisplay, LeakSuiteOptions } from "./index.ts";
14
- import { attack, inline, js, type Probe, type ProbeContext } from "./kit.ts";
14
+ import { attack, inline, js, noteRefused, type Probe, type ProbeContext } from "./kit.ts";
15
15
  import { BEHAVIOR_PROBES } from "./behavior.ts";
16
16
  import { CLIPBOARD_PROBES } from "./clipboard.ts";
17
17
  import { LIMIT_PROBES } from "./limits.ts";
@@ -77,6 +77,7 @@ async function expectNoChild(
77
77
  expect(verdict.childRan ?? false, "probe: a nested frame's script ran").toBe(false);
78
78
  expect(verdict.frames ?? 0, "probe: a nested frame is still in the tree").toBe(0);
79
79
  expect(udp.packets(), "probe: STUN packets reached the oracle").toBe(0);
80
+ noteRefused(context, verdict);
80
81
  if (verdict.reached !== undefined || verdict.blocked !== undefined) {
81
82
  context.measured(
82
83
  `${context.engine}: a new frame's realm, in the task that added it, was ${verdict.blocked === undefined ? `reachable (RTCPeerConnection: ${JSON.stringify(verdict.reached)})` : `unreachable (${JSON.stringify(verdict.blocked)})`}`,
@@ -90,7 +91,7 @@ const childSetup = (stun: string) => `
90
91
  r.childRan = false;
91
92
  window.addEventListener("message", (event) => { if (event.data && event.data.tag === "child-ran") r.childRan = true; });
92
93
  const child = ${js(childDocument(stun))};
93
- const makeFrame = () => { const f = document.createElement("iframe"); f.setAttribute("srcdoc", child); return f; };`;
94
+ const makeFrame = () => { const f = created("iframe"); if (f) f.setAttribute("srcdoc", child); return f; };`;
94
95
 
95
96
  /**
96
97
  * A navigated document's beacon to an allowed witness, heard only if that document ran: its first
@@ -595,7 +596,8 @@ export const PROBES: readonly Probe[] = [
595
596
  "light-dom",
596
597
  "a srcdoc frame appended to the document",
597
598
  () => `
598
- document.body.append(makeFrame());
599
+ const f = makeFrame();
600
+ if (f) document.body.append(f);
599
601
  await wait(50);
600
602
  r.frames = document.querySelectorAll("iframe").length;`,
601
603
  ),
@@ -603,16 +605,18 @@ export const PROBES: readonly Probe[] = [
603
605
  "sync-realm",
604
606
  "reaching a new frame's realm in the same task it was added",
605
607
  (stun) => `
606
- const f = document.createElement("iframe");
607
- document.body.append(f);
608
- try {
609
- const w = window[window.length - 1] || f.contentWindow;
610
- r.reached = typeof (w && w.RTCPeerConnection);
611
- const p = new w.RTCPeerConnection({ iceServers: [{ urls: ${js(stun)} }], iceCandidatePoolSize: 4 });
612
- p.createDataChannel("x");
613
- p.createOffer().then((o) => p.setLocalDescription(o));
614
- r.childRan = true;
615
- } catch (e) { r.blocked = String(e && e.name); }
608
+ const f = created("iframe");
609
+ if (f) {
610
+ document.body.append(f);
611
+ try {
612
+ const w = window[window.length - 1] || f.contentWindow;
613
+ r.reached = typeof (w && w.RTCPeerConnection);
614
+ const p = new w.RTCPeerConnection({ iceServers: [{ urls: ${js(stun)} }], iceCandidatePoolSize: 4 });
615
+ p.createDataChannel("x");
616
+ p.createOffer().then((o) => p.setLocalDescription(o));
617
+ r.childRan = true;
618
+ } catch (e) { r.blocked = String(e && e.name); }
619
+ }
616
620
  await wait(50);
617
621
  r.frames = document.querySelectorAll("iframe").length;`,
618
622
  ),
@@ -623,7 +627,8 @@ export const PROBES: readonly Probe[] = [
623
627
  const host = document.createElement("div");
624
628
  document.body.append(host);
625
629
  const root = host.attachShadow({ mode: "open" });
626
- root.append(makeFrame());
630
+ const f = makeFrame();
631
+ if (f) root.append(f);
627
632
  await wait(50);
628
633
  r.frames = root.querySelectorAll("iframe").length;`,
629
634
  ),
@@ -635,7 +640,8 @@ export const PROBES: readonly Probe[] = [
635
640
  document.body.append(host);
636
641
  const root = host.attachShadow({ mode: "closed" });
637
642
  root.innerHTML = '<p>shadow</p>';
638
- root.append(makeFrame());
643
+ const f = makeFrame();
644
+ if (f) root.append(f);
639
645
  await wait(50);
640
646
  r.frames = root.querySelectorAll("iframe").length;`,
641
647
  ),
@@ -649,7 +655,8 @@ export const PROBES: readonly Probe[] = [
649
655
  const inner = document.createElement("div");
650
656
  first.append(inner);
651
657
  const second = inner.attachShadow({ mode: "open" });
652
- second.append(makeFrame());
658
+ const f = makeFrame();
659
+ if (f) second.append(f);
653
660
  await wait(50);
654
661
  r.frames = second.querySelectorAll("iframe").length;`,
655
662
  ),
@@ -703,13 +710,17 @@ export const PROBES: readonly Probe[] = [
703
710
  "plugins",
704
711
  "object and embed elements holding a document",
705
712
  () => `
706
- const object = document.createElement("object");
707
- object.type = "text/html";
708
- object.data = "data:text/html," + encodeURIComponent(child);
709
- const embed = document.createElement("embed");
710
- embed.type = "text/html";
711
- embed.src = "data:text/html," + encodeURIComponent(child);
712
- document.body.append(object, embed);
713
+ const object = created("object");
714
+ if (object) {
715
+ object.type = "text/html";
716
+ object.data = "data:text/html," + encodeURIComponent(child);
717
+ }
718
+ const embed = created("embed");
719
+ if (embed) {
720
+ embed.type = "text/html";
721
+ embed.src = "data:text/html," + encodeURIComponent(child);
722
+ }
723
+ document.body.append(...[object, embed].filter((each) => each !== null));
713
724
  await wait(50);
714
725
  r.frames = document.querySelectorAll("object, embed").length;`,
715
726
  ),
@@ -751,6 +762,115 @@ export const PROBES: readonly Probe[] = [
751
762
  },
752
763
  },
753
764
 
765
+ // ── 4, opted in: a page's own frames (P128) ────────────────────────────────────────────────
766
+ // A host that sets `nestedFrames: "own"` lets srcdoc frames (and, served, frames of the page's
767
+ // own files: leak/served/files.spec.ts) load and run; every other frame stays out. These run
768
+ // under an opaque inline widget, where they check what stays out. A srcdoc frame's scripts don't
769
+ // run there (measured, all three engines: the child inherits the frame's nonce policy), so that
770
+ // a kept frame runs is the served case's to show.
771
+ {
772
+ id: "4.own-external",
773
+ item: 4,
774
+ title:
775
+ "a page's own frames, opted in (P128): a frame of another site, a plugin, a frame with no document of its own: none stays or loads",
776
+ async run(context) {
777
+ const canary = await context.http();
778
+ const c = canary.origin;
779
+ const display = await context.launch({
780
+ config: inline({ nestedFrames: "own" }),
781
+ content: attack(
782
+ `
783
+ const away = document.createElement("iframe");
784
+ away.src = ${js(`${c}/made.html?d=secret`)};
785
+ document.body.append(away);
786
+ const blank = document.createElement("iframe");
787
+ document.body.append(blank);
788
+ const holder = document.createElement("div");
789
+ holder.innerHTML = ${js(`<iframe src="${c}/parsed.html?d=secret"></iframe><iframe src="parsed-relative.html"></iframe><object data="${c}/object.html" type="text/html"></object><embed src="${c}/embed.html" type="text/html"><iframe src="data:text/html,<p>x</p>"></iframe>`)};
790
+ document.body.append(holder);
791
+ await wait(1200);
792
+ r.blankKept = blank.isConnected;
793
+ r.frames = document.querySelectorAll("iframe, object, embed").length;`,
794
+ `<iframe src="${c}/markup.html?d=secret"></iframe>`,
795
+ ),
796
+ });
797
+ const verdict = await context.result(display, 15_000);
798
+ await settle(1_000);
799
+ expect(verdict.error, "the content's own code failed").toBeUndefined();
800
+ expect(verdict.frames, "probe: a frame that isn't the content's own is in the tree").toBe(0);
801
+ expect(verdict.blankKept, "probe: a frame with no document of its own was kept").toBe(false);
802
+ expect(canary.requests(), "probe: a frame reached the canary").toEqual([]);
803
+ expect(context.requestsTo(c), "probe: the page requested the canary").toEqual([]);
804
+ },
805
+ },
806
+ {
807
+ id: "4.own-turned",
808
+ item: 4,
809
+ title:
810
+ "a page's own frames, opted in (P128): a kept frame turned to another site leaves before it goes",
811
+ async run(context) {
812
+ const canary = await context.http();
813
+ const c = canary.origin;
814
+ const display = await context.launch({
815
+ config: inline({ nestedFrames: "own" }),
816
+ content: attack(`
817
+ const make = () => { const f = document.createElement("iframe"); f.srcdoc = "<p>kept</p>"; document.body.append(f); return f; };
818
+ const dropped = make();
819
+ const attribute = make();
820
+ const named = make();
821
+ r.kept = document.querySelectorAll("iframe").length;
822
+ // Its srcdoc wins while it has one: a src alone changes nothing.
823
+ dropped.src = ${js(`${c}/dropped.html?d=secret`)};
824
+ r.keptWithSrc = dropped.isConnected;
825
+ dropped.removeAttribute("srcdoc");
826
+ attribute.setAttribute("src", ${js(`${c}/attribute.html?d=secret`)});
827
+ attribute.attributes.removeNamedItem("srcdoc");
828
+ named.toggleAttribute("srcdoc");
829
+ named.setAttribute("src", ${js(`${c}/named.html?d=secret`)});
830
+ await wait(1200);
831
+ r.frames = document.querySelectorAll("iframe").length;`),
832
+ });
833
+ const verdict = await context.result(display, 15_000);
834
+ await settle(1_000);
835
+ expect(verdict.error, "the content's own code failed").toBeUndefined();
836
+ expect(verdict.kept, "the content's own srcdoc frames were kept").toBe(3);
837
+ expect(verdict.keptWithSrc, "a srcdoc frame given a src was kept").toBe(true);
838
+ expect(verdict.frames, "probe: a frame turned to another site is in the tree").toBe(0);
839
+ expect(canary.requests(), "probe: a turned frame reached the canary").toEqual([]);
840
+ expect(context.requestsTo(c), "probe: the page requested the canary").toEqual([]);
841
+ },
842
+ },
843
+ {
844
+ id: "4.own-default",
845
+ item: 4,
846
+ title:
847
+ 'no nested frame runs by default (P128): what nestedFrames "own" would keep is removed without it',
848
+ async run(context) {
849
+ const udp = await context.udp();
850
+ const child = childDocument(udp.stun).replace(/"/gu, "&quot;");
851
+ const display = await context.launch({
852
+ config: inline(),
853
+ content: attack(
854
+ `${childSetup(udp.stun)}
855
+ const made = created("iframe");
856
+ if (made) {
857
+ made.srcdoc = child;
858
+ document.body.append(made);
859
+ }
860
+ const relative = created("iframe");
861
+ if (relative) {
862
+ relative.src = "page.html";
863
+ document.body.append(relative);
864
+ }
865
+ await wait(1200);
866
+ r.frames = document.querySelectorAll("iframe").length;`,
867
+ `<iframe srcdoc="${child}"></iframe><iframe src="page.html"></iframe>`,
868
+ ),
869
+ });
870
+ await expectNoChild(context, display, udp);
871
+ },
872
+ },
873
+
754
874
  // ── 5: self-navigation ─────────────────────────────────────────────────────────────────────
755
875
  navigation("location", "location.href", (target) => `location.href = ${js(target)};`),
756
876
  navigation("replace", "location.replace", (target) => `location.replace(${js(target)});`),
@@ -917,11 +1037,11 @@ export const PROBES: readonly Probe[] = [
917
1037
  const img = document.createElement("img");
918
1038
  img.src = "relative.png?d=secret";
919
1039
  document.body.append(img);
920
- const object = document.createElement("object");
921
- object.data = ${js(`${c}/object.html`)};
922
- const embed = document.createElement("embed");
923
- embed.src = ${js(`${c}/embed.html`)};
924
- document.body.append(object, embed);
1040
+ const object = created("object");
1041
+ if (object) object.data = ${js(`${c}/object.html`)};
1042
+ const embed = created("embed");
1043
+ if (embed) embed.src = ${js(`${c}/embed.html`)};
1044
+ document.body.append(...[object, embed].filter((each) => each !== null));
925
1045
  await wait(500);
926
1046
  r.plugins = document.querySelectorAll("object, embed").length;`,
927
1047
  `<object data="${c}/static-object.html"></object><embed src="${c}/static-embed.swf">`,
@@ -935,6 +1055,7 @@ export const PROBES: readonly Probe[] = [
935
1055
  });
936
1056
  expect(canary.requests(), "probe: requests reached the canary").toEqual([]);
937
1057
  expect(context.requestsTo(canary.origin), "probe: the page requested the canary").toEqual([]);
1058
+ noteRefused(context, verdict);
938
1059
  },
939
1060
  },
940
1061
 
@@ -1479,12 +1479,32 @@ navigator.mediaDevices && navigator.mediaDevices.getUserMedia({ video: true }).t
1479
1479
  link.rel = "stylesheet";
1480
1480
  link.href = each.style;
1481
1481
  document.head.append(link);
1482
- const nested = document.createElement("iframe");
1483
- nested.src = each.frame;
1484
- document.body.append(nested);
1482
+ // Refused at creation under the default config (P130): the frame can't exist.
1483
+ let nested: HTMLIFrameElement | null = null;
1484
+ try {
1485
+ nested = document.createElement("iframe");
1486
+ } catch (error) {
1487
+ if ((error as { name?: unknown } | null)?.name !== "NotSupportedError") {
1488
+ throw error;
1489
+ }
1490
+ }
1491
+ if (nested !== null) {
1492
+ nested.src = each.frame;
1493
+ document.body.append(nested);
1494
+ }
1485
1495
  await new Promise((resolve) => setTimeout(resolve, 800));
1486
- return { fetched, policy: policies.find((policy) => /connect-src/u.test(policy)) ?? "" };
1496
+ return {
1497
+ fetched,
1498
+ policy: policies.find((policy) => /connect-src/u.test(policy)) ?? "",
1499
+ frameRefused: nested === null,
1500
+ };
1487
1501
  }, urls);
1502
+ if (seen.frameRefused) {
1503
+ info?.annotations.push({
1504
+ type: "measured",
1505
+ description: "the nested frame was refused at creation",
1506
+ });
1507
+ }
1488
1508
  await page.waitForTimeout(SETTLE_MS);
1489
1509
  expect(seen.fetched, "probe: the fetch got out").toBe("blocked");
1490
1510
  expect(seen.policy, "probe: a CSP applied to the document").not.toBe("");
@@ -0,0 +1,86 @@
1
+ import type { AnnotationRect } from "../annotate/types.ts";
2
+
3
+ /**
4
+ * Find in page (P131): the host draws its own find bar (a query box, previous and next, "3/12")
5
+ * and the shell finds the query in the content's text and highlights it, the current match apart,
6
+ * in a layer of its own. The host drives it with Porthole's own messages (`porthole/find.*`); the
7
+ * shell answers how many matches there are and which is current.
8
+ *
9
+ * Everything the frame says is the content's word: the shell shares its realm with the content,
10
+ * which can read the query, change the count or hide the highlights. Use what it says for the
11
+ * find bar (a count, where the current match is), never as a fact about the content.
12
+ */
13
+
14
+ /** Which match becomes the current one: the next, the previous, or the same (a new query: the first in view). */
15
+ export type FindDirection = "next" | "prev" | "none";
16
+
17
+ export interface FindOptions {
18
+ /** Default `"none"`: a new query's first match at or after where the person is reading. */
19
+ readonly direction?: FindDirection;
20
+ /** Default false: case-insensitive, as a browser's own find is. */
21
+ readonly caseSensitive?: boolean;
22
+ }
23
+
24
+ /**
25
+ * Where the matches stand. The content's word: a count for the find bar, nothing more.
26
+ */
27
+ export interface FindResult {
28
+ /** How many matches, at most `FIND_LIMITS.matches`. */
29
+ readonly total: number;
30
+ /** The current match, from 1; 0 when there is none. */
31
+ readonly active: number;
32
+ /** There may be more than `total`: the shell stopped at `FIND_LIMITS.matches` ("1000+"). */
33
+ readonly capped?: true;
34
+ /**
35
+ * The current match's box in the frame's viewport, once it was scrolled into view, clamped to
36
+ * the frame's viewport as an annotation's box is (P104): for a host whose frame doesn't scroll
37
+ * itself (a display that grows with its content) to scroll its own page to it. A hint only.
38
+ */
39
+ readonly rect?: AnnotationRect;
40
+ }
41
+
42
+ /** What the frame says unasked, once the host has checked it. */
43
+ export type FindReport =
44
+ /**
45
+ * The person pressed Cmd+F (Apple) or Ctrl+F (elsewhere) with the keyboard in the frame, and the
46
+ * page didn't take the key itself. Sent only while the host takes the shortcut
47
+ * (`find.takeShortcut(true)`), which also stops the browser's own find. The page's word too: it
48
+ * can send it, or keep the key from the shell. Open the host's find bar, nothing more.
49
+ */
50
+ | { readonly type: "requested" }
51
+ /**
52
+ * The matches changed while a query is shown, without the host asking: the content changed
53
+ * (more of it, or the page's own changes). At most once a second.
54
+ */
55
+ | ({ readonly type: "updated" } & FindResult);
56
+
57
+ /** Porthole's own messages for find in page (own-prefixed, P002). */
58
+ export const FIND_METHODS = {
59
+ /**
60
+ * Host → frame, a request: `{ query, direction?, caseSensitive? }`, answered with a
61
+ * `FindResult`. An empty query (or only spaces) clears, and answers no matches. One that a later
62
+ * query or a clear superseded before the shell ran it is answered with an error (code -32800,
63
+ * "superseded by a later query"; the host's `"unsupported"`): only the latest is searched.
64
+ */
65
+ query: "porthole/find.query",
66
+ /** Host → frame: remove the highlights and forget the query. */
67
+ clear: "porthole/find.clear",
68
+ /**
69
+ * Host → frame: `{ handled: boolean }`, whether the host draws its own find bar: while it does,
70
+ * the shell stops the browser's own find on Cmd+F or Ctrl+F in the frame and says `requested`.
71
+ */
72
+ handled: "porthole/find.handled",
73
+ /** Frame → host. */
74
+ requested: "porthole/find.requested",
75
+ updated: "porthole/find.updated",
76
+ } as const;
77
+
78
+ /** The most of each part of a query or an answer. */
79
+ export const FIND_LIMITS = {
80
+ /** The longest query, in UTF-16 code units. */
81
+ query: 256,
82
+ /** The most matches the shell finds and highlights; past it the answer says `capped`. */
83
+ matches: 1_000,
84
+ /** How long the host waits for an answer before it calls the display's find unsupported, ms. */
85
+ timeoutMs: 3_000,
86
+ } as const;
@@ -0,0 +1,101 @@
1
+ import { parseRect } from "../annotate/validate.ts";
2
+ import {
3
+ FIND_LIMITS as LIMITS,
4
+ type FindDirection,
5
+ type FindOptions,
6
+ type FindReport,
7
+ type FindResult,
8
+ } from "./types.ts";
9
+
10
+ /**
11
+ * The host's checks on find in page (P131): what it sends (a query and its options) and what a
12
+ * frame says back. A frame's word is rebuilt from known fields only, within `FIND_LIMITS`, and is
13
+ * null for anything else: dropped whole, never repaired.
14
+ */
15
+
16
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
17
+ value !== null && typeof value === "object" && !Array.isArray(value);
18
+
19
+ const whole = (value: unknown, max: number): value is number =>
20
+ typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
21
+
22
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
23
+ export function parseFindResult(value: unknown): FindResult | null {
24
+ if (!isRecord(value)) {
25
+ return null;
26
+ }
27
+ const { total, active, capped, rect } = value;
28
+ if (!whole(total, LIMITS.matches) || !whole(active, total)) {
29
+ return null;
30
+ }
31
+ if ((total === 0) !== (active === 0)) {
32
+ return null;
33
+ }
34
+ if (capped !== undefined && capped !== true && capped !== false) {
35
+ return null;
36
+ }
37
+ // Capped only at the limit: fewer matches were all of them.
38
+ if (capped === true && total !== LIMITS.matches) {
39
+ return null;
40
+ }
41
+ const box = rect === undefined || active === 0 ? undefined : parseRect(rect);
42
+ if (box === null) {
43
+ return null;
44
+ }
45
+ return {
46
+ total,
47
+ active,
48
+ ...(capped === true ? { capped: true as const } : {}),
49
+ ...(box === undefined ? {} : { rect: box }),
50
+ };
51
+ }
52
+
53
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
54
+ export function parseFindReport(value: unknown): FindReport | null {
55
+ if (!isRecord(value)) {
56
+ return null;
57
+ }
58
+ switch (value.type) {
59
+ case "requested":
60
+ return { type: "requested" };
61
+ case "updated": {
62
+ // No box: where the current match is goes only with an answer to the host's own query.
63
+ const { rect: _rect, ...numbers } = value;
64
+ const result = parseFindResult(numbers);
65
+ return result === null ? null : { type: "updated", ...result };
66
+ }
67
+ default:
68
+ return null;
69
+ }
70
+ }
71
+
72
+ const DIRECTIONS: readonly FindDirection[] = ["next", "prev", "none"];
73
+
74
+ /**
75
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
76
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
77
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
78
+ */
79
+ export function checkFindQuery(
80
+ query: unknown,
81
+ options: FindOptions | undefined,
82
+ ): { query: string; direction: FindDirection; caseSensitive: boolean } {
83
+ if (typeof query !== "string" || query.length > LIMITS.query) {
84
+ throw new TypeError(`find.query: the query is text, at most ${LIMITS.query} characters`);
85
+ }
86
+ if (options !== undefined && !isRecord(options)) {
87
+ throw new TypeError("find.query: options are { direction?, caseSensitive? }");
88
+ }
89
+ const direction: unknown = options?.direction ?? "none";
90
+ if (!(DIRECTIONS as readonly unknown[]).includes(direction)) {
91
+ throw new TypeError('find.query: direction is "next", "prev" or "none"');
92
+ }
93
+ const caseSensitive: unknown = options?.caseSensitive ?? false;
94
+ if (typeof caseSensitive !== "boolean") {
95
+ throw new TypeError("find.query: caseSensitive is true or false");
96
+ }
97
+ return { query, direction: direction as FindDirection, caseSensitive };
98
+ }
99
+
100
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
101
+ export const blankQuery = (query: string): boolean => query.trim() === "";
@@ -444,6 +444,8 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
444
444
  : `- Copying: the request porthole/copy-text with { text } (at most ${MAX_COPY_CHARS.toLocaleString("en-US")} characters) copies text to the person's clipboard, and the app shows them what was copied; nothing else in the ${c.noun} can write the clipboard. ${gateWords(gates, "the text")}`,
445
445
  annotate: (c) =>
446
446
  `- Comments: the person may point at parts of the ${c.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${c.noun} is written again.`,
447
+ find: (c) =>
448
+ `- Find: the person may search the ${c.noun}'s words with the app's own find bar (Cmd+F or Ctrl+F), which highlights them where they are. Keep the words they would look for as text (not in images or a canvas). A ${c.noun} that handles Cmd+F or Ctrl+F itself (preventDefault) keeps the key.`,
447
449
  reportError: (c) =>
448
450
  `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
449
451
  resize: () => "",
@@ -456,7 +458,7 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
456
458
  };
457
459
 
458
460
  /** The shell's own capabilities, which content never calls by name: taught as they are. */
459
- const SHELL_OWN: readonly CapabilityName[] = ["annotate", "reportError", "resize"];
461
+ const SHELL_OWN: readonly CapabilityName[] = ["annotate", "find", "reportError", "resize"];
460
462
 
461
463
  function interactive(c: Context): string {
462
464
  const { config, noun } = c;
@@ -190,9 +190,17 @@ export function manualLimits(config: PortholeConfig, network: string): ManualLim
190
190
  ? `The ${it}'s address is about:srcdoc: it has no query string or hash to read.`
191
191
  : `The ${it}'s address is its own (with Porthole's one-time ticket), never the app's: read no parameters from it.`,
192
192
  );
193
+ // A page's own frames (P128): what loads, as the shell keeps it; the rest is removed. By default
194
+ // the shell also refuses to make one (P130).
195
+ const frames =
196
+ config.nestedFrames !== "own"
197
+ ? "nested frames (iframe, object, embed) are removed, and making one in script throws"
198
+ : config.mode === "artifact" && config.isolation === "domain"
199
+ ? `an <iframe> of one of the ${it}'s own files (a relative src) or with srcdoc loads, set before it is added; other iframes, object, embed and frame are removed`
200
+ : "an <iframe> with srcdoc loads, set before it is added; other iframes, object, embed and frame are removed";
193
201
  add(
194
202
  "shell",
195
- `document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : config.runtime !== undefined && declared.has("copyText") ? " (copy buttons call clipboard.copy)" : ""}.`,
203
+ `document.write and document.open throw; ${frames}; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : config.runtime !== undefined && declared.has("copyText") ? " (copy buttons call clipboard.copy)" : ""}.`,
196
204
  );
197
205
  add(
198
206
  "storage",