@botiverse/porthole 0.14.7 → 0.14.8

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 (49) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/check/files.js +2 -0
  3. package/dist/check/lint.js +82 -3
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/compile/policy.d.ts +17 -6
  6. package/dist/compile/policy.js +22 -7
  7. package/dist/config/schema.d.ts +13 -0
  8. package/dist/config/validate.js +15 -0
  9. package/dist/conformance/harness-source.js +1 -1
  10. package/dist/conformance/kit.d.ts +5 -0
  11. package/dist/conformance/kit.js +21 -0
  12. package/dist/conformance/limits.js +10 -5
  13. package/dist/conformance/probes.js +139 -28
  14. package/dist/conformance/served.js +25 -4
  15. package/dist/guide/limits.js +8 -1
  16. package/dist/host/create-host.js +35 -4
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/presets/presets.d.ts +6 -0
  20. package/dist/presets/presets.js +6 -0
  21. package/dist/server/files.js +4 -3
  22. package/dist/server/server.js +4 -1
  23. package/dist/shell/plan.d.ts +5 -0
  24. package/dist/shell/plan.js +2 -0
  25. package/dist/shell/runtime.d.ts +30 -1
  26. package/dist/shell/runtime.js +785 -104
  27. package/docs/ADOPTING.md +20 -0
  28. package/docs/DECISIONS.md +294 -0
  29. package/docs/DESIGN.md +7 -4
  30. package/docs/THREAT_MODEL.md +30 -5
  31. package/docs/insertion-entry-points.md +95 -0
  32. package/package.json +1 -1
  33. package/src/check/files.ts +2 -0
  34. package/src/check/lint.ts +97 -8
  35. package/src/compile/policy.ts +23 -6
  36. package/src/config/schema.ts +13 -0
  37. package/src/config/validate.ts +16 -0
  38. package/src/conformance/kit.ts +22 -0
  39. package/src/conformance/limits.ts +10 -5
  40. package/src/conformance/probes.ts +149 -28
  41. package/src/conformance/served.ts +24 -4
  42. package/src/guide/limits.ts +9 -1
  43. package/src/host/create-host.ts +37 -4
  44. package/src/index.ts +1 -0
  45. package/src/presets/presets.ts +15 -0
  46. package/src/server/files.ts +8 -2
  47. package/src/server/server.ts +4 -1
  48. package/src/shell/plan.ts +7 -0
  49. package/src/shell/runtime.ts +788 -104
@@ -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("");
@@ -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
@@ -420,16 +420,40 @@ export function createHost(config, options = {}) {
420
420
  ...options.hostContext?.(),
421
421
  };
422
422
  };
