@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
package/src/check/lint.ts CHANGED
@@ -6,8 +6,10 @@ import {
6
6
  librarySources,
7
7
  } from "../compile/policy.ts";
8
8
  import type { PortholeConfig } from "../config/schema.ts";
9
+ import { servesFiles } from "../files/paths.ts";
9
10
  import { sizeWords } from "../guide/limits.ts";
10
11
  import { originMatchesSource } from "../isolation/served.ts";
12
+ import { attributesOf } from "./markup.ts";
11
13
  import { scrollLock } from "./scroll.ts";
12
14
 
13
15
  /**
@@ -124,6 +126,72 @@ const OWN_CDN: readonly {
124
126
  { name: "Plotly", host: /^https:\/\/cdn\.plot\.ly\/plotly/u, pinned: /\d+\.\d+\.\d+/u },
125
127
  ];
126
128
 
129
+ /** The most of a tag's text a frame's attributes are read from: a `srcdoc` may hold markup. */
130
+ const MOST_TAG_CHARS = 65_536;
131
+
132
+ /** The most frame-like tags read for `strayFrame`: past them, the rest isn't looked at. */
133
+ const MOST_FRAMES = 200;
134
+
135
+ /**
136
+ * A tag's attributes' text, from just past its name to its closing `>` outside any quoted value
137
+ * (a `srcdoc` holds `<` and `>`), read at most `MOST_TAG_CHARS` far: linear in what it reads.
138
+ */
139
+ function tagText(content: string, from: number): string {
140
+ const end = Math.min(content.length, from + MOST_TAG_CHARS);
141
+ let quote = "";
142
+ for (let at = from; at < end; at += 1) {
143
+ const char = content[at];
144
+ if (quote !== "") {
145
+ if (char === quote) {
146
+ quote = "";
147
+ }
148
+ } else if (char === '"' || char === "'") {
149
+ quote = char;
150
+ } else if (char === ">") {
151
+ return content.slice(from, at);
152
+ }
153
+ }
154
+ return content.slice(from, end);
155
+ }
156
+
157
+ /**
158
+ * Under `nestedFrames: "own"` (P128), the first frame-like element that never loads, and why: a
159
+ * `<frame>`, `<object>` or `<embed>`; an `<iframe>` of another site (any scheme, `//`), of the
160
+ * origin's root (`/`), or with neither `src` nor `srcdoc`; one with a relative `src` where there
161
+ * are no files to frame (`relative`: false). Null where every frame is the page's own.
162
+ */
163
+ function strayFrame(
164
+ content: string,
165
+ relative: boolean,
166
+ ): { readonly tag: string; readonly src: string; readonly index: number } | null {
167
+ let read = 0;
168
+ for (const match of content.matchAll(/<(iframe|frame|object|embed)\b/giu)) {
169
+ read += 1;
170
+ if (read > MOST_FRAMES) {
171
+ break;
172
+ }
173
+ const tag = (match[1] ?? "").toLowerCase();
174
+ if (tag !== "iframe") {
175
+ return { tag, src: "", index: match.index };
176
+ }
177
+ const attributes = attributesOf(tagText(content, match.index + match[0].length));
178
+ if (attributes.some((each) => each.name === "srcdoc")) {
179
+ continue;
180
+ }
181
+ const src = (attributes.find((each) => each.name === "src")?.value ?? "").trim();
182
+ const elsewhere =
183
+ src === "" ||
184
+ /^[a-z][a-z0-9+.-]*:/iu.test(src) ||
185
+ src.startsWith("/") ||
186
+ src.startsWith("\\") ||
187
+ !relative;
188
+ if (elsewhere) {
189
+ return { tag, src, index: match.index };
190
+ }
191
+ }
192
+ return null;
193
+ }
194
+
127
195
  export function lintContent(config: PortholeConfig, content: string): Finding[] {
128
196
  return lintPage(config, content, { scrollLock: true });
129
197
  }
@@ -179,14 +247,35 @@ export function lintPage(
179
247
  }
180
248
  }
181
249
  }
