@botiverse/porthole 0.6.0 → 0.8.0

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 (208) hide show
  1. package/README.md +25 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -13,6 +13,17 @@
13
13
  */
14
14
  import { expect } from "@playwright/test";
15
15
  import { MCP_APPS_METHODS } from "../protocol/mcp-apps.js";
16
+ import { keepsFramedCookies } from "./cookies.js";
17
+ /** The cases of a served page on a tab of its own (P099), one per wall. */
18
+ export const TAB_CASES = [
19
+ "served.domain.tab-window-open",
20
+ "served.domain.tab-escapes",
21
+ "served.domain.tab-opener",
22
+ "served.domain.tab-navigation",
23
+ "served.domain.tab-links",
24
+ "served.domain.tab-devices",
25
+ "served.domain.tab-prompts",
26
+ ];
16
27
  const SETTLE_MS = 800;
17
28
  /** What a served shell is given to draw (`ServedConformanceHost.show`'s `content`). */
18
29
  const SHELL_CONTENT = '<p id="porthole-probe-content">Porthole conformance probe</p>';
@@ -250,6 +261,673 @@ export function servedTests(host, options = {}) {
250
261
  await fresh.close();
251
262
  }
252
263
  });
264
+ define("served.domain.self-navigation", "a served frame can't navigate itself away, to an outside site or another content origin, even after a click", async ({ page }) => {
265
+ // Data in the address of a navigation the frame starts itself (P079). Another content
266
+ // origin first: the embedding page's frame-src must let content origins in, so the shell's
267
+ // guard is the only wall there, and the frame's document must stay. Then an outside site,
268
+ // which frame-src stops too (where it does, an engine may show its error page in the
269
+ // frame): no request may reach it.
270
+ const display = await host.show(page, await host.shell("self-navigation"), {
271
+ content: SHELL_CONTENT,
272
+ });
273
+ const frame = await display.frame();
274
+ const sibling = `${(await host.locate(await host.shell("self-navigation-sibling"))).origin}/?d=secret`;
275
+ const outside = `${await host.canary("self-navigation")}?d=secret`;
276
+ const away = async (url) => {
277
+ await frame.evaluate((target) => {
278
+ window.portholeProbeStays = true;
279
+ document.getElementById("porthole-probe-self")?.remove();
280
+ const button = document.createElement("button");
281
+ button.id = "porthole-probe-self";
282
+ button.textContent = "go";
283
+ button.addEventListener("click", () => {
284
+ location.href = target;
285
+ });
286
+ document.body.append(button);
287
+ }, url);
288
+ await frame.click("#porthole-probe-self");
289
+ await page.waitForTimeout(SETTLE_MS);
290
+ };
291
+ await away(sibling);
292
+ const stays = await frame
293
+ .evaluate(() => window.portholeProbeStays === true)
294
+ .catch(() => false);
295
+ expect(stays, "another content origin: the frame's document stays").toBe(true);
296
+ expect(new URL(frame.url()).origin, "another content origin").toBe(display.origin);
297
+ await away(outside);
298
+ expect(await host.canaryHits("self-navigation"), "the outside site").toBe(0);
299
+ });
300
+ // A served page on a tab of its own (P099, the review's S4): a public link, "open in a new
301
+ // tab", a bookmark. No frame's sandbox is there: the page's own (its CSP's `sandbox`) must
302
+ // hold what the frame's holds, and a click (a visitor's, after typing into the page) must open
303
+ // nothing either. One case per wall, so each negative control fails its own.
304
+ const onTab = async (page, scope) => {
305
+ const location = await host.locate(await host.shell(scope));
306
+ const answer = await page.goto(location.url);
307
+ expect(answer?.status()).toBe(200);
308
+ expect(new URL(page.url()).origin).toBe(location.origin);
309
+ };
310
+ /**
311
+ * Clicks `selector` with raw input: a person's click (user activation), and an action that
312
+ * doesn't wait on what the click starts (a navigation refused, a popup that never commits).
313
+ */
314
+ const press = async (page, selector) => {
315
+ const box = await page.locator(selector).boundingBox();
316
+ expect(box, selector).not.toBeNull();
317
+ await page.mouse.click((box?.x ?? 0) + (box?.width ?? 0) / 2, (box?.y ?? 0) + (box?.height ?? 0) / 2);
318
+ };
319
+ /** Windows, downloads and browser dialogs the page's context starts from now on. */
320
+ const watchWindows = (page) => {
321
+ const opened = [];
322
+ const downloads = [];
323
+ const dialogs = [];
324
+ page.context().on("page", (each) => opened.push(each.url()));
325
+ page.on("download", (each) => downloads.push(each.url()));
326
+ page.on("dialog", (each) => {
327
+ dialogs.push(`${each.type()}: ${each.message()}`);
328
+ void each.dismiss();
329
+ });
330
+ return { opened, downloads, dialogs };
331
+ };
332
+ define("served.domain.tab-window-open", "a page on a tab of its own can't open a window (window.open, a picture-in-picture document), even after a click", async ({ page }) => {
333
+ await onTab(page, "tab-window-open");
334
+ const target = await host.canary("tab-window-open");
335
+ const { opened } = watchWindows(page);
336
+ const programmatic = await page.evaluate((url) => {
337
+ // Chromium and WebKit answer null, Firefox throws: either way nothing opens.
338
+ const open = () => {
339
+ try {
340
+ return window.open(`${url}?d=secret`) !== null;
341
+ }
342
+ catch {
343
+ return false;
344
+ }
345
+ };
346
+ // A picture-in-picture document (Chromium, Firefox) is a window of this origin, in a
347
+ // fresh realm the shell never hardened: measured, on a tab it opened with WebRTC there.
348
+ const pip = window.documentPictureInPicture;
349
+ const button = document.createElement("button");
350
+ button.id = "porthole-probe-open";
351
+ button.textContent = "send";
352
+ button.addEventListener("click", () => {
353
+ document.body.dataset.popup = String(open());
354
+ if (pip === undefined) {
355
+ document.body.dataset.pip = "absent";
356
+ return;
357
+ }
358
+ pip.requestWindow({ width: 120, height: 120 }).then((shown) => {
359
+ document.body.dataset.pip = "opened";
360
+ shown.close();
361
+ }, () => {
362
+ document.body.dataset.pip = "refused";
363
+ });
364
+ });
365
+ document.body.append(button);
366
+ return open();
367
+ }, target);
368
+ await press(page, "#porthole-probe-open");
369
+ await page.waitForTimeout(SETTLE_MS);
370
+ expect(programmatic, "on load").toBe(false);
371
+ expect(await page.evaluate(() => document.body.dataset.popup), "after a click").toBe("false");
372
+ expect(["absent", "refused"], "picture-in-picture").toContain(await page.evaluate(() => document.body.dataset.pip));
373
+ expect(opened, "a window opened").toEqual([]);
374
+ expect(await host.canaryHits("tab-window-open")).toBe(0);
375
+ });
376
+ define("served.domain.tab-escapes", "a page on a tab of its own can't open a link in a new window, submit a form, start a download or ask in a browser dialog, even after a click", async ({ page }) => {
377
+ await onTab(page, "tab-escapes");
378
+ const kinds = ["link", "form", "blank-form"];
379
+ const urls = Object.fromEntries(await Promise.all(kinds.map(async (kind) => [kind, await host.canary(`tab-${kind}`)])));
380
+ const { opened, downloads, dialogs } = watchWindows(page);
381
+ await page.evaluate((each) => {
382
+ const box = document.createElement("div");
383
+ box.innerHTML = `<a id="porthole-probe-blank" href="${each.link}?d=secret" target="_blank">blank</a>
384
+ <form id="porthole-probe-form" action="${each.form}" method="get"><input name="d" value="secret"></form>
385
+ <form id="porthole-probe-blank-form" action="${each["blank-form"]}" target="_blank"><input name="d" value="secret"></form>`;
386
+ document.body.append(box);
387
+ // Links clicked past the shell's own click handling, as content may click them.
388
+ window.addEventListener("click", (event) => {
389
+ if (event.target instanceof Element && event.target.closest("a") !== null) {
390
+ event.stopImmediatePropagation();
391
+ }
392
+ }, true);
393
+ const button = document.createElement("button");
394
+ button.id = "porthole-probe-escape";
395
+ button.textContent = "send";
396
+ button.addEventListener("click", () => {
397
+ document.getElementById("porthole-probe-blank")?.click();
398
+ for (const id of ["porthole-probe-form", "porthole-probe-blank-form"]) {
399
+ try {
400
+ document.getElementById(id).submit();
401
+ }
402
+ catch {
403
+ // Refused: what we want.
404
+ }
405
+ }
406
+ const save = document.createElement("a");
407
+ save.href = URL.createObjectURL(new Blob(["secret"]));
408
+ save.download = "secret.txt";
409
+ document.body.append(save);
410
+ save.click();
411
+ // The browser's own dialog, asking for what a phishing page wants (no allow-modals).
412
+ window.prompt("Your password, to go on");
413
+ });
414
+ document.body.append(button);
415
+ }, urls);
416
+ await press(page, "#porthole-probe-escape");
417
+ await page.waitForTimeout(SETTLE_MS);
418
+ expect(opened, "a window opened").toEqual([]);
419
+ expect(downloads, "a download started").toEqual([]);
420
+ expect(dialogs, "a browser dialog showed").toEqual([]);
421
+ expect(new URL(page.url()).pathname, "the page stays").not.toMatch(/canary/u);
422
+ for (const kind of kinds) {
423
+ expect(await host.canaryHits(`tab-${kind}`), kind).toBe(0);
424
+ }
425
+ });
426
+ /** A served shell on a tab opened by another page that keeps a reference to it. */
427
+ const fromOpener = async (page, scope) => {
428
+ const location = await host.locate(await host.shell(scope));
429
+ await page.goto("about:blank");
430
+ await page.setContent('<button id="porthole-probe-opener" type="button">open</button>');
431
+ await page.evaluate((url) => {
432
+ document
433
+ .getElementById("porthole-probe-opener")
434
+ ?.addEventListener("click", () => void window.open(url));
435
+ }, location.url);
436
+ const [tab] = await Promise.all([
437
+ page.waitForEvent("popup"),
438
+ press(page, "#porthole-probe-opener"),
439
+ ]);
440
+ await tab.waitForURL((url) => url.origin === location.origin);
441
+ await tab.waitForLoadState("load");
442
+ return tab;
443
+ };
444
+ /** Adds a button to `page` that sends itself or its opener to `url` when clicked; clicks it. */
445
+ const clickAway = async (page, url, which) => {
446
+ await page.evaluate(([target, whose]) => {
447
+ const button = document.createElement("button");
448
+ button.id = "porthole-probe-away";
449
+ button.textContent = "go";
450
+ button.addEventListener("click", () => {
451
+ try {
452
+ (whose === "opener" ? window.opener : window).location.href = target;
453
+ }
454
+ catch {
455
+ // Refused: what we want.
456
+ }
457
+ });
458
+ document.body.append(button);
459
+ }, [url, which]);
460
+ await press(page, "#porthole-probe-away");
461
+ };
462
+ define("served.domain.tab-opener", "a page on a tab of its own can't navigate the page that opened it, even after a click", async ({ page }) => {
463
+ // `window.open` without noopener: the opener keeps a reference to the tab, and the tab to
464
+ // it, which an unsandboxed page may send elsewhere (reverse tabnabbing).
465
+ const tab = await fromOpener(page, "tab-opener");
466
+ const away = await host.canary("tab-opener");
467
+ await clickAway(tab, `${away}?d=secret`, "opener");
468
+ await page.waitForTimeout(SETTLE_MS);
469
+ expect(page.url(), "the opener stays").toBe("about:blank");
470
+ expect(await host.canaryHits("tab-opener")).toBe(0);
471
+ });
472
+ define("served.domain.tab-navigation", 'a page on a tab of its own can\'t navigate itself away, to a blob: document of its own or an outside site, by location, a link, navigation.navigate() or open(…, "_self"), however the address is given', async ({ page, browserName }) => {
473
+ const located = await host.locate(await host.shell("tab-navigation"));
474
+ // Location granted by the browser, so a document the shell never ran in would get it.
475
+ await page
476
+ .context()
477
+ .grantPermissions(["geolocation"], { origin: located.origin })
478
+ .catch(() => { });
479
+ await page.context().setGeolocation({ latitude: 48.8566, longitude: 2.3522 });
480
+ // A document it wrote itself (its own origin and CSP, sandbox included, no shell), then an
481
+ // outside site; each by `location`, by `navigation.navigate()` (WebKit sent its request though
482
+ // the navigate event cancelled it: measured) and by `open(…, "_self")`.
483
+ // Every way a page starts its own navigation: `location` (set, assign, replace), a
484
+ // target=_self link clicked past the shell, `navigation.navigate()`, `open(…, "_self")`,
485
+ // and the last two given an object whose address is a page of its own the first time it
486
+ // is read and the outside site after, and both again with String.prototype, URL, closest
487
+ // and an event's target replaced by liars that say the address is the page's own. Each
488
+ // outside one has a canary of its own: WebKit was measured sending the request of
489
+ // navigation.navigate() and of a link though the navigate event cancelled them.
490
+ info?.setTimeout(90_000);
491
+ const ways = [
492
+ "location",
493
+ "assign",
494
+ "replace",
495
+ "link",
496
+ "navigate",
497
+ "open",
498
+ "navigate-twice",
499
+ "open-twice",
500
+ "navigate-lying",
501
+ "link-lying",
502
+ ];
503
+ const canaries = Object.fromEntries(await Promise.all(ways.map(async (how) => [how, await host.canary(`tab-nav-${how}`)])));
504
+ /** The tab, loaded again (its session cookie serves it), with one button armed. */
505
+ const arm = (tab, kind, way) => tab.evaluate(([outside, name, how]) => {
506
+ const html = `<!doctype html><title>blob</title><script>
507
+ const said = { rtc: typeof RTCPeerConnection };
508
+ const done = () => { document.title = JSON.stringify(said); };
509
+ navigator.geolocation.getCurrentPosition(() => { said.location = "granted"; done(); }, (e) => { said.location = "denied " + e.code; done(); });
510
+ navigator.mediaDevices && navigator.mediaDevices.getUserMedia({ video: true }).then(() => { said.media = "granted"; done(); }, (e) => { said.media = "rejected " + e.name; done(); });
511
+ </script>`;
512
+ const blob = URL.createObjectURL(new Blob([html], { type: "text/html" }));
513
+ const navigation = window.navigation;
514
+ // Links clicked past the shell's own click handling, as content may click them.
515
+ window.addEventListener("click", (event) => {
516
+ if (event.target instanceof Element && event.target.closest("a") !== null) {
517
+ event.stopImmediatePropagation();
518
+ }
519
+ }, true);
520
+ const twoFaced = (url) => {
521
+ let reads = 0;
522
+ return {
523
+ toString: () => {
524
+ reads += 1;
525
+ return reads === 1 ? location.href : url;
526
+ },
527
+ };
528
+ };
529
+ // Built-ins replaced for the length of one call, each lying in the page's favour.
530
+ const lying = (run) => {
531
+ const here = location.href;
532
+ const liars = [
533
+ [String.prototype, "indexOf", () => 0],
534
+ [String.prototype, "split", () => [here]],
535
+ [
536
+ window,
537
+ "URL",
538
+ function () {
539
+ return { href: here };
540
+ },
541
+ ],
542
+ [Element.prototype, "closest", () => null],
543
+ ];
544
+ const kept = liars.map(([owner, key]) => [owner, key, Object.getOwnPropertyDescriptor(owner, key)]);
545
+ const target = Object.getOwnPropertyDescriptor(Event.prototype, "target");
546
+ for (const [owner, key, value] of liars) {
547
+ Object.defineProperty(owner, key, { configurable: true, writable: true, value });
548
+ }
549
+ Object.defineProperty(Event.prototype, "target", {
550
+ configurable: true,
551
+ get: () => document.body,
552
+ });
553
+ try {
554
+ run();
555
+ }
556
+ finally {
557
+ for (const [owner, key, descriptor] of kept) {
558
+ if (descriptor !== undefined) {
559
+ Object.defineProperty(owner, key, descriptor);
560
+ }
561
+ }
562
+ if (target !== undefined) {
563
+ Object.defineProperty(Event.prototype, "target", target);
564
+ }
565
+ }
566
+ };
567
+ const quiet = (result) => {
568
+ const started = result;
569
+ started?.committed?.catch(() => { });
570
+ started?.finished?.catch(() => { });
571
+ };
572
+ {
573
+ {
574
+ const url = name === "blob" ? blob : `${outside[how]}?d=secret`;
575
+ const button = document.createElement("button");
576
+ button.id = `porthole-probe-${name}-${how}`;
577
+ button.textContent = `${name} by ${how}`;
578
+ button.addEventListener("click", () => {
579
+ try {
580
+ if (how === "location") {
581
+ location.href = url;
582
+ }
583
+ else if (how === "assign") {
584
+ location.assign(url);
585
+ }
586
+ else if (how === "replace") {
587
+ location.replace(url);
588
+ }
589
+ else if (how === "link" || how === "link-lying") {
590
+ const link = document.createElement("a");
591
+ link.href = url;
592
+ link.target = "_self";
593
+ document.body.append(link);
594
+ if (how === "link") {
595
+ link.click();
596
+ }
597
+ else {
598
+ lying(() => link.click());
599
+ }
600
+ }
601
+ else if (how === "navigate-lying") {
602
+ lying(() => quiet(navigation?.navigate(url)));
603
+ }
604
+ else if (how === "open") {
605
+ window.open(url, "_self");
606
+ }
607
+ else if (how === "open-twice") {
608
+ window.open(twoFaced(url), "_self");
609
+ }
610
+ else if (navigation !== undefined) {
611
+ quiet(navigation.navigate(how === "navigate" ? url : twoFaced(url)));
612
+ }
613
+ }
614
+ catch {
615
+ // Refused: what we want.
616
+ }
617
+ });
618
+ document.body.append(button);
619
+ }
620
+ }
621
+ }, [canaries, kind, way]);
622
+ for (const name of ["blob", "outside"]) {
623
+ for (const how of ways) {
624
+ // A tab of its own each time, from a fresh ticket: WebKit was measured sending a
625
+ // cancelled navigation's request from a tab's first, and not from one after another.
626
+ const fresh = await host.locate(await host.shell("tab-navigation"));
627
+ const tab = await page.context().newPage();
628
+ expect((await tab.goto(fresh.url))?.status()).toBe(200);
629
+ const here = tab.url();
630
+ await arm(tab, name, how);
631
+ const id = `porthole-probe-${name}-${how}`;
632
+ // Clicked by the page itself, after the evaluation returns: none of these needs a
633
+ // person's click, and a Playwright action may wait on a navigation the engine started
634
+ // and dropped (measured: WebKit, a mouse click after these, never returned).
635
+ await tab.evaluate((each) => {
636
+ setTimeout(() => document.getElementById(each)?.click(), 0);
637
+ }, id);
638
+ await tab.waitForTimeout(SETTLE_MS);
639
+ if (tab.url().startsWith("blob:")) {
640
+ // What such a document gets, where nothing stopped it (P099's accepted limit).
641
+ info?.annotations.push({
642
+ type: "measured",
643
+ description: `${browserName}: a blob: document of its own, by ${how}, got ${await tab.title()}`,
644
+ });
645
+ }
646
+ expect(tab.url(), `a ${name === "blob" ? "blob: document" : "outside site"} by ${how}: the tab stays`).toBe(here);
647
+ await tab.close();
648
+ }
649
+ }
650
+ await page.waitForTimeout(SETTLE_MS);
651
+ const heard = (await Promise.all(ways.map(async (how) => [how, await host.canaryHits(`tab-nav-${how}`)]))).filter(([, hits]) => hits > 0);
652
+ expect(heard, "the outside site heard these").toEqual([]);
653
+ });
654
+ define("served.domain.tab-links", "a page on a tab of its own can't send a link elsewhere by changing it after the shell read it, or from a shadow root; its fragment links and its own cancels still work", async ({ page }) => {
655
+ // The browser follows a link with what it is once every listener ran; the shell follows
656
+ // what it read in the first. Each in a fresh tab (WebKit sent a cancelled navigation's
657
+ // request from a tab's first attempt), each outside one with a canary of its own.
658
+ info?.setTimeout(90_000);
659
+ const ways = [
660
+ "switch-href",
661
+ "switch-target",
662
+ "add-href",
663
+ "drop-download",
664
+ "open-shadow",
665
+ "closed-shadow",
666
+ ];
667
+ const canaries = Object.fromEntries(await Promise.all(ways.map(async (how) => [how, await host.canary(`tab-links-${how}`)])));
668
+ const freshTab = async () => {
669
+ const located = await host.locate(await host.shell("tab-links"));
670
+ const tab = await page.context().newPage();
671
+ expect((await tab.goto(located.url))?.status()).toBe(200);
672
+ return tab;
673
+ };
674
+ for (const how of ways) {
675
+ const tab = await freshTab();
676
+ const here = tab.url();
677
+ await tab.evaluate(([way, outside]) => {
678
+ const url = `${outside}?d=secret`;
679
+ const link = document.createElement("a");
680
+ link.textContent = "go";
681
+ if (way === "switch-href") {
682
+ link.href = location.href;
683
+ }
684
+ else if (way === "switch-target") {
685
+ link.href = url;
686
+ link.target = "_blank";
687
+ }
688
+ else if (way === "drop-download") {
689
+ link.href = "data.bin";
690
+ link.setAttribute("download", "data.bin");
691
+ }
692
+ else if (way !== "add-href") {
693
+ link.href = url;
694
+ }
695
+ if (way === "open-shadow" || way === "closed-shadow") {
696
+ const holder = document.createElement("div");
697
+ document.body.append(holder);
698
+ const root = holder.attachShadow({
699
+ mode: way === "open-shadow" ? "open" : "closed",
700
+ });
701
+ root.append(link);
702
+ // Past every listener after the shell's, the shadow tree's own included.
703
+ window.addEventListener("click", (event) => event.stopImmediatePropagation(), true);
704
+ }
705
+ else {
706
+ document.body.append(link);
707
+ // After the shell's first listener, and past every one after it: the link changed
708
+ // before the browser reads it.
709
+ window.addEventListener("click", (event) => {
710
+ event.stopImmediatePropagation();
711
+ if (way === "switch-target") {
712
+ link.target = "_self";
713
+ }
714
+ else {
715
+ link.href = url;
716
+ }
717
+ if (way === "drop-download") {
718
+ link.removeAttribute("download");
719
+ }
720
+ }, true);
721
+ }
722
+ setTimeout(() => link.click(), 0);
723
+ }, [how, canaries[how] ?? ""]);
724
+ await tab.waitForTimeout(SETTLE_MS);
725
+ expect(tab.url(), `${how}: the tab stays`).toBe(here);
726
+ await tab.close();
727
+ }
728
+ await page.waitForTimeout(SETTLE_MS);
729
+ const heard = (await Promise.all(ways.map(async (how) => [how, await host.canaryHits(`tab-links-${how}`)]))).filter(([, hits]) => hits > 0);
730
+ expect(heard, "the outside site heard these").toEqual([]);
731
+ // Still as before: a fragment link jumps; a link content cancels goes nowhere.
732
+ const tab = await freshTab();
733
+ await tab.evaluate(() => {
734
+ const below = document.createElement("p");
735
+ below.id = "porthole-probe-below";
736
+ const jump = document.createElement("a");
737
+ jump.id = "porthole-probe-jump";
738
+ jump.href = "#porthole-probe-below";
739
+ jump.textContent = "jump";
740
+ const kept = document.createElement("a");
741
+ kept.id = "porthole-probe-kept";
742
+ kept.href = "#porthole-probe-kept";
743
+ kept.textContent = "kept";
744
+ kept.addEventListener("click", (event) => event.preventDefault());
745
+ document.body.append(jump, kept, below);
746
+ setTimeout(() => jump.click(), 0);
747
+ });
748
+ await expect
749
+ .poll(() => tab.evaluate(() => location.hash), { timeout: 3_000 })
750
+ .toBe("#porthole-probe-below");
751
+ await tab.evaluate(() => {
752
+ setTimeout(() => document.getElementById("porthole-probe-kept")?.click(), 0);
753
+ });
754
+ await tab.waitForTimeout(SETTLE_MS);
755
+ expect(await tab.evaluate(() => location.hash), "a click content cancelled").toBe("#porthole-probe-below");
756
+ await tab.close();
757
+ });
758
+ define("served.domain.tab-devices", "a page on a tab of its own gets no camera, microphone, location or full screen, even with the browser's permission and a click", async ({ page, browserName }) => {
759
+ const location = await host.locate(await host.shell("tab-devices"));
760
+ // The browser's permission given (a person who said yes before): only the page's own
761
+ // policy may refuse. An engine Playwright can't grant a name to asks, and is refused.
762
+ const context = page.context();
763
+ for (const name of ["geolocation", "camera", "microphone"]) {
764
+ await context.grantPermissions([name], { origin: location.origin }).catch(() => { });
765
+ }
766
+ await context.setGeolocation({ latitude: 48.8566, longitude: 2.3522 });
767
+ const warnings = [];
768
+ page.on("console", (message) => {
769
+ if (/permissions.policy/iu.test(message.text())) {
770
+ warnings.push(message.text());
771
+ }
772
+ });
773
+ const answer = await page.goto(location.url);
774
+ expect(answer?.status()).toBe(200);
775
+ await page.evaluate(() => {
776
+ const button = document.createElement("button");
777
+ button.id = "porthole-probe-devices";
778
+ button.textContent = "share";
779
+ button.addEventListener("click", () => {
780
+ // Full screen first: it takes the click's activation.
781
+ const element = document.documentElement;
782
+ const fullscreen = typeof element.requestFullscreen === "function"
783
+ ? element.requestFullscreen().then(() => "entered", () => "rejected")
784
+ : Promise.resolve("absent");
785
+ const media = navigator.mediaDevices === undefined
786
+ ? Promise.resolve("absent")
787
+ : navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
788
+ stream.getTracks().forEach((track) => track.stop());
789
+ return "granted";
790
+ }, (error) => `rejected ${error instanceof Error ? error.name : String(error)}`);
791
+ const position = new Promise((resolve) => {
792
+ navigator.geolocation.getCurrentPosition(() => resolve("granted"), (error) => resolve(`denied ${error.code}`), { timeout: 3_000 });
793
+ });
794
+ void Promise.all([fullscreen, media, position]).then(([screen, devices, place]) => {
795
+ if (document.fullscreenElement !== null) {
796
+ void document.exitFullscreen();
797
+ }
798
+ document.body.dataset.devices = JSON.stringify({
799
+ fullscreen: screen,
800
+ media: devices,
801
+ location: place,
802
+ });
803
+ });
804
+ });
805
+ document.body.append(button);
806
+ });
807
+ await press(page, "#porthole-probe-devices");
808
+ await expect
809
+ .poll(() => page.evaluate(() => document.body.dataset.devices ?? ""), { timeout: 6_000 })
810
+ .not.toBe("");
811
+ const said = JSON.parse(await page.evaluate(() => document.body.dataset.devices ?? "{}"));
812
+ expect(said.location, "location").toBe("denied 1");
813
+ // No stream, however it is refused: a machine without a camera says NotFoundError even
814
+ // where the policy would refuse (measured: Chromium, the header alone).
815
+ expect(said.media, "camera and microphone").not.toBe("granted");
816
+ expect(["rejected", "absent"], "full screen").toContain(said.fullscreen);
817
+ if (warnings.length > 0) {
818
+ info?.annotations.push({
819
+ type: "measured",
820
+ description: `${browserName}: ${warnings.slice(0, 3).join(" | ")}`,
821
+ });
822
+ }
823
+ });
824
+ define("served.domain.tab-prompts", "a page on a tab of its own can't ask for a passkey, a payment (Apple Pay too) or a share, or put a video in full screen, even after a click", async ({ page }) => {
825
+ // Each where the engine has it, refused at once (a prompt would wait for the person, up
826
+ // to the request's own timeout). A payment method's address is fetched by the browser,
827
+ // outside the CSP: the canary must hear nothing.
828
+ await onTab(page, "tab-prompts");
829
+ const canary = await host.canary("tab-payment");
830
+ await page.evaluate((payTo) => {
831
+ const button = document.createElement("button");
832
+ button.id = "porthole-probe-prompts";
833
+ button.textContent = "pay";
834
+ const timed = (start) => {
835
+ const begun = performance.now();
836
+ let asked;
837
+ try {
838
+ asked = start();
839
+ }
840
+ catch (error) {
841
+ return Promise.resolve(`refused ${error instanceof Error ? error.name : "error"} at once`);
842
+ }
843
+ if (asked === undefined) {
844
+ return Promise.resolve("absent");
845
+ }
846
+ return asked.then(() => "granted", (error) => `refused ${error instanceof Error ? error.name : "error"}${performance.now() - begun < 1_500 ? " at once" : " later"}`);
847
+ };
848
+ const challenge = new Uint8Array(32);
849
+ button.addEventListener("click", () => {
850
+ const passkey = timed(() => navigator.credentials?.create({
851
+ publicKey: {
852
+ challenge,
853
+ rp: { name: "Probe" },
854
+ user: { id: challenge, name: "probe", displayName: "Probe" },
855
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],
856
+ timeout: 6_000,
857
+ },
858
+ }));
859
+ const payment = timed(() => typeof PaymentRequest === "function"
860
+ ? new PaymentRequest([{ supportedMethods: `${payTo}?d=secret` }], {
861
+ total: { label: "Probe", amount: { currency: "USD", value: "1.00" } },
862
+ }).show()
863
+ : undefined);
864
+ const share = timed(() => typeof navigator.share === "function"
865
+ ? navigator.share({ title: "Probe", url: `${payTo}?via=share` })
866
+ : undefined);
867
+ // WebKit's Apple Pay sheet, where it has one: a session begun from a click.
868
+ const ApplePay = window.ApplePaySession;
869
+ const applePay = timed(() => {
870
+ if (ApplePay === undefined) {
871
+ return undefined;
872
+ }
873
+ const session = new ApplePay(3, {
874
+ countryCode: "US",
875
+ currencyCode: "USD",
876
+ supportedNetworks: ["visa"],
877
+ merchantCapabilities: ["supports3DS"],
878
+ total: { label: "Probe", amount: "1.00" },
879
+ });
880
+ return new Promise((resolve, reject) => {
881
+ session.addEventListener("cancel", () => reject(new DOMException("cancelled", "AbortError")));
882
+ session.begin();
883
+ setTimeout(() => resolve("begun"), 1_000);
884
+ });
885
+ });
886
+ const video = document.createElement("video");
887
+ document.body.append(video);
888
+ const enter = video
889
+ .webkitEnterFullscreen;
890
+ let videoFullscreen = "absent";
891
+ if (typeof enter === "function") {
892
+ try {
893
+ enter.call(video);
894
+ videoFullscreen = "called";
895
+ }
896
+ catch (error) {
897
+ videoFullscreen = `refused ${error instanceof Error ? error.name : "error"}`;
898
+ }
899
+ }
900
+ void Promise.all([passkey, payment, share, applePay]).then(([key, pay, sent, apple]) => {
901
+ document.body.dataset.prompts = JSON.stringify({
902
+ passkey: key,
903
+ payment: pay,
904
+ share: sent,
905
+ applePay: apple,
906
+ video: videoFullscreen,
907
+ shown: video
908
+ .webkitDisplayingFullscreen === true,
909
+ });
910
+ });
911
+ });
912
+ document.body.append(button);
913
+ }, canary);
914
+ await press(page, "#porthole-probe-prompts");
915
+ await expect
916
+ .poll(() => page.evaluate(() => document.body.dataset.prompts ?? ""), {
917
+ timeout: 10_000,
918
+ })
919
+ .not.toBe("");
920
+ const said = JSON.parse(await page.evaluate(() => document.body.dataset.prompts ?? "{}"));
921
+ const atOnce = (value) => value === "absent" || (typeof value === "string" && /^refused \w+ at once$/u.test(value));
922
+ expect(atOnce(said.passkey), `a passkey: ${String(said.passkey)}`).toBe(true);
923
+ expect(atOnce(said.payment), `a payment: ${String(said.payment)}`).toBe(true);
924
+ expect(atOnce(said.share), `a share: ${String(said.share)}`).toBe(true);
925
+ expect(atOnce(said.applePay), `Apple Pay: ${String(said.applePay)}`).toBe(true);
926
+ expect(said.video === "absent" || String(said.video).startsWith("refused"), `a video's full screen: ${String(said.video)}`).toBe(true);
927
+ expect(said.shown, "a video in full screen").toBe(false);
928
+ await page.waitForTimeout(SETTLE_MS);
929
+ expect(await host.canaryHits("tab-payment"), "the payment method's address").toBe(0);
930
+ });
253
931
  define("served.domain.frame-ancestors", "only the host's origins may frame content", async ({ page }) => {
254
932
  const location = await host.locate(await host.shell("foreign"));
255
933
  await host.frameFromForeignOrigin(page, location.url);
@@ -404,11 +1082,14 @@ export function servedTests(host, options = {}) {
404
1082
  await page.goto(location.url);
405
1083
  await expect(page.locator("html")).toHaveAttribute("data-app", "ready");
406
1084
  });
407
- define("served.url.framed", "a framed app's own requests ride on its partitioned cookie", async ({ page, browserName }) => {
408
- // Measured (P025): WebKit keeps no cookie in a cross-site frame, partitioned or not, so a
409
- // framed app's subresources are refused there; such hosts open the app on a tab.
410
- typed.fail(browserName === "webkit", "WebKit keeps no cookie in a cross-site frame");
1085
+ define("served.url.framed", "a framed app's own requests ride on its partitioned cookie", async ({ page }) => {
1086
+ // Where the browser keeps no cookie in a cross-site frame (P025: Playwright's WebKit on
1087
+ // Linux), a framed app's own requests are refused and such hosts open it on a tab: the
1088
+ // case must fail there. Measured by a probe of the browser's own, not by its name (P098:
1089
+ // the same WebKit on macOS keeps them).
411
1090
  const display = await host.show(page, await host.app("url-framed"));
1091
+ const scheme = new URL(display.origin).protocol === "https:" ? "https:" : "http:";
1092
+ typed.fail(!(await keepsFramedCookies(page, scheme)), "this browser keeps no cookie in a cross-site frame (measured)");
412
1093
  const frame = await display.frame();
413
1094
  await expect
414
1095
  .poll(() => frame.evaluate(() => document.documentElement.dataset.app ?? null), {
@@ -416,6 +1097,58 @@ export function servedTests(host, options = {}) {
416
1097
  })
417
1098
  .toBe("ready");
418
1099
  });
1100
+ define("served.url.siblings", "another origin's page never rides an app's cookie: its load of the app's script is refused", async ({ page, browserName }) => {
1101
+ // P101: two apps framed on one host page share its cookie partition, and sibling labels
1102
+ // are same-site until the content domain is on the Public Suffix List (P047), so a tab's
1103
+ // Lax cookie goes with a sibling's requests too. The app's own load is the control.
1104
+ const load = (frame, src) => frame.evaluate((url) => new Promise((resolve) => {
1105
+ const script = document.createElement("script");
1106
+ script.addEventListener("load", () => resolve("load"));
1107
+ script.addEventListener("error", () => resolve("error"));
1108
+ script.src = url;
1109
+ document.head.append(script);
1110
+ setTimeout(() => resolve("timeout"), 3_000);
1111
+ }), src);
1112
+ const ready = (frame) => expect
1113
+ .poll(() => frame.evaluate(() => document.documentElement.dataset.app ?? null), {
1114
+ timeout: 3_000,
1115
+ })
1116
+ .toBe("ready");
1117
+ const scriptOf = async (frame, origin) => {
1118
+ const src = await frame.evaluate(() => document.querySelector("script[src]")?.src ?? "");
1119
+ expect(src, "the app's page loads a script").not.toBe("");
1120
+ expect(new URL(src).origin, "from its own origin").toBe(origin);
1121
+ return src;
1122
+ };
1123
+ // Framed side by side, where the engine keeps a framed cookie (WebKit doesn't, P025).
1124
+ if (browserName !== "webkit") {
1125
+ const a = await host.show(page, await host.app("url-siblings-a"));
1126
+ const frameA = await a.frame();
1127
+ await ready(frameA);
1128
+ const script = await scriptOf(frameA, a.origin);
1129
+ expect(await load(frameA, script), "the app's own load").toBe("load");
1130
+ const b = await host.show(page, await host.app("url-siblings-b"));
1131
+ const frameB = await b.frame();
1132
+ await ready(frameB);
1133
+ expect(await load(frameB, script), "another app's frame loading it").toBe("error");
1134
+ }
1135
+ // Each on a tab of its own, in one browser.
1136
+ const c = await host.locate(await host.app("url-siblings-c"));
1137
+ const d = await host.locate(await host.app("url-siblings-d"));
1138
+ const tab = await page.context().newPage();
1139
+ try {
1140
+ await tab.goto(c.url);
1141
+ await ready(tab.mainFrame());
1142
+ const script = await scriptOf(tab.mainFrame(), c.origin);
1143
+ expect(await load(tab.mainFrame(), script), "the app's own load").toBe("load");
1144
+ await tab.goto(d.url);
1145
+ await ready(tab.mainFrame());
1146
+ expect(await load(tab.mainFrame(), script), "another app's tab loading it").toBe("error");
1147
+ }
1148
+ finally {
1149
+ await tab.close();
1150
+ }
1151
+ });
419
1152
  }
420
1153
  return tests;
421
1154
  }