423
+ // A frame's size is taken at most once an animation frame after its run's first, and only
424
+ // when it changed (P127): `resize` has no gate, and each one would reflow the host's page and
425
+ // tell its listeners.
426
+ let sizeFrame = null;
427
+ let pendingSize = null;
428
+ let shownSize = null;
429
+ const applySize = () => {
430
+ sizeFrame = null;
431
+ const size = pendingSize;
432
+ pendingSize = null;
433
+ if (size === null ||
434
+ (shownSize !== null && size.height === shownSize.height && size.width === shownSize.width)) {
435
+ return;
436
+ }
437
+ shownSize = size;
438
+ height = size.height;
439
+ surface?.setHeight(size.height);
440
+ emit("resize", size);
441
+ };
423
442
  const onBridge = (event) => {
424
443
  switch (event.type) {
425
444
  case "resize": {
426
445
  const next = Math.min(config.limits.maxHeightPx, Math.max(config.limits.minHeightPx, Math.ceil(event.height)));
427
- height = next;
428
- surface?.setHeight(next);
429
- emit("resize", {
446
+ pendingSize = {
430
447
  height: next,
431
448
  ...(event.width === undefined ? {} : { width: event.width }),
432
- });
449
+ };
450
+ // A run's first size at once: until then its frame has no height of its own.
451
+ if (view === null || shownSize === null) {
452
+ applySize();
453
+ }
454
+ else if (sizeFrame === null) {
455
+ sizeFrame = view.requestAnimationFrame(applySize);
456
+ }
433
457
  return;
434
458
  }
435
459
  case "navigationBlocked":
@@ -465,6 +489,13 @@ export function createHost(config, options = {}) {
465
489
  bridge?.close();
466
490
  bridge = null;
467
491
  handshaken = false;
492
+ // The next run's frame tells its own size, the same as this one's or not.
493
+ if (sizeFrame !== null) {
494
+ view?.cancelAnimationFrame(sizeFrame);
495
+ sizeFrame = null;
496
+ }
497
+ pendingSize = null;
498
+ shownSize = null;
468
499
  abort?.abort();
469
500
  abort = null;
470
501
  outcomeWatch?.stop();
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ export { LIBRARY_PATH, VENDORED_LIBRARIES, libraryPath, licensePath, type Vendor
23
23
  export { checkFileSet, DEFAULT_ENTRY, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_FILES, DEFAULT_MAX_VERSION_BYTES, fileLimits, filePathProblem, lookupFile, requestFilePath, servesFiles, type FileLimits, type FileLookup, type FileSetProblem, } from "./files/paths.ts";
24
24
  export { fileTypeOf, KNOWN_EXTENSIONS, UNKNOWN_TYPE, type FileRole, type FileType, } from "./files/types.ts";
25
25
  export { compile, type CompiledConfig } from "./compile/compile.ts";
26
- export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, ASSET_CODE_DIRECTIVES, ASSET_DIRECTIVES, assetCodeRuns, assetCspDirectives, FILE_SET_DIRECTIVES, fileSetCspDirectives, INERT_FILE_CSP, type CspDirective, type EgressKind, } from "./compile/policy.ts";
26
+ export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, ASSET_CODE_DIRECTIVES, ASSET_DIRECTIVES, assetCodeRuns, assetCspDirectives, FILE_SET_DIRECTIVES, fileSetCspDirectives, fileSetDirectives, INERT_FILE_CSP, type CspDirective, type EgressKind, } from "./compile/policy.ts";
27
27
  export { shellPlan, type ShellPlan } from "./shell/plan.ts";
28
28
  export type { ShellDocumentOptions } from "./shell/document.ts";
29
29
  export { generateGuide, generateToolDescription, type BuiltInTopic, type GuideTopic, } from "./guide/guide.ts";
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ export { checkFileSet, DEFAULT_ENTRY, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_FILES,
28
28
  export { fileTypeOf, KNOWN_EXTENSIONS, UNKNOWN_TYPE, } from "./files/types.js";
29
29
  // The compiler.
30
30
  export { compile } from "./compile/compile.js";
31
- export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, ASSET_CODE_DIRECTIVES, ASSET_DIRECTIVES, assetCodeRuns, assetCspDirectives, FILE_SET_DIRECTIVES, fileSetCspDirectives, INERT_FILE_CSP, } from "./compile/policy.js";
31
+ export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, ASSET_CODE_DIRECTIVES, ASSET_DIRECTIVES, assetCodeRuns, assetCspDirectives, FILE_SET_DIRECTIVES, fileSetCspDirectives, fileSetDirectives, INERT_FILE_CSP, } from "./compile/policy.js";
32
32
  export { shellPlan } from "./shell/plan.js";
33
33
  export { generateGuide, generateToolDescription, } from "./guide/guide.js";
34
34
  export { GUIDE_EXAMPLES } from "./guide/examples.js";
@@ -42,6 +42,12 @@ export interface PresetOptions {
42
42
  readonly runtime?: RuntimeVersion;
43
43
  /** Domain isolation, artifact pages: the page in an opaque child of Porthole's shell (P111). */
44
44
  readonly nested?: true;
45
+ /**
46
+ * `own` (P128): an `<iframe>` of one of the page's own files (a relative `src`) or a `srcdoc`
47
+ * one loads and runs, in a realm of its own that the shell's hardening doesn't reach
48
+ * (`PortholeConfig.nestedFrames`). `none` (default): every nested frame is removed.
49
+ */
50
+ readonly nestedFrames?: "none" | "own";
45
51
  }
46
52
  /** What a live widget may say about a capability (P103): anything but origins of its own. */
47
53
  export type LiveCapabilityConfig = Omit<CapabilityConfig, "connect" | "resource">;
@@ -142,6 +142,7 @@ function build(mode, defaults, options) {
142
142
  ...(options.errors === undefined ? {} : { errors: options.errors }),
143
143
  ...(options.runtime === undefined ? {} : { runtime: options.runtime }),
144
144
  ...(options.nested === undefined ? {} : { nested: options.nested }),
145
+ ...(options.nestedFrames === undefined ? {} : { nestedFrames: options.nestedFrames }),
145
146
  });
