@botiverse/porthole 0.13.0 → 0.14.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 (68) hide show
  1. package/dist/annotate/types.d.ts +32 -3
  2. package/dist/annotate/types.js +4 -0
  3. package/dist/annotate/validate.js +19 -2
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/compile/policy.d.ts +7 -0
  6. package/dist/compile/policy.js +13 -1
  7. package/dist/config/schema.d.ts +11 -0
  8. package/dist/config/validate.js +19 -0
  9. package/dist/conformance/harness-source.js +1 -1
  10. package/dist/displays/displays.js +3 -1
  11. package/dist/guide/limits.js +1 -1
  12. package/dist/host/create-host.d.ts +2 -0
  13. package/dist/host/create-host.js +73 -3
  14. package/dist/host/pass-on.d.ts +15 -0
  15. package/dist/host/pass-on.js +65 -0
  16. package/dist/host/types.d.ts +22 -0
  17. package/dist/index.d.ts +4 -1
  18. package/dist/index.js +4 -1
  19. package/dist/isolation/types.d.ts +8 -0
  20. package/dist/isolation/types.js +8 -0
  21. package/dist/platform/focus-guard.d.ts +71 -2
  22. package/dist/platform/focus-guard.js +187 -12
  23. package/dist/platform/types.d.ts +8 -1
  24. package/dist/platform/web.js +60 -4
  25. package/dist/presets/presets.d.ts +2 -0
  26. package/dist/presets/presets.js +1 -0
  27. package/dist/server/files.js +19 -3
  28. package/dist/server/index.d.ts +1 -0
  29. package/dist/server/index.js +4 -0
  30. package/dist/server/nested.d.ts +37 -0
  31. package/dist/server/nested.js +70 -0
  32. package/dist/server/server.js +57 -7
  33. package/dist/shell/annotate.d.ts +1 -1
  34. package/dist/shell/annotate.js +157 -7
  35. package/dist/shell/frame.d.ts +45 -0
  36. package/dist/shell/frame.js +250 -0
  37. package/dist/shell/plan.js +2 -1
  38. package/dist/shell/runtime.js +49 -14
  39. package/docs/ADOPTING.md +56 -2
  40. package/docs/ARCHITECTURE.md +23 -0
  41. package/docs/DECISIONS.md +209 -0
  42. package/docs/DESIGN.md +9 -0
  43. package/docs/THREAT_MODEL.md +75 -5
  44. package/package.json +1 -1
  45. package/src/annotate/types.ts +28 -3
  46. package/src/annotate/validate.ts +23 -2
  47. package/src/compile/policy.ts +14 -1
  48. package/src/config/schema.ts +11 -0
  49. package/src/config/validate.ts +23 -0
  50. package/src/displays/displays.ts +3 -1
  51. package/src/guide/limits.ts +1 -1
  52. package/src/host/create-host.ts +76 -4
  53. package/src/host/pass-on.ts +73 -0
  54. package/src/host/types.ts +20 -0
  55. package/src/index.ts +4 -1
  56. package/src/isolation/types.ts +12 -0
  57. package/src/platform/focus-guard.ts +258 -15
  58. package/src/platform/types.ts +8 -1
  59. package/src/platform/web.ts +81 -9
  60. package/src/presets/presets.ts +3 -0
  61. package/src/server/files.ts +19 -3
  62. package/src/server/index.ts +10 -0
  63. package/src/server/nested.ts +86 -0
  64. package/src/server/server.ts +65 -6
  65. package/src/shell/annotate.ts +157 -7
  66. package/src/shell/frame.ts +268 -0
  67. package/src/shell/plan.ts +2 -1
  68. package/src/shell/runtime.ts +49 -14
@@ -6,7 +6,9 @@ import { randomBytes } from "./crypto.js";
6
6
  import { isHostLabel, reservedLabels } from "./naming.js";
7
7
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.js";
8
8
  import { libraryFile } from "./libraries.js";
9
- import { ownLoad, serveAsset, serveFile } from "./files.js";
9
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.js";
10
+ import { nestedAncestors, nestedShellResponse } from "./nested.js";
11
+ import { DEFAULT_ENTRY } from "../files/paths.js";
10
12
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
11
13
  import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
12
14
  import { parseViewer } from "../runtime/levels.js";
