@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
@@ -46,3 +46,8 @@ export declare const js: (value: unknown) => string;
46
46
  */
47
47
  export declare function attack(code: string, markup?: string): string;
48
48
  export declare const inline: (options?: PresetOptions) => import("../index.ts").PortholeConfig;
49
+ /**
50
+ * Records, as a measured fact, the frame-like elements a probe's verdict says the shell refused
51
+ * at creation (`created` in `attack`; P130): the guard held, and nothing was there to remove.
52
+ */
53
+ export declare function noteRefused(context: ProbeContext, verdict: Record<string, unknown>): void;
@@ -22,6 +22,17 @@ export function attack(code, markup = "") {
22
22
  document.removeEventListener("securitypolicyviolation", seen);
23
23
  return blocked;
24
24
  };
25
+ // An element of \`tag\`, or null where the shell refuses to make one (P130: a frame-like element,
26
+ // under the default config): the guard held, and \`r.refused\` lists what was refused at creation.
27
+ const created = (tag) => {
28
+ try {
29
+ return document.createElement(tag);
30
+ } catch (error) {
31
+ if (!error || error.name !== "NotSupportedError") throw error;
32
+ r.refused = (r.refused || []).concat(tag);
33
+ return null;
34
+ }
35
+ };
25
36
  try {
26
37
  ${code}
27
38
  } catch (error) {
@@ -33,3 +44,13 @@ ${code}
33
44
  </script>`;
34
45
  }
35
46
  export const inline = (options = {}) => presets.inlineWidget(options);
47
+ /**
48
+ * Records, as a measured fact, the frame-like elements a probe's verdict says the shell refused
49
+ * at creation (`created` in `attack`; P130): the guard held, and nothing was there to remove.
50
+ */
51
+ export function noteRefused(context, verdict) {
52
+ const refused = verdict.refused;
53
+ if (Array.isArray(refused) && refused.length > 0) {
54
+ context.measured(`${context.engine}: ${refused.join(", ")} refused at creation`);
55
+ }
56
+ }
@@ -1,7 +1,7 @@
1
1
  import { expect } from "@playwright/test";
2
2
  import { presets } from "../presets/presets.js";
3
3
  import { resolveTheme } from "../theme/variables.js";
4
- import { attack, inline, js } from "./kit.js";
4
+ import { attack, inline, js, noteRefused } from "./kit.js";
5
5
  import { settle } from "./oracles.js";
6
6
  /**
7
7
  * The manual's claims about the sandbox, each proven in a real browser (item 14, P064). Every
@@ -566,8 +566,10 @@ export const LIMIT_PROBES = [
566
566
  document.getElementById("go").addEventListener("click", async () => {
567
567
  try { document.write("<p>x</p>"); r.write = "wrote"; } catch (e) { r.write = "throws"; }
568
568
  try { document.open(); r.open = "opened"; } catch (e) { r.open = "throws"; }
569
- const frame = document.createElement("iframe");
570
- document.body.append(frame);
569
+ // Refused at creation under the default config (P130): the frame can't exist.
570
+ let frame = null;
571
+ try { frame = document.createElement("iframe"); } catch (e) { if (!e || e.name !== "NotSupportedError") throw e; r.refused = ["iframe"]; }
572
+ if (frame) document.body.append(frame);
571
573
  await new Promise((resolve) => setTimeout(resolve, 100));
572
574
  r.frames = document.querySelectorAll("iframe, object, embed").length;
573
575
  r.fullscreen = await document.documentElement.requestFullscreen().then(() => "entered", (e) => "rejected");
@@ -577,13 +579,15 @@ export const LIMIT_PROBES = [
577
579
  </script>`,
578
580
  });
579
581
  await click(display, "#go");
580
- expect(await replacedOrRecorded(display, "#go"), "probe: write and open throw, nested frames are removed, full screen is closed").toMatchObject({
582
+ const shell = await replacedOrRecorded(display, "#go");
583
+ expect(shell, "probe: write and open throw, nested frames are removed, full screen is closed").toMatchObject({
581
584
  write: "throws",
582
585
  open: "throws",
583
586
  frames: 0,
584
587
  fullscreen: "rejected",
585
588
  });
586
589
  expect(["rejected", "absent"], "probe: the clipboard was written").toContain((await recorded(display)).clipboard);
590
+ noteRefused(context, shell);
587
591
  },
588
592
  },