146
147
  }
147
148
  export const presets = {
@@ -164,6 +165,11 @@ export const presets = {
164
165
  if (options.egress !== undefined) {
165
166
  throw new ConfigError("options.egress", "a live widget has no network of its own: its egress stays closed (P079)");
166
167
  }
168
+ // A child frame is a realm the shell's WebRTC removal never reached (P128): a network of its
169
+ // own, which a live widget never has.
170
+ if (options.nestedFrames === "own") {
171
+ throw new ConfigError("options.nestedFrames", "a live widget has no network of its own: its frames stay removed (P079, P128)");
172
+ }
167
173
  // A capability's own origins join the CSP as egress does (P103): none for a live widget.
168
174
  for (const [name, value] of Object.entries(options.capabilities ?? {})) {
169
175
  for (const field of ["connect", "resource"]) {
@@ -1,4 +1,4 @@
1
- import { assetCspDirectives, fileSetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, serializeCsp, } from "../compile/policy.js";
1
+ import { assetCspDirectives, fileSetCspDirectives, fileSetDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, serializeCsp, } from "../compile/policy.js";
2
2
  import { DEFAULT_ENTRY, lookupFile, requestFilePath } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  import { isCodeAsset } from "../runtime/requests.js";
@@ -187,8 +187,9 @@ export async function serveFile(serving) {
187
187
  serving.compiled.config.capabilities.assets !== undefined
188
188
  ? "same-origin"
189
189
  : "no-referrer";
190
- // Its version's files (P082), and its artifact's assets where the config serves them (P089).
191
- const directives = assetCspDirectives(serving.compiled.config, fileSetCspDirectives(serving.compiled.cspDirectives, serving.source), serving.origin);
190
+ // Its version's files (P082), frames of them where the config opts in (P128), and its
191
+ // artifact's assets where the config serves them (P089).
192
+ const directives = assetCspDirectives(serving.compiled.config, fileSetCspDirectives(serving.compiled.cspDirectives, serving.source, fileSetDirectives(serving.compiled.config)), serving.origin);
192
193
  // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
193
194
  // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
194
195
  // its own.
@@ -1032,6 +1032,9 @@ export function createServer(options) {
1032
1032
  const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
1033
1033
  if ("files" in served) {
1034
1034
  if (at !== undefined) {
1035
+ // A page's own frames (P128): its files below the base are framed by its own pages too,
1036
+ // on this origin (`frame-ancestors` names every ancestor). Never another origin's.
1037
+ const own = served.compiled.config.nestedFrames === "own";
1035
1038
  return serveFile({
1036
1039
  request,
1037
1040
  set: served.files,
@@ -1043,7 +1046,7 @@ export function createServer(options) {
1043
1046
  source: at.source,
1044
1047
  compiled: served.compiled,
1045
1048
  hostOrigins: options.hostOrigins,
1046
- frameAncestors: ancestors,
1049
+ frameAncestors: own ? `${access.origin} ${ancestors}` : ancestors,
1047
1050
  ...versionOf(access.instance),
1048
1051
  });
1049
1052
  }
@@ -51,5 +51,10 @@ export interface ShellPlan {
51
51
  /** The most text `copyText` carries. */
52
52
  readonly maxCopyChars: number;
53
53
  readonly protocolVersion: string;
54
+ /**
55
+ * `own` where the config lets content frame its own files and `srcdoc` (P128): the shell keeps
56
+ * those iframes and removes every other frame-like element. Absent: it removes them all.
57
+ */
58
+ readonly nestedFrames?: "own";
54
59
  }
55
60
  export declare function shellPlan(config: PortholeConfig): ShellPlan | null;
@@ -44,5 +44,7 @@ export function shellPlan(config) {
44
44
  maxPromptChars: config.limits.maxPromptChars,
45
45
  maxCopyChars: MAX_COPY_CHARS,
46
46
  protocolVersion: MCP_APPS_PROTOCOL_VERSION,
47
+ // Only where opted into (P128): every other plan is the same as before it.
48
+ ...(config.nestedFrames === "own" ? { nestedFrames: "own" } : {}),
47
49
  };
48
50
  }
@@ -4,6 +4,31 @@
4
4
  * more comes. Parsed as it is, a cut right after `<` or `</` draws them as text.
5
5
  */
6
6
  export declare const HELD_BACK: string;
7
+ /**
8
+ * Which `<iframe>` the shell keeps under `nestedFrames: "own"` (P128), spliced into the runtime:
9
+ * one with a `srcdoc` attribute (which wins over any `src`), or one whose `src`, resolved by the
10
+ * platform's own URL parser (`resolve`, which normalizes `..`, `%2e` and backslashes), is under the
11
+ * version's own files' address (`filesBase`, ending in `/`). Nothing else: no `src` or a blank one
12
+ * (`about:blank`), another path of the origin, another origin, `data:`, `blob:`, `javascript:`.
13
+ * Only comparisons and indexing, which content can't replace (no String.prototype method).
14
+ */
15
+ export declare const OWN_FRAME: string;
16
+ /**
17
+ * Which values a guard forwards as they are (P129, P130), spliced into the runtime: those that are
18
+ * their own single reading. A string, a number, a boolean, a bigint, `null`, and a genuine
19
+ * `undefined` (`value === undefined`: an object whose `typeof` is "undefined" isn't one). Nothing
20
+ * here can throw or run content's code (`typeof` and `===` read no property).
21
+ */
22
+ export declare const PASSES_AS_IS: string;
23
+ /**
24
+ * A name or value a guard inspects and then forwards, pinned to one reading (P129, P130), spliced
25
+ * into the runtime as `ONCE(passesAsIs, toText)`: a value `passesAsIs` lets through goes on
26
+ * unchanged; anything else is turned into its string once, by `toText` (the platform's own
27
+ * `String`, kept before content runs), and that string is what is both checked and forwarded. A
28
+ * symbol, a conversion that throws, or one that doesn't give a string is refused (the guard throws
29
+ * and nothing is forwarded): fail closed.
30
+ */
31
+ export declare const ONCE: string;
7
32
  /**
8
33
  * The shell's runtime: the code that runs first in the frame, before any content. Plain ES2020,
9
34
  * no imports and no build step, so every engine (a browser frame now, a native web view later)
@@ -17,7 +42,11 @@ export declare const HELD_BACK: string;
17
42
  * 3. removes every frame-like element content adds, wherever it adds it (the document, any shadow
18
43
  * root), since a nested frame runs in a fresh realm where step 2 never happened (and not every
19
44
  * engine enforces `frame-src 'none'` for `srcdoc`/`about:blank` children); and the resource
20
- * hints and refreshes a CSP doesn't govern;
45
+ * hints and refreshes a CSP doesn't govern. Where the config opts in (`nestedFrames: "own"`,
46
+ * P128), an `<iframe>` of the page's own files or with `srcdoc` is kept (`OWN_FRAME`), and
47
+ * one that is kept leaves the document before a change would make it any other; in such a
48
+ * child realm steps 1, 2, 5 and 6 never ran (a page of the set has its own shell there), which
49
+ * the host accepted by opting in;
21
50
  * 4. closes the parser entry points that could build a shadow root step 3 can't see (declarative
22
51
  * shadow DOM through `setHTMLUnsafe`, `parseHTMLUnsafe`, `document.write`);
23
52
  * 5. keeps content off the clipboard: the async Clipboard API refuses, `execCommand` won't copy or