@@ -425,6 +427,7 @@ export function createServer(options) {
425
427
  }
426
428
  return {
427
429
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
430
+ document: stored.html,
428
431
  compiled: config,
429
432
  assets: true,
430
433
  };
@@ -648,10 +651,10 @@ export function createServer(options) {
648
651
  return null;
649
652
  }
650
653
  }
651
- function documentHeaders(csp, permissions) {
654
+ function documentHeaders(csp, permissions, ancestors = frameAncestors) {
652
655
  return new Headers({
653
656
  "content-type": "text/html; charset=utf-8",
654
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
657
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
655
658
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
656
659
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
657
660
  "cache-control": "no-store",
@@ -730,7 +733,9 @@ export function createServer(options) {
730
733
  }
731
734
  const access = await sealedAccess(request, label, token);
732
735
  if (access === null) {
733
- return page(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", method, "session");
736
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
737
+ // config without nesting never frames this address but at the host.
738
+ return statusPage(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", nestedAncestors(origin, frameAncestors), method, "session", [...options.hostOrigins, origin]);
734
739
  }
735
740
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
736
741
  // sends a frame's path, where some send no Referer that names it.
@@ -815,6 +820,43 @@ export function createServer(options) {
815
820
  if (served === null) {
816
821
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
817
822
  }
823
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
824
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
825
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
826
+ const nested = served.compiled.config.nested === true;
827
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
828
+ if (nested && !sealedAt) {
829
+ if (!isNavigation(request)) {
830
+ return page(404, "Not found", "This page's files are at its own address.", method);
831
+ }
832
+ const sealed = await sealFiles(access);
833
+ let rest = "";
834
+ if ("files" in served) {
835
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
836
+ rest =
837
+ at !== undefined && at.rest !== ""
838
+ ? at.rest
839
+ : entry.includes("/")
840
+ ? entry
841
+ .split("/")
842
+ .map((segment) => encodeURIComponent(segment))
843
+ .join("/")
844
+ : "";
845
+ }
846
+ const shell = nestedShellResponse(served.compiled, {
847
+ origin: access.origin,
848
+ origins: options.hostOrigins,
849
+ page: `${access.origin}${sealed.base}${rest}`,
850
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
851
+ method,
852
+ });
853
+ if (cookie !== null) {
854
+ shell.headers.set("set-cookie", cookie);
855
+ }
856
+ return shell;
857
+ }
858
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
859
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
818
860
  if ("files" in served) {
819
861
  if (at !== undefined) {
820
862
  return serveFile({
@@ -828,7 +870,7 @@ export function createServer(options) {
828
870
  source: at.source,
829
871
  compiled: served.compiled,
830
872
  hostOrigins: options.hostOrigins,
831
- frameAncestors,
873
+ frameAncestors: ancestors,
832
874
  ...versionOf(access.instance),
833
875
  });
834
876
  }
@@ -859,11 +901,19 @@ export function createServer(options) {
859
901
  // A page that may use its artifact's assets loads them from its own origin (P089); every
860
902
  // served page carries its frame's sandbox, a tab of its own included (P099).
861
903
  const { config, cspDirectives } = served.compiled;
862
- const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config));
904
+ const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config), ancestors);
863
905
  if (cookie !== null) {
864
906
  headers.set("set-cookie", cookie);
865
907
  }
866
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
908
+ // A nested page's document takes messages from its shell, on its own origin (P111).
909
+ const html = nested
910
+ ? served.compiled.shellDocument({
911
+ origins: [access.origin],
912
+ document: served.document ?? "",
913
+ cspMeta: false,
914
+ })
915
+ : served.html;
916
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
867
917
  }
868
918
  /**
869
919
  * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
@@ -8,7 +8,7 @@
8
8
  * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
9
9
  * - picking an element: the element under the pointer (or finger) is outlined with its name; a
10
10
  * click or tap picks it, and the content's own handlers never see that click (unless the content
11
- * patched the DOM's built-ins, P105); Escape cancels;
11
+ * patched the DOM's built-ins, P105); Escape cancels (while selecting text too, P112);
12
12
  * - selecting text: each selection that settles is reported, with where it is, and its clearing;
13
13
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
14
14
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the
@@ -8,7 +8,7 @@
8
8
  * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
9
9
  * - picking an element: the element under the pointer (or finger) is outlined with its name; a
10
10
  * click or tap picks it, and the content's own handlers never see that click (unless the content
11
- * patched the DOM's built-ins, P105); Escape cancels;
11
+ * patched the DOM's built-ins, P105); Escape cancels (while selecting text too, P112);
12
12
  * - selecting text: each selection that settles is reported, with where it is, and its clearing;
13
13
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
14
14
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the
@@ -39,6 +39,8 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
39
39
  cancelled: "porthole/annotate.cancelled",
40
40
  anchored: "porthole/annotate.anchored",
41
41
  activated: "porthole/annotate.activated",
42
+ track: "porthole/annotate.track",
43
+ tracked: "porthole/annotate.tracked",
42
44
  };
43
45
  // The DOM's own functions, taken before content runs.
44
46
  const elementFromPoint = Document.prototype.elementFromPoint;
@@ -51,6 +53,9 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
51
53
  const elementRect = Element.prototype.getBoundingClientRect;
52
54
  const rangeRect = Range.prototype.getBoundingClientRect;
53
55
  const rangeRects = Range.prototype.getClientRects;
56
+ const setStart = Range.prototype.setStart;
57
+ const setStartBefore = Range.prototype.setStartBefore;
58
+ const compareBoundaryPoints = Range.prototype.compareBoundaryPoints;
54
59
  const attachShadow = Element.prototype.attachShadow;
55
60
  const getAttribute = Element.prototype.getAttribute;
56
61
  const listenOn = EventTarget.prototype.addEventListener;
@@ -389,7 +394,7 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
389
394
  return shadow;
390
395
  };
391
396
 
392
- let mode = { elements: false, text: false };
397
+ let mode = { elements: false, text: false, hold: false };
393
398
  let hover = null;
394
399
  let marks = [];
395
400
  // The markers as last drawn, for a click to find: { id, element }. Each mark keeps its
@@ -817,7 +822,76 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
817
822
  }
818
823
  };
819
824
 
820
- const resultOf = (mark) => (mark.found === null ? { id: mark.id, state: "orphaned" } : { id: mark.id, state: "attached", rect: box(rectOf(mark.found)) });
825
+ // The mark the host follows (P112): its box at each animation frame where it moved, at most
826
+ // one every 16 ms, read through the platform's own frame clock (taken before content runs).
827
+ const nextFrame = window.requestAnimationFrame.bind(window);
828
+ let tracking = null;
829
+ let trackedBox = null;
830
+ let trackedAt = 0;
831
+ let trackFrame = 0;
832
+ const trackTick = () => {
833
+ trackFrame = 0;
834
+ if (tracking === null) {
835
+ return;
836
+ }
837
+ const mark = marks.find((each) => each.id === tracking);
838
+ if (mark !== undefined && mark.found !== null) {
839
+ const rect = box(rectOf(mark.found));
840
+ const now = performance.now();
841
+ if (apart(trackedBox, rect) && now - trackedAt >= 16) {
842
+ trackedBox = rect;
843
+ trackedAt = now;
844
+ tell(M.tracked, { id: tracking, rect });
845
+ }
846
+ }
847
+ trackFrame = nextFrame(trackTick);
848
+ };
849
+ const track = (id) => {
850
+ tracking = typeof id === "string" ? id : null;
851
+ trackedBox = null;
852
+ if (tracking !== null && trackFrame === 0) {
853
+ trackFrame = nextFrame(trackTick);
854
+ }
855
+ };
856
+
857
+ // Where each found mark starts in the document, in order (P112): its place in a list the host
858
+ // sorts, offscreen ones too. Read now, every time results are told.
859
+ const startOf = (found) => {
860
+ const range = createRange.call(document);
861
+ if (found.range) {
862
+ setStart.call(range, found.range.startContainer, found.range.startOffset);
863
+ } else {
864
+ setStartBefore.call(range, found.element);
865
+ }
866
+ return range;
867
+ };
868
+ const ordersOf = () => {
869
+ const placed = [];
870
+ for (const mark of marks) {
871
+ if (mark.found !== null) {
872
+ try {
873
+ placed.push({ mark, start: startOf(mark.found) });
874
+ } catch (_) {}
875
+ }
876
+ }
877
+ placed.sort((a, b) => {
878
+ try {
879
+ return compareBoundaryPoints.call(a.start, Range.START_TO_START, b.start);
880
+ } catch (_) {
881
+ return 0;
882
+ }
883
+ });
884
+ const orders = new Map();
885
+ placed.forEach((each, at) => orders.set(each.mark, at));
886
+ return orders;
887
+ };
888
+ const resultOf = (mark, orders) => {
889
+ if (mark.found === null) {
890
+ return { id: mark.id, state: "orphaned" };
891
+ }
892
+ const order = (orders || ordersOf()).get(mark);
893
+ return Object.assign({ id: mark.id, state: "attached", rect: box(rectOf(mark.found)) }, order === undefined ? {} : { order });
894
+ };
821
895
  // Two boxes more than 0.5 px apart on any side (or one of them unknown).
822
896
  const apart = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.5 || Math.abs(a.y - b.y) > 0.5 || Math.abs(a.width - b.width) > 0.5 || Math.abs(a.height - b.height) > 0.5;
823
897
  // What the host was last told of each mark (mark.told), so a settle tells only what moved.
@@ -826,7 +900,7 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
826
900
  if (!told || told.state !== result.state) {
827
901
  return true;
828
902
  }
829
- return result.state === "attached" && apart(told.rect, result.rect);
903
+ return result.state === "attached" && (apart(told.rect, result.rect) || told.order !== result.order);
830
904
  };
831
905
  const report = (pairs) => {
832
906
  if (pairs.length > 0) {
@@ -836,7 +910,10 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
836
910
  tell(M.anchored, { results: pairs.map((pair) => pair.result) });
837
911
  }
838
912
  };
839
- const resultsOf = (only) => marks.map((mark) => ({ mark, result: resultOf(mark) })).filter((pair) => !only || moved(pair.mark, pair.result));
913
+ const resultsOf = (only) => {
914
+ const orders = ordersOf();
915
+ return marks.map((mark) => ({ mark, result: resultOf(mark, orders) })).filter((pair) => !only || moved(pair.mark, pair.result));
916
+ };
840
917
  // Finds every mark again; tells the host every result (after show, or when a state changed),
841
918
  // only the marks that moved (once the content is quiet), or nothing.
842
919
  const anchorAll = (all, quiet) => {
@@ -1142,6 +1219,66 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1142
1219
  redraw();
1143
1220
  }
1144
1221
  }, true);
1222
+
1223
+ // Holding a block (P112, hold mode): a finger held still for 500 ms selects the block under
1224
+ // it, and the click its release makes is the shell's; every other tap is the page's, as is
1225
+ // any mouse. On the platform's own timer (taken before content runs).
1226
+ const later = window.setTimeout.bind(window);
1227
+ const cancelLater = window.clearTimeout.bind(window);
1228
+ const HOLD_MS = 500;
1229
+ const HOLD_SLOP = 10;
1230
+ let holding = null;
1231
+ let swallowUntil = 0;
1232
+ const endHold = () => {
1233
+ if (holding !== null) {
1234
+ cancelLater(holding.timer);
1235
+ holding = null;
1236
+ }
1237
+ };
1238
+ window.addEventListener("pointerdown", (event) => {
1239
+ if (!mode.hold || mode.elements || event.pointerType !== "touch" || !event.isPrimary) {
1240
+ return;
1241
+ }
1242
+ endHold();
1243
+ const x = event.clientX;
1244
+ const y = event.clientY;
1245
+ holding = {
1246
+ x,
1247
+ y,
1248
+ timer: later(() => {
1249
+ holding = null;
1250
+ if (!mode.hold) {
1251
+ return;
1252
+ }
1253
+ const element = under(x, y);
1254
+ const anchor = element === null ? null : elementAnchor(element, textIndex());
1255
+ if (anchor === null) {
1256
+ return;
1257
+ }
1258
+ swallowUntil = performance.now() + 2000;
1259
+ tell(M.selected, { anchor, rect: box(elementRect.call(element)) });
1260
+ }, HOLD_MS),
1261
+ };
1262
+ }, true);
1263
+ window.addEventListener("pointermove", (event) => {
1264
+ if (holding !== null && event.pointerType === "touch" && Math.abs(event.clientX - holding.x) + Math.abs(event.clientY - holding.y) > HOLD_SLOP) {
1265
+ endHold();
1266
+ }
1267
+ }, true);
1268
+ for (const type of ["pointerup", "pointercancel"]) {
1269
+ window.addEventListener(type, endHold, true);
1270
+ }
1271
+ for (const type of ["click", "contextmenu"]) {
1272
+ window.addEventListener(type, (event) => {
1273
+ if (swallowUntil > performance.now()) {
1274
+ if (type === "click") {
1275
+ swallowUntil = 0;
1276
+ }
1277
+ event.preventDefault();
1278
+ event.stopImmediatePropagation();
1279
+ }
1280
+ }, true);
1281
+ }
1145
1282
  window.addEventListener("click", (event) => {
1146
1283
  if (!mode.elements) {
1147
1284
  return;
@@ -1170,7 +1307,10 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1170
1307
  tell(M.selected, { anchor, rect: box(elementRect.call(element)) });
1171
1308
  }, true);
1172
1309
  window.addEventListener("keydown", (event) => {
1173
- if (mode.elements && event.key === "Escape") {
1310
+ if (event.key !== "Escape") {
1311
+ return;
1312
+ }
1313
+ if (mode.elements) {
1174
1314
  event.preventDefault();
1175
1315
  event.stopImmediatePropagation();
1176
1316
  mode = { elements: false, text: mode.text };
@@ -1178,6 +1318,12 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1178
1318
  setCursor(false);
1179
1319
  draw();
1180
1320
  tell(M.cancelled, {});
1321
+ return;
1322
+ }
1323
+ // Selecting text (P112): the person wants out too. The key stays the page's (a page that
1324
+ // closes its own dialog on Escape still does); the host decides what ends.
1325
+ if (mode.text) {
1326
+ tell(M.cancelled, {});
1181
1327
  }
1182
1328
  }, true);
1183
1329
 
@@ -1244,7 +1390,7 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1244
1390
  const params = data.params !== null && typeof data.params === "object" ? data.params : {};
1245
1391
  switch (data.method) {
1246
1392
  case M.start:
1247
- mode = { elements: params.elements === true, text: params.text === true };
1393
+ mode = { elements: params.elements === true, text: params.text === true, hold: params.elements === "hold" };
1248
1394
  hover = null;
1249
1395
  reported = null;
1250
1396
  reportedBox = null;
@@ -1276,7 +1422,11 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1276
1422
  case M.focus:
1277
1423
  focus(String(params.id));
1278
1424
  break;
1425
+ case M.track:
1426
+ track(params.id);
1427
+ break;
1279
1428
  case M.clear:
1429
+ track(null);
1280
1430
  pendingFocus = null;
1281
1431
  marks = [];
1282
1432
  active = null;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Porthole's shell for a nested page (P111): the whole document at the address the host frames,
3
+ * with no content in it. It frames the page (the same origin's sealed files' address) in a child
4
+ * sandboxed without `allow-same-origin`, so the page's origin is opaque and nothing of the shell's
5
+ * realm is reachable from it: not its DOM, its globals, its storage, or the window the host hears.
6
+ *
7
+ * The shell:
8
+ * - passes every message between the host (its parent, from the host origins) and the page (its
9
+ * child's window, by `event.source` alone: the page's origin is "null") unchanged, and drops any
10
+ * the page sends in the shell's own namespace (`porthole/shell/`), so the shell's words to the
11
+ * host are only its own;
12
+ * - tells the host its own state (`porthole/shell/state`): whether its transient activation is on,
13
+ * and since when, and whether the page's focus is in it. A gesture in the page activates the
14
+ * page and its ancestors, the shell among them, and nothing on the host's page activates the
15
+ * shell (activation goes up, never down), so the shell's activation turning on is a press or
16
+ * key of the person's in this page. It is read at every animation frame, on its window's focus
17
+ * and blur, and before each message of the page's is passed on (a call made in a click's handler
18
+ * arrives after the state that says so). What it can't see: a gesture while its activation is
19
+ * already on (within 5 s of the last one) turns nothing on;
20
+ * - renews the page's sealed files' address before it ends, and gives the page the new one
21
+ * (`porthole/files-renewed`): the page's own loads aren't its origin's (an opaque origin's never
22
+ * are), so only the shell, on that origin, may renew it (P083);
23
+ * - passes its focus to the page (the host's own move into the frame, or a Tab).
24
+ *
25
+ * Plain ES2020, no imports and no build step, like the runtime. `__PLAN__` is its plan.
26
+ */
27
+ export declare const FRAME_SHELL_RUNTIME: string;
28
+ export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.ts";
29
+ export interface FrameShellOptions {
30
+ /** The host origins: the shell takes messages from its parent only from these. */
31
+ readonly origins: readonly string[];
32
+ /** The page's address: absolute, on the shell's own origin, under `/__porthole/f/`. */
33
+ readonly page: string;
34
+ /** The page frame's accessible name. */
35
+ readonly title?: string;
36
+ /** Where the page's sealed address is renewed (`<base>__porthole/renew`), and when it ends. */
37
+ readonly renew?: {
38
+ readonly url: string;
39
+ readonly expires: number;
40
+ };
41
+ }
42
+ /** The shell's script for `options`: what its document runs, and what its CSP's hash names. */
43
+ export declare function frameShellScript(options: FrameShellOptions): string;
44
+ /** The shell's document around its script: nothing else (its CSP allows that script alone). */
45
+ export declare function frameShellDocument(script: string): string;
@@ -0,0 +1,250 @@
1
+ import { PAGE_SANDBOX_TOKENS } from "../compile/policy.js";
2
+ import { hostOriginProblem } from "../isolation/served.js";
3
+ /**
4
+ * Porthole's shell for a nested page (P111): the whole document at the address the host frames,
5
+ * with no content in it. It frames the page (the same origin's sealed files' address) in a child
6
+ * sandboxed without `allow-same-origin`, so the page's origin is opaque and nothing of the shell's
7
+ * realm is reachable from it: not its DOM, its globals, its storage, or the window the host hears.
8
+ *
9
+ * The shell:
10
+ * - passes every message between the host (its parent, from the host origins) and the page (its
11
+ * child's window, by `event.source` alone: the page's origin is "null") unchanged, and drops any
12
+ * the page sends in the shell's own namespace (`porthole/shell/`), so the shell's words to the
13
+ * host are only its own;
14
+ * - tells the host its own state (`porthole/shell/state`): whether its transient activation is on,
15
+ * and since when, and whether the page's focus is in it. A gesture in the page activates the
16
+ * page and its ancestors, the shell among them, and nothing on the host's page activates the
17
+ * shell (activation goes up, never down), so the shell's activation turning on is a press or
18
+ * key of the person's in this page. It is read at every animation frame, on its window's focus
19
+ * and blur, and before each message of the page's is passed on (a call made in a click's handler
20
+ * arrives after the state that says so). What it can't see: a gesture while its activation is
21
+ * already on (within 5 s of the last one) turns nothing on;
22
+ * - renews the page's sealed files' address before it ends, and gives the page the new one
23
+ * (`porthole/files-renewed`): the page's own loads aren't its origin's (an opaque origin's never
24
+ * are), so only the shell, on that origin, may renew it (P083);
25
+ * - passes its focus to the page (the host's own move into the frame, or a Tab).
26
+ *
27
+ * Plain ES2020, no imports and no build step, like the runtime. `__PLAN__` is its plan.
28
+ */
29
+ export const FRAME_SHELL_RUNTIME = String.raw `(() => {
30
+ "use strict";
31
+ const plan = __PLAN__;
32
+ const PREFIX = "porthole/shell/";
33
+ const own = location.origin;
34
+ let page = null;
35
+ try {
36
+ page = new URL(plan.page);
37
+ } catch (_) {}
38
+ // Only a page of this origin's sealed files: nothing else is ever framed here.
39
+ if (page === null || page.origin !== own || page.pathname.indexOf("/__porthole/f/") !== 0) {
40
+ return;
41
+ }
42
+ // Belt and braces: a plan that would give the page this origin frames nothing.
43
+ if (typeof plan.sandbox !== "string" || /allow-same-origin/i.test(plan.sandbox)) {
44
+ return;
45
+ }
46
+ const root = document.documentElement;
47
+ root.style.height = "100%";
48
+ document.body.style.margin = "0";
49
+ document.body.style.height = "100%";
50
+ document.body.style.background = "transparent";
51
+ const frame = document.createElement("iframe");
52
+ // Scripts only: never allow-same-origin (the page would have this origin, and so this realm).
53
+ frame.setAttribute("sandbox", plan.sandbox);
54
+ frame.setAttribute("allow", "clipboard-read 'none'; clipboard-write 'none'");
55
+ frame.setAttribute("referrerpolicy", "no-referrer");
56
+ frame.title = typeof plan.title === "string" ? plan.title : "Content";
57
+ frame.style.display = "block";
58
+ frame.style.border = "0";
59
+ frame.style.width = "100%";
60
+ frame.style.height = "100%";
61
+ frame.style.background = "transparent";
62
+ frame.src = page.href;
63
+ document.body.append(frame);
64
+
65
+ const framed = window.parent !== window;
66
+ const web = plan.origins.filter((origin) => origin.indexOf("https://") === 0 || origin.indexOf("http://") === 0);
67
+ // To the host: each web host origin (only the parent's is delivered); a desktop app's own scheme
68
+ // is no target a browser takes, so where one is listed and the parent isn't a known web origin,
69
+ // "*" (frame-ancestors holds the parent to the host origins; nothing said here is secret).
70
+ const toHost = (message) => {
71
+ if (!framed) {
72
+ return;
73
+ }
74
+ for (const origin of web) {
75
+ try {
76
+ window.parent.postMessage(message, origin);
77
+ } catch (_) {}
78
+ }
79
+ const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
80
+ if (web.length < plan.origins.length && (parent === null || web.indexOf(parent) === -1)) {
81
+ try {
82
+ window.parent.postMessage(message, "*");
83
+ } catch (_) {}
84
+ }
85
+ };
86
+
87
+ // The shell's own state: its transient activation (and when it turned on), the page's focus.
88
+ // "since" is when the shell saw activation turn on, which a page that holds the thread the shell
89
+ // shares with it (WebKit, Firefox) can push later than the press: so the shell looks every 50 ms
90
+ // and beats as often, and each report says how long it went without a look before (gap). The
91
+ // host takes an activation the shell saw after a stall for uncertain (P111, after its review).
92
+ const activation = navigator.userActivation;
93
+ let active = false;
94
+ let since = 0;
95
+ let focused = false;
96
+ let lookedAt = performance.now();
97
+ let toldAt = 0;
98
+ const tell = (gap) => {
99
+ toldAt = performance.now();
100
+ toHost({
101
+ jsonrpc: "2.0",
102
+ method: PREFIX + "state",
103
+ params: {
104
+ supported: activation !== undefined,
105
+ active,
106
+ ago: active ? Math.max(0, Math.round(performance.now() - since)) : null,
107
+ focused,
108
+ gap: Math.max(0, Math.round(gap)),
109
+ },
110
+ });
111
+ };
112
+ const look = () => {
113
+ const now = performance.now();
114
+ const gap = now - lookedAt;
115
+ lookedAt = now;
116
+ const on = activation !== undefined && activation.isActive === true;
117
+ const inside = document.hasFocus();
118
+ let changed = false;
119
+ if (on !== active) {
120
+ active = on;
121
+ if (on) {
122
+ since = performance.now();
123
+ }
124
+ changed = true;
125
+ }
126
+ if (inside !== focused) {
127
+ focused = inside;
128
+ changed = true;
129
+ }
130
+ if (changed) {
131
+ tell(gap);
132
+ } else if (now - toldAt >= 50) {
133
+ // The heartbeat: the host knows the shell was looking, every 50 ms.
134
+ toldAt = now;
135
+ toHost({ jsonrpc: "2.0", method: PREFIX + "beat", params: { gap: Math.max(0, Math.round(gap)) } });
136
+ }
137
+ };
138
+ const tick = () => {
139
+ look();
140
+ requestAnimationFrame(tick);
141
+ };
142
+ requestAnimationFrame(tick);
143
+ setInterval(look, 50);
144
+ addEventListener("blur", look);
145
+ addEventListener("focus", (event) => {
146
+ // The host's move into the frame (or a Tab) lands here: on to the page.
147
+ if (event.target === window && document.activeElement !== frame) {
148
+ frame.focus();
149
+ }
150
+ look();
151
+ });
152
+ document.addEventListener("visibilitychange", look);
153
+ tell(0);
154
+
155
+ addEventListener("message", (event) => {
156
+ const source = event.source;
157
+ if (source !== null && source === frame.contentWindow) {
158
+ const data = event.data;
159
+ // Never the shell's words in the page's mouth.
160
+ if (data !== null && typeof data === "object" && typeof data.method === "string" && data.method.indexOf(PREFIX) === 0) {
161
+ return;
162
+ }
163
+ // What the shell knows now goes first: a call in a click's handler follows its activation.
164
+ look();
165
+ toHost(data);
166
+ return;
167
+ }
168
+ if (framed && source === window.parent && plan.origins.indexOf(event.origin) !== -1) {
169
+ const child = frame.contentWindow;
170
+ if (child !== null) {
171
+ child.postMessage(event.data, "*");
172
+ }
173
+ }
174
+ });
175
+
176
+ // The page's sealed address, renewed before it ends (P083): the page can't, the shell can.
177
+ if (plan.renew && typeof plan.renew.url === "string" && typeof plan.renew.expires === "number") {
178
+ const prefix = own + "/__porthole/f/";
179
+ let renewUrl = plan.renew.url;
180
+ const renewIn = (expires) => Math.max(30000, expires - Date.now() - 300000);
181
+ const renew = () => {
182
+ fetch(renewUrl, { credentials: "omit", cache: "no-store" })
183
+ .then((answer) => (answer.ok ? answer.json() : null))
184
+ .then((renewed) => {
185
+ if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || renewed.base.indexOf(prefix) !== 0) {
186
+ setTimeout(renew, 60000);
187
+ return;
188
+ }
189
+ renewUrl = renewed.base + "__porthole/renew";
190
+ const child = frame.contentWindow;
191
+ if (child !== null) {
192
+ child.postMessage({ jsonrpc: "2.0", method: "porthole/files-renewed", params: { base: renewed.base } }, "*");
193
+ }
194
+ setTimeout(renew, renewIn(renewed.expires));
195
+ })
196
+ .catch(() => setTimeout(renew, 60000));
197
+ };
198
+ setTimeout(renew, renewIn(plan.renew.expires));
199
+ }
200
+ })();`;
201
+ export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.js";
202
+ /** JSON that is safe inside a `<script>`. */
203
+ const scriptJson = (value) => JSON.stringify(value)
204
+ .replace(/</gu, "\\u003c")
205
+ .replace(/\u2028/gu, "\\u2028")
206
+ .replace(/\u2029/gu, "\\u2029");
207
+ /** The shell's script for `options`: what its document runs, and what its CSP's hash names. */
208
+ export function frameShellScript(options) {
209
+ for (const origin of options.origins) {
210
+ const problem = hostOriginProblem(origin);
211
+ if (problem !== null) {
212
+ throw new TypeError(`frameShellScript: ${problem}`);
213
+ }
214
+ }
215
+ let page;
216
+ try {
217
+ page = new URL(options.page);
218
+ }
219
+ catch {
220
+ throw new TypeError("frameShellScript: page is an absolute URL");
221
+ }
222
+ if (!page.pathname.startsWith("/__porthole/f/") || page.hash !== "") {
223
+ throw new TypeError("frameShellScript: page is under /__porthole/f/, with no fragment");
224
+ }
225
+ return FRAME_SHELL_RUNTIME.replace("__PLAN__", () => scriptJson({
226
+ origins: options.origins,
227
+ page: page.href,
228
+ sandbox: PAGE_SANDBOX_TOKENS.join(" "),
229
+ ...(options.title === undefined ? {} : { title: options.title }),
230
+ ...(options.renew === undefined
231
+ ? {}
232
+ : { renew: { url: options.renew.url, expires: options.renew.expires } }),
233
+ }));
234
+ }
235
+ /** The shell's document around its script: nothing else (its CSP allows that script alone). */
236
+ export function frameShellDocument(script) {
237
+ return `<!doctype html>
238
+ <html lang="en">
239
+ <head>
240
+ <meta charset="utf-8">
241
+ <meta name="color-scheme" content="light dark">
242
+ <meta name="referrer" content="no-referrer">
243
+ <title>Porthole</title>
244
+ </head>
245
+ <body>
246
+ <script>${script}</script>
247
+ </body>
248
+ </html>
249
+ `;
250
+ }