182
- const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
183
- if (frame !== null) {
184
- add(
185
- "nested-frame",
186
- "error",
187
- `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`,
188
- frame.index,
189
- );
250
+ if (config.nestedFrames === "own") {
251
+ // A page's own frames load (P128): only what never does is said.
252
+ const files = servesFiles(config);
253
+ const own = files
254
+ ? 'an <iframe> of one of its own files (a relative src, src="chart.html") or with srcdoc does'
255
+ : "an <iframe> with srcdoc does";
256
+ const stray = strayFrame(content, files);
257
+ if (stray !== null) {
258
+ add(
259
+ "nested-frame",
260
+ "error",
261
+ stray.tag !== "iframe"
262
+ ? `Remove the <${stray.tag}>: <frame>, <object> and <embed> are taken out of a ${it} and never run; ${own}.`
263
+ : stray.src === ""
264
+ ? `This <iframe> has neither src nor srcdoc, and is taken out of the ${it}: ${own}.`
265
+ : `Remove the <iframe src="${stray.src.slice(0, 200)}">: ${files ? "frames of other sites (or of another path of the address) are" : "frames of an address are"} taken out of a ${it} and never load; ${own}.`,
266
+ stray.index,
267
+ );
268
+ }
269
+ } else {
270
+ const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
271
+ if (frame !== null) {
272
+ add(
273
+ "nested-frame",
274
+ "error",
275
+ `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`,
276
+ frame.index,
277
+ );
278
+ }
190
279
  }
191
280
  const write = /\bdocument\s*\.\s*write(?:ln)?\s*\(/u.exec(content);
192
281
  if (write !== null) {
@@ -139,20 +139,37 @@ export const FILE_SET_DIRECTIVES = [
139
139
  "worker-src",
140
140
  ] as const;
141
141
 
142
+ /**
143
+ * The directives a page of a file set opens to its version's own files under `config` (P082):
144
+ * `FILE_SET_DIRECTIVES`, and `frame-src` too where the config lets content frame its own files
145
+ * (`nestedFrames: "own"`, P128). Never `child-src`: every engine Porthole supports reads frames
146
+ * from `frame-src` (P038), and `child-src` is only its fallback (and workers', which have
147
+ * `worker-src`).
148
+ */
149
+ export function fileSetDirectives(config: PortholeConfig): readonly string[] {
150
+ return config.nestedFrames === "own"
151
+ ? [...FILE_SET_DIRECTIVES, "frame-src"]
152
+ : FILE_SET_DIRECTIVES;
153
+ }
154
+
142
155
  /**
143
156
  * A served page's CSP when it comes with files (P082): the frame's, with its version's own files
144
- * opened for each kind that loads (`FILE_SET_DIRECTIVES`), by `source`, the files' path on the
145
- * content origin (`https://a-x.example-usercontent.com/v/3/`). Never `'self'`: the origin's other
146
- * paths (other versions, Porthole's own) stay closed, and frames, plugins, forms and `<base>` stay
147
- * `'none'`. Opaque frames have no files, and keep P022's rule whole.
157
+ * opened for each kind that loads (`opened`: `FILE_SET_DIRECTIVES` by default, a server's
158
+ * `fileSetDirectives(config)`), by `source`, the files' path on the content origin
159
+ * (`https://a-x.example-usercontent.com/v/3/`).
160
+ * Never `'self'`: the origin's other paths (other versions, Porthole's own) stay closed, and
161
+ * plugins, forms and `<base>` stay `'none'`, frames too unless the config opts into its own
162
+ * (P128: `frame-src` its version's path, never another origin). Opaque frames have no files, and
163
+ * keep P022's rule whole.
148
164
  */
149
165
  export function fileSetCspDirectives(
150
166
  directives: readonly CspDirective[],
151
167
  source: string,
168
+ opened: readonly string[] = FILE_SET_DIRECTIVES,
152
169
  ): CspDirective[] {
153
- const opened = new Set<string>(FILE_SET_DIRECTIVES);
170
+ const open = new Set<string>(opened);
154
171
  return directives.map(([name, ...sources]) => {
155
- if (!opened.has(name)) {
172
+ if (!open.has(name)) {
156
173
  return [name, ...sources];
157
174
  }
158
175
  const kept = sources.filter((each) => each !== "'none'");
@@ -269,6 +269,19 @@ export interface PortholeConfig {
269
269
  * page has no storage of its own (an in-memory stand-in) and fetches nothing with a cookie.
270
270
  */
271
271
  readonly nested?: true;
272
+ /**
273
+ * Which nested frames content may make (P128). `none` (default, and absent): the shell removes
274
+ * every frame-like element content adds, and the CSP's `frame-src` is `'none'`. `own`: an
275
+ * `<iframe>` of one of the page's own files (its `src` under its version's own address, P082)
276
+ * and a `srcdoc` one load and run; frames of other sites, `<frame>`, `<object>` and `<embed>`
277
+ * are still removed, and a served file set's `frame-src` opens its version's own path only.
278
+ * A weakening, opted into: a child frame is a realm of its own, where the shell's WebRTC
279
+ * removal, clipboard guards and navigation cancel never ran (a page of the set framed there has
280
+ * its own shell; a `srcdoc` frame, or the `about:blank` a new frame starts as, has none), so
281
+ * content reaches WebRTC and the clipboard's events there. Not for url mode, a live widget
282
+ * (no network of its own, P079) or a nested page (P111).
283
+ */
284
+ readonly nestedFrames?: "none" | "own";
272
285
  }
273
286
 
274
287
  export interface StorageConfig {
@@ -325,6 +325,7 @@ export function validateConfig(
325
325
  "errors",
326
326
  "runtime",
327
327
  "nested",
328
+ "nestedFrames",
328
329
  ],
329
330
  "config",
330
331
  );
@@ -710,6 +711,21 @@ export function validateConfig(
710
711
  }
711
712
  }
712
713
 
714
+ // A page's own nested frames (P128): opted into, never a default.
715
+ if (config.nestedFrames !== undefined) {
716
+ if (config.nestedFrames !== "none" && config.nestedFrames !== "own") {
717
+ fail("config.nestedFrames", 'must be "none" or "own", or left out');
718
+ }
719
+ if (config.nestedFrames === "own" && config.mode === "url") {
720
+ fail("config.nestedFrames", "url mode has no shell: its app's frames are its own");
721
+ }
722
+ // A nested page's frames have an opaque ancestor, which no frame-ancestors source matches:
723
+ // none of its own files would load in one. Not measured yet.
724
+ if (config.nestedFrames === "own" && config.nested === true) {
725
+ fail("config.nestedFrames", 'a nested page (P111) has no "own" frames yet: leave it out');
726
+ }
727
+ }
728
+
713
729
  if (config.errors !== undefined) {
714
730
  if (config.errors !== "agent" && config.errors !== "host" && config.errors !== "none") {
715
731
  fail("config.errors", 'must be "agent", "host" or "none"');
@@ -66,6 +66,17 @@ export function attack(code: string, markup = ""): string {
66
66
  document.removeEventListener("securitypolicyviolation", seen);
67
67
  return blocked;
68
68
  };
69
+ // An element of \`tag\`, or null where the shell refuses to make one (P130: a frame-like element,
70
+ // under the default config): the guard held, and \`r.refused\` lists what was refused at creation.
71
+ const created = (tag) => {
72
+ try {
73
+ return document.createElement(tag);
74
+ } catch (error) {
75
+ if (!error || error.name !== "NotSupportedError") throw error;
76
+ r.refused = (r.refused || []).concat(tag);
77
+ return null;
78
+ }
79
+ };
69
80
  try {
70
81
  ${code}
71
82
  } catch (error) {
@@ -78,3 +89,14 @@ ${code}
78
89
  }
79
90
 
80
91
  export const inline = (options: PresetOptions = {}) => presets.inlineWidget(options);
92
+
93
+ /**
94
+ * Records, as a measured fact, the frame-like elements a probe's verdict says the shell refused
95
+ * at creation (`created` in `attack`; P130): the guard held, and nothing was there to remove.
96
+ */
97
+ export function noteRefused(context: ProbeContext, verdict: Record<string, unknown>): void {
98
+ const refused = verdict.refused;
99
+ if (Array.isArray(refused) && refused.length > 0) {
100
+ context.measured(`${context.engine}: ${refused.join(", ")} refused at creation`);
101
+ }
102
+ }
@@ -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("");
@@ -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",