589
593
  {
@@ -627,6 +631,7 @@ export const LIMIT_CHECKS = {
627
631
  workers: ["14.workers", "3.webrtc"],
628
632
  sound: ["14.sound"],
629
633
  address: ["14.address", "served.domain.address"],
630
- shell: ["14.shell", "4.document-write", "4.light-dom"],
634
+ // A page's own frames, where the config opts in (P128): what loads, and what still doesn't.
635
+ shell: ["14.shell", "4.document-write", "4.light-dom", "4.own-external"],
631
636
  storage: ["14.storage", "served.domain.storage-scope"],
632
637
  };
@@ -1,7 +1,7 @@
1
1
  import { expect, } from "@playwright/test";
2
2
  import { presets } from "../presets/presets.js";
3
3
  import { resolveTheme } from "../theme/variables.js";
4
- import { attack, inline, js } from "./kit.js";
4
+ import { attack, inline, js, noteRefused } from "./kit.js";
5
5
  import { BEHAVIOR_PROBES } from "./behavior.js";
6
6
  import { CLIPBOARD_PROBES } from "./clipboard.js";
7
7
  import { LIMIT_PROBES } from "./limits.js";
@@ -49,6 +49,7 @@ async function expectNoChild(context, display, udp) {
49
49
  expect(verdict.childRan ?? false, "probe: a nested frame's script ran").toBe(false);
50
50
  expect(verdict.frames ?? 0, "probe: a nested frame is still in the tree").toBe(0);
51
51
  expect(udp.packets(), "probe: STUN packets reached the oracle").toBe(0);
52
+ noteRefused(context, verdict);
52
53
  if (verdict.reached !== undefined || verdict.blocked !== undefined) {
53
54
  context.measured(`${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)})`}`);
54
55
  }
@@ -59,7 +60,7 @@ const childSetup = (stun) => `
59
60
  r.childRan = false;
60
61
  window.addEventListener("message", (event) => { if (event.data && event.data.tag === "child-ran") r.childRan = true; });
61
62
  const child = ${js(childDocument(stun))};
62
- const makeFrame = () => { const f = document.createElement("iframe"); f.setAttribute("srcdoc", child); return f; };`;
63
+ const makeFrame = () => { const f = created("iframe"); if (f) f.setAttribute("srcdoc", child); return f; };`;
63
64
  /**
64
65
  * A navigated document's beacon to an allowed witness, heard only if that document ran: its first
65
66
  * act, a real beacon, which the browser delivers even when the frame is removed a moment later (the
@@ -485,27 +486,31 @@ export const PROBES = [
485
486
  },
486
487
  // ── 4: nested frames ───────────────────────────────────────────────────────────────────────
487
488
  nested("light-dom", "a srcdoc frame appended to the document", () => `
488
- document.body.append(makeFrame());
489
+ const f = makeFrame();
490
+ if (f) document.body.append(f);
489
491
  await wait(50);
490
492
  r.frames = document.querySelectorAll("iframe").length;`),
491
493
  nested("sync-realm", "reaching a new frame's realm in the same task it was added", (stun) => `
492
- const f = document.createElement("iframe");
493
- document.body.append(f);
494
- try {
495
- const w = window[window.length - 1] || f.contentWindow;
496
- r.reached = typeof (w && w.RTCPeerConnection);
497
- const p = new w.RTCPeerConnection({ iceServers: [{ urls: ${js(stun)} }], iceCandidatePoolSize: 4 });
498
- p.createDataChannel("x");
499
- p.createOffer().then((o) => p.setLocalDescription(o));
500
- r.childRan = true;
501
- } catch (e) { r.blocked = String(e && e.name); }
494
+ const f = created("iframe");
495
+ if (f) {
496
+ document.body.append(f);
497
+ try {
498
+ const w = window[window.length - 1] || f.contentWindow;
499
+ r.reached = typeof (w && w.RTCPeerConnection);
500
+ const p = new w.RTCPeerConnection({ iceServers: [{ urls: ${js(stun)} }], iceCandidatePoolSize: 4 });
501
+ p.createDataChannel("x");
502
+ p.createOffer().then((o) => p.setLocalDescription(o));
503
+ r.childRan = true;
504
+ } catch (e) { r.blocked = String(e && e.name); }
505
+ }
502
506
  await wait(50);
503
507
  r.frames = document.querySelectorAll("iframe").length;`),
504
508
  nested("open-shadow", "a frame inside an open shadow root", () => `
505
509
  const host = document.createElement("div");
506
510
  document.body.append(host);
507
511
  const root = host.attachShadow({ mode: "open" });
508
- root.append(makeFrame());
512
+ const f = makeFrame();
513
+ if (f) root.append(f);
509
514
  await wait(50);
510
515
  r.frames = root.querySelectorAll("iframe").length;`),
511
516
  nested("closed-shadow", "a frame inside a closed shadow root", () => `
@@ -513,7 +518,8 @@ export const PROBES = [
513
518
  document.body.append(host);
514
519
  const root = host.attachShadow({ mode: "closed" });
515
520
  root.innerHTML = '<p>shadow</p>';
516
- root.append(makeFrame());
521
+ const f = makeFrame();
522
+ if (f) root.append(f);
517
523
  await wait(50);
518
524
  r.frames = root.querySelectorAll("iframe").length;`),
519
525
  nested("shadow-nested", "a frame two shadow roots deep", () => `
@@ -523,7 +529,8 @@ export const PROBES = [
523
529
  const inner = document.createElement("div");
524
530
  first.append(inner);
525
531
  const second = inner.attachShadow({ mode: "open" });
526
- second.append(makeFrame());
532
+ const f = makeFrame();
533
+ if (f) second.append(f);
527
534
  await wait(50);
528
535
  r.frames = second.querySelectorAll("iframe").length;`),
529
536
  nested("declarative-shadow", "a frame in a declarative closed shadow root (setHTMLUnsafe)", () => `
@@ -557,13 +564,17 @@ export const PROBES = [
557
564
  await wait(50);
558
565
  r.frames = document.querySelectorAll("iframe").length;`),
559
566
  nested("plugins", "object and embed elements holding a document", () => `
560
- const object = document.createElement("object");
561
- object.type = "text/html";
562
- object.data = "data:text/html," + encodeURIComponent(child);
563
- const embed = document.createElement("embed");
564
- embed.type = "text/html";
565
- embed.src = "data:text/html," + encodeURIComponent(child);
566
- document.body.append(object, embed);
567
+ const object = created("object");
568
+ if (object) {
569
+ object.type = "text/html";
570
+ object.data = "data:text/html," + encodeURIComponent(child);
571
+ }
572
+ const embed = created("embed");
573
+ if (embed) {
574
+ embed.type = "text/html";
575
+ embed.src = "data:text/html," + encodeURIComponent(child);
576
+ }
577
+ document.body.append(...[object, embed].filter((each) => each !== null));
567
578
  await wait(50);
568
579
  r.frames = document.querySelectorAll("object, embed").length;`),
569
580
  nested("foreign-object", "a frame inside SVG foreignObject", () => `
@@ -592,6 +603,105 @@ export const PROBES = [
592
603
  await expectNoChild(context, display, udp);
593
604
  },
594
605
  },
606
+ // ── 4, opted in: a page's own frames (P128) ────────────────────────────────────────────────
607
+ // A host that sets `nestedFrames: "own"` lets srcdoc frames (and, served, frames of the page's
608
+ // own files: leak/served/files.spec.ts) load and run; every other frame stays out. These run
609
+ // under an opaque inline widget, where they check what stays out. A srcdoc frame's scripts don't
610
+ // run there (measured, all three engines: the child inherits the frame's nonce policy), so that
611
+ // a kept frame runs is the served case's to show.
612
+ {
613
+ id: "4.own-external",
614
+ item: 4,
615
+ title: "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",
616
+ async run(context) {
617
+ const canary = await context.http();
618
+ const c = canary.origin;
619
+ const display = await context.launch({
620
+ config: inline({ nestedFrames: "own" }),
621
+ content: attack(`
622
+ const away = document.createElement("iframe");
623
+ away.src = ${js(`${c}/made.html?d=secret`)};
624
+ document.body.append(away);
625
+ const blank = document.createElement("iframe");
626
+ document.body.append(blank);
627
+ const holder = document.createElement("div");
628
+ 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>`)};
629
+ document.body.append(holder);
630
+ await wait(1200);
631
+ r.blankKept = blank.isConnected;
632
+ r.frames = document.querySelectorAll("iframe, object, embed").length;`, `<iframe src="${c}/markup.html?d=secret"></iframe>`),
633
+ });
634
+ const verdict = await context.result(display, 15_000);
635
+ await settle(1_000);
636
+ expect(verdict.error, "the content's own code failed").toBeUndefined();
637
+ expect(verdict.frames, "probe: a frame that isn't the content's own is in the tree").toBe(0);
638
+ expect(verdict.blankKept, "probe: a frame with no document of its own was kept").toBe(false);
639
+ expect(canary.requests(), "probe: a frame reached the canary").toEqual([]);
640
+ expect(context.requestsTo(c), "probe: the page requested the canary").toEqual([]);
641
+ },
642
+ },
643
+ {
644
+ id: "4.own-turned",
645
+ item: 4,
646
+ title: "a page's own frames, opted in (P128): a kept frame turned to another site leaves before it goes",
647
+ async run(context) {
648
+ const canary = await context.http();
649
+ const c = canary.origin;
650
+ const display = await context.launch({
651
+ config: inline({ nestedFrames: "own" }),
652
+ content: attack(`
653
+ const make = () => { const f = document.createElement("iframe"); f.srcdoc = "<p>kept</p>"; document.body.append(f); return f; };
654
+ const dropped = make();
655
+ const attribute = make();
656
+ const named = make();
657
+ r.kept = document.querySelectorAll("iframe").length;
658
+ // Its srcdoc wins while it has one: a src alone changes nothing.
659
+ dropped.src = ${js(`${c}/dropped.html?d=secret`)};
660
+ r.keptWithSrc = dropped.isConnected;
661
+ dropped.removeAttribute("srcdoc");
662
+ attribute.setAttribute("src", ${js(`${c}/attribute.html?d=secret`)});
663
+ attribute.attributes.removeNamedItem("srcdoc");
664
+ named.toggleAttribute("srcdoc");
665
+ named.setAttribute("src", ${js(`${c}/named.html?d=secret`)});
666
+ await wait(1200);
667
+ r.frames = document.querySelectorAll("iframe").length;`),
668
+ });
669
+ const verdict = await context.result(display, 15_000);
670
+ await settle(1_000);
671
+ expect(verdict.error, "the content's own code failed").toBeUndefined();
672
+ expect(verdict.kept, "the content's own srcdoc frames were kept").toBe(3);
673
+ expect(verdict.keptWithSrc, "a srcdoc frame given a src was kept").toBe(true);
674
+ expect(verdict.frames, "probe: a frame turned to another site is in the tree").toBe(0);
675
+ expect(canary.requests(), "probe: a turned frame reached the canary").toEqual([]);
676
+ expect(context.requestsTo(c), "probe: the page requested the canary").toEqual([]);
677
+ },
678
+ },
679
+ {
680
+ id: "4.own-default",
681
+ item: 4,
682
+ title: 'no nested frame runs by default (P128): what nestedFrames "own" would keep is removed without it',
683
+ async run(context) {
684
+ const udp = await context.udp();
685
+ const child = childDocument(udp.stun).replace(/"/gu, "&quot;");
686
+ const display = await context.launch({
687
+ config: inline(),
688
+ content: attack(`${childSetup(udp.stun)}
689
+ const made = created("iframe");
690
+ if (made) {
691
+ made.srcdoc = child;
692
+ document.body.append(made);
693
+ }
694
+ const relative = created("iframe");
695
+ if (relative) {
696
+ relative.src = "page.html";
697
+ document.body.append(relative);
698
+ }
699
+ await wait(1200);
700
+ r.frames = document.querySelectorAll("iframe").length;`, `<iframe srcdoc="${child}"></iframe><iframe src="page.html"></iframe>`),
701
+ });
702
+ await expectNoChild(context, display, udp);
703
+ },
704
+ },
595
705
  // ── 5: self-navigation ─────────────────────────────────────────────────────────────────────
596
706
  navigation("location", "location.href", (target) => `location.href = ${js(target)};`),
597
707
  navigation("replace", "location.replace", (target) => `location.replace(${js(target)});`),
@@ -704,11 +814,11 @@ export const PROBES = [
704
814
  const img = document.createElement("img");
705
815
  img.src = "relative.png?d=secret";
706
816
  document.body.append(img);
707
- const object = document.createElement("object");
708
- object.data = ${js(`${c}/object.html`)};
709
- const embed = document.createElement("embed");
710
- embed.src = ${js(`${c}/embed.html`)};
711
- document.body.append(object, embed);
817
+ const object = created("object");
818
+ if (object) object.data = ${js(`${c}/object.html`)};
819
+ const embed = created("embed");
820
+ if (embed) embed.src = ${js(`${c}/embed.html`)};
821
+ document.body.append(...[object, embed].filter((each) => each !== null));
712
822
  await wait(500);
713
823
  r.plugins = document.querySelectorAll("object, embed").length;`, `<object data="${c}/static-object.html"></object><embed src="${c}/static-embed.swf">`),
714
824
  });
@@ -720,6 +830,7 @@ export const PROBES = [
720
830
  });
721
831
  expect(canary.requests(), "probe: requests reached the canary").toEqual([]);
722
832
  expect(context.requestsTo(canary.origin), "probe: the page requested the canary").toEqual([]);
833
+ noteRefused(context, verdict);
723
834
  },
724
835
  },
725
836
  // ── 8: resource hints ──────────────────────────────────────────────────────────────────────
@@ -1132,12 +1132,33 @@ navigator.mediaDevices && navigator.mediaDevices.getUserMedia({ video: true }).t
1132
1132
  link.rel = "stylesheet";
1133
1133
  link.href = each.style;
1134
1134
  document.head.append(link);
1135
- const nested = document.createElement("iframe");
1136
- nested.src = each.frame;
1137
- document.body.append(nested);
1135
+ // Refused at creation under the default config (P130): the frame can't exist.
1136
+ let nested = null;
1137
+ try {
1138
+ nested = document.createElement("iframe");
1139
+ }
1140
+ catch (error) {
1141
+ if (error?.name !== "NotSupportedError") {
1142
+ throw error;
1143
+ }
1144
+ }
1145
+ if (nested !== null) {
1146
+ nested.src = each.frame;
1147
+ document.body.append(nested);
1148
+ }
1138
1149
  await new Promise((resolve) => setTimeout(resolve, 800));
1139
- return { fetched, policy: policies.find((policy) => /connect-src/u.test(policy)) ?? "" };
1150
+ return {
1151
+ fetched,
1152
+ policy: policies.find((policy) => /connect-src/u.test(policy)) ?? "",
1153
+ frameRefused: nested === null,
1154
+ };
1140
1155
  }, urls);
1156
+ if (seen.frameRefused) {
1157
+ info?.annotations.push({
1158
+ type: "measured",
1159
+ description: "the nested frame was refused at creation",
1160
+ });
1161
+ }
1141
1162
  await page.waitForTimeout(SETTLE_MS);
1142
1163
  expect(seen.fetched, "probe: the fetch got out").toBe("blocked");
1143
1164
  expect(seen.policy, "probe: a CSP applied to the document").not.toBe("");
@@ -0,0 +1,83 @@
1
+ import type { AnnotationRect } from "../annotate/types.ts";
2
+ /**
3
+ * Find in page (P131): the host draws its own find bar (a query box, previous and next, "3/12")
4
+ * and the shell finds the query in the content's text and highlights it, the current match apart,
5
+ * in a layer of its own. The host drives it with Porthole's own messages (`porthole/find.*`); the
6
+ * shell answers how many matches there are and which is current.
7
+ *
8
+ * Everything the frame says is the content's word: the shell shares its realm with the content,
9
+ * which can read the query, change the count or hide the highlights. Use what it says for the
10
+ * find bar (a count, where the current match is), never as a fact about the content.
11
+ */
12
+ /** Which match becomes the current one: the next, the previous, or the same (a new query: the first in view). */
13
+ export type FindDirection = "next" | "prev" | "none";
14
+ export interface FindOptions {
15
+ /** Default `"none"`: a new query's first match at or after where the person is reading. */
16
+ readonly direction?: FindDirection;
17
+ /** Default false: case-insensitive, as a browser's own find is. */
18
+ readonly caseSensitive?: boolean;
19
+ }
20
+ /**
21
+ * Where the matches stand. The content's word: a count for the find bar, nothing more.
22
+ */
23
+ export interface FindResult {
24
+ /** How many matches, at most `FIND_LIMITS.matches`. */
25
+ readonly total: number;
26
+ /** The current match, from 1; 0 when there is none. */
27
+ readonly active: number;
28
+ /** There may be more than `total`: the shell stopped at `FIND_LIMITS.matches` ("1000+"). */
29
+ readonly capped?: true;
30
+ /**
31
+ * The current match's box in the frame's viewport, once it was scrolled into view, clamped to
32
+ * the frame's viewport as an annotation's box is (P104): for a host whose frame doesn't scroll
33
+ * itself (a display that grows with its content) to scroll its own page to it. A hint only.
34
+ */
35
+ readonly rect?: AnnotationRect;
36
+ }
37
+ /** What the frame says unasked, once the host has checked it. */
38
+ export type FindReport =
39
+ /**
40
+ * The person pressed Cmd+F (Apple) or Ctrl+F (elsewhere) with the keyboard in the frame, and the
41
+ * page didn't take the key itself. Sent only while the host takes the shortcut
42
+ * (`find.takeShortcut(true)`), which also stops the browser's own find. The page's word too: it
43
+ * can send it, or keep the key from the shell. Open the host's find bar, nothing more.
44
+ */
45
+ {
46
+ readonly type: "requested";
47
+ }
48
+ /**
49
+ * The matches changed while a query is shown, without the host asking: the content changed
50
+ * (more of it, or the page's own changes). At most once a second.
51
+ */
52
+ | ({
53
+ readonly type: "updated";
54
+ } & FindResult);
55
+ /** Porthole's own messages for find in page (own-prefixed, P002). */
56
+ export declare const FIND_METHODS: {
57
+ /**
58
+ * Host → frame, a request: `{ query, direction?, caseSensitive? }`, answered with a
59
+ * `FindResult`. An empty query (or only spaces) clears, and answers no matches. One that a later
60
+ * query or a clear superseded before the shell ran it is answered with an error (code -32800,
61
+ * "superseded by a later query"; the host's `"unsupported"`): only the latest is searched.
62
+ */
63
+ readonly query: "porthole/find.query";
64
+ /** Host → frame: remove the highlights and forget the query. */
65
+ readonly clear: "porthole/find.clear";
66
+ /**
67
+ * Host → frame: `{ handled: boolean }`, whether the host draws its own find bar: while it does,
68
+ * the shell stops the browser's own find on Cmd+F or Ctrl+F in the frame and says `requested`.
69
+ */
70
+ readonly handled: "porthole/find.handled";
71
+ /** Frame → host. */
72
+ readonly requested: "porthole/find.requested";
73
+ readonly updated: "porthole/find.updated";
74
+ };
75
+ /** The most of each part of a query or an answer. */
76
+ export declare const FIND_LIMITS: {
77
+ /** The longest query, in UTF-16 code units. */
78
+ readonly query: 256;
79
+ /** The most matches the shell finds and highlights; past it the answer says `capped`. */
80
+ readonly matches: 1000;
81
+ /** How long the host waits for an answer before it calls the display's find unsupported, ms. */
82
+ readonly timeoutMs: 3000;
83
+ };
@@ -0,0 +1,29 @@
1
+ /** Porthole's own messages for find in page (own-prefixed, P002). */
2
+ export const FIND_METHODS = {
3
+ /**
4
+ * Host → frame, a request: `{ query, direction?, caseSensitive? }`, answered with a
5
+ * `FindResult`. An empty query (or only spaces) clears, and answers no matches. One that a later
6
+ * query or a clear superseded before the shell ran it is answered with an error (code -32800,
7
+ * "superseded by a later query"; the host's `"unsupported"`): only the latest is searched.
8
+ */
9
+ query: "porthole/find.query",
10
+ /** Host → frame: remove the highlights and forget the query. */
11
+ clear: "porthole/find.clear",
12
+ /**
13
+ * Host → frame: `{ handled: boolean }`, whether the host draws its own find bar: while it does,
14
+ * the shell stops the browser's own find on Cmd+F or Ctrl+F in the frame and says `requested`.
15
+ */
16
+ handled: "porthole/find.handled",
17
+ /** Frame → host. */
18
+ requested: "porthole/find.requested",
19
+ updated: "porthole/find.updated",
20
+ };
21
+ /** The most of each part of a query or an answer. */
22
+ export const FIND_LIMITS = {
23
+ /** The longest query, in UTF-16 code units. */
24
+ query: 256,
25
+ /** The most matches the shell finds and highlights; past it the answer says `capped`. */
26
+ matches: 1_000,
27
+ /** How long the host waits for an answer before it calls the display's find unsupported, ms. */
28
+ timeoutMs: 3_000,
29
+ };
@@ -0,0 +1,17 @@
1
+ import { type FindDirection, type FindOptions, type FindReport, type FindResult } from "./types.ts";
2
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
3
+ export declare function parseFindResult(value: unknown): FindResult | null;
4
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
5
+ export declare function parseFindReport(value: unknown): FindReport | null;
6
+ /**
7
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
8
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
9
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
10
+ */
11
+ export declare function checkFindQuery(query: unknown, options: FindOptions | undefined): {
12
+ query: string;
13
+ direction: FindDirection;
14
+ caseSensitive: boolean;
15
+ };
16
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
17
+ export declare const blankQuery: (query: string) => boolean;
@@ -0,0 +1,82 @@
1
+ import { parseRect } from "../annotate/validate.js";
2
+ import { FIND_LIMITS as LIMITS, } from "./types.js";
3
+ /**
4
+ * The host's checks on find in page (P131): what it sends (a query and its options) and what a
5
+ * frame says back. A frame's word is rebuilt from known fields only, within `FIND_LIMITS`, and is
6
+ * null for anything else: dropped whole, never repaired.
7
+ */
8
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9
+ const whole = (value, max) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
10
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
11
+ export function parseFindResult(value) {
12
+ if (!isRecord(value)) {
13
+ return null;
14
+ }
15
+ const { total, active, capped, rect } = value;
16
+ if (!whole(total, LIMITS.matches) || !whole(active, total)) {
17
+ return null;
18
+ }
19
+ if ((total === 0) !== (active === 0)) {
20
+ return null;
21
+ }
22
+ if (capped !== undefined && capped !== true && capped !== false) {
23
+ return null;
24
+ }
25
+ // Capped only at the limit: fewer matches were all of them.
26
+ if (capped === true && total !== LIMITS.matches) {
27
+ return null;
28
+ }
29
+ const box = rect === undefined || active === 0 ? undefined : parseRect(rect);
30
+ if (box === null) {
31
+ return null;
32
+ }
33
+ return {
34
+ total,
35
+ active,
36
+ ...(capped === true ? { capped: true } : {}),
37
+ ...(box === undefined ? {} : { rect: box }),
38
+ };
39
+ }
40
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
41
+ export function parseFindReport(value) {
42
+ if (!isRecord(value)) {
43
+ return null;
44
+ }
45
+ switch (value.type) {
46
+ case "requested":
47
+ return { type: "requested" };
48
+ case "updated": {
49
+ // No box: where the current match is goes only with an answer to the host's own query.
50
+ const { rect: _rect, ...numbers } = value;
51
+ const result = parseFindResult(numbers);
52
+ return result === null ? null : { type: "updated", ...result };
53
+ }
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+ const DIRECTIONS = ["next", "prev", "none"];
59
+ /**
60
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
61
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
62
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
63
+ */
64
+ export function checkFindQuery(query, options) {
65
+ if (typeof query !== "string" || query.length > LIMITS.query) {
66
+ throw new TypeError(`find.query: the query is text, at most ${LIMITS.query} characters`);
67
+ }
68
+ if (options !== undefined && !isRecord(options)) {
69
+ throw new TypeError("find.query: options are { direction?, caseSensitive? }");
70
+ }
71
+ const direction = options?.direction ?? "none";
72
+ if (!DIRECTIONS.includes(direction)) {
73
+ throw new TypeError('find.query: direction is "next", "prev" or "none"');
74
+ }
75
+ const caseSensitive = options?.caseSensitive ?? false;
76
+ if (typeof caseSensitive !== "boolean") {
77
+ throw new TypeError("find.query: caseSensitive is true or false");
78
+ }
79
+ return { query, direction: direction, caseSensitive };
80
+ }
81
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
82
+ export const blankQuery = (query) => query.trim() === "";
@@ -256,6 +256,7 @@ const ENTRIES = {
256
256
  ? `- copyText(text): copies text to the person's clipboard (at most ${MAX_COPY_CHARS.toLocaleString("en-US")} characters), and the app shows them what was copied. Use it for every copy button: nothing else in the ${c.noun} can write the clipboard. ${gateWords(gates, "the text")} It returns a promise: true if it was copied.`
257
257
  : `- 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")}`,
258
258
  annotate: (c) => `- 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.`,
259
+ find: (c) => `- 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.`,
259
260
  reportError: (c) => `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
260
261
  resize: () => "",
261
262
  // The runtime's own: taught as porthole.use's methods (runtimeEntries), never alone.
@@ -266,7 +267,7 @@ const ENTRIES = {
266
267
  db: () => "",
267
268
  };
268
269
  /** The shell's own capabilities, which content never calls by name: taught as they are. */
269
- const SHELL_OWN = ["annotate", "reportError", "resize"];
270
+ const SHELL_OWN = ["annotate", "find", "reportError", "resize"];
270
271
  function interactive(c) {
271
272
  const { config, noun } = c;
272
273
  // Under the capability runtime (P085), what content calls is porthole.use's methods.
@@ -131,7 +131,14 @@ export function manualLimits(config, network) {
131
131
  add("address", config.isolation === "opaque"
132
132
  ? `The ${it}'s address is about:srcdoc: it has no query string or hash to read.`
133
133
  : `The ${it}'s address is its own (with Porthole's one-time ticket), never the app's: read no parameters from it.`);
134
- add("shell", `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)" : ""}.`);
134
+ // A page's own frames (P128): what loads, as the shell keeps it; the rest is removed. By default
135
+ // the shell also refuses to make one (P130).
136
+ const frames = config.nestedFrames !== "own"
137
+ ? "nested frames (iframe, object, embed) are removed, and making one in script throws"
138
+ : config.mode === "artifact" && config.isolation === "domain"
139
+ ? `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`
140
+ : "an <iframe> with srcdoc loads, set before it is added; other iframes, object, embed and frame are removed";
141
+ add("shell", `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)" : ""}.`);
135
142
  add("storage", config.isolation === "opaque" || config.nested === true
136
143
  ? `State isn't saved: localStorage works but lasts only while the ${it} is on screen, and a reload or another device starts fresh. Keep what matters in the ${it}'s code.`
137
144
  : config.storage?.scope !== undefined