@botiverse/porthole 0.12.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 (94) 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/bridge/bridge.d.ts +8 -1
  5. package/dist/bridge/bridge.js +7 -0
  6. package/dist/bridge/unseen.d.ts +8 -0
  7. package/dist/bridge/unseen.js +17 -0
  8. package/dist/check/files.js +14 -10
  9. package/dist/check/lint.js +1 -1
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/scroll.d.ts +29 -13
  12. package/dist/check/scroll.js +74 -18
  13. package/dist/compile/policy.d.ts +7 -0
  14. package/dist/compile/policy.js +13 -1
  15. package/dist/config/capabilities.d.ts +16 -3
  16. package/dist/config/capabilities.js +1 -0
  17. package/dist/config/schema.d.ts +11 -0
  18. package/dist/config/validate.js +19 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.js +3 -1
  21. package/dist/guide/limits.js +1 -1
  22. package/dist/guide/runtime.js +1 -1
  23. package/dist/host/create-host.d.ts +2 -0
  24. package/dist/host/create-host.js +100 -3
  25. package/dist/host/pass-on.d.ts +15 -0
  26. package/dist/host/pass-on.js +65 -0
  27. package/dist/host/types.d.ts +37 -0
  28. package/dist/index.d.ts +5 -1
  29. package/dist/index.js +5 -1
  30. package/dist/isolation/types.d.ts +8 -0
  31. package/dist/isolation/types.js +8 -0
  32. package/dist/platform/focus-guard.d.ts +212 -0
  33. package/dist/platform/focus-guard.js +620 -0
  34. package/dist/platform/types.d.ts +25 -0
  35. package/dist/platform/web.js +80 -2
  36. package/dist/presets/presets.d.ts +2 -0
  37. package/dist/presets/presets.js +1 -0
  38. package/dist/react/frame.d.ts +8 -0
  39. package/dist/react/frame.js +4 -0
  40. package/dist/runtime/requests.js +34 -12
  41. package/dist/runtime/types.generated.js +1 -1
  42. package/dist/server/files.js +19 -3
  43. package/dist/server/index.d.ts +1 -0
  44. package/dist/server/index.js +4 -0
  45. package/dist/server/nested.d.ts +37 -0
  46. package/dist/server/nested.js +70 -0
  47. package/dist/server/server.js +57 -7
  48. package/dist/shell/annotate.d.ts +1 -1
  49. package/dist/shell/annotate.js +157 -7
  50. package/dist/shell/frame.d.ts +45 -0
  51. package/dist/shell/frame.js +250 -0
  52. package/dist/shell/plan.js +2 -1
  53. package/dist/shell/runtime.js +49 -14
  54. package/docs/ADOPTING.md +140 -7
  55. package/docs/ARCHITECTURE.md +23 -0
  56. package/docs/DECISIONS.md +564 -5
  57. package/docs/DESIGN.md +18 -2
  58. package/docs/THREAT_MODEL.md +192 -30
  59. package/package.json +1 -1
  60. package/src/annotate/types.ts +28 -3
  61. package/src/annotate/validate.ts +23 -2
  62. package/src/bridge/bridge.ts +17 -1
  63. package/src/bridge/unseen.ts +24 -0
  64. package/src/check/files.ts +14 -10
  65. package/src/check/lint.ts +1 -1
  66. package/src/check/scroll.ts +106 -38
  67. package/src/compile/policy.ts +14 -1
  68. package/src/config/capabilities.ts +16 -3
  69. package/src/config/schema.ts +11 -0
  70. package/src/config/validate.ts +23 -0
  71. package/src/displays/displays.ts +3 -1
  72. package/src/guide/limits.ts +1 -1
  73. package/src/guide/runtime.ts +1 -1
  74. package/src/host/create-host.ts +105 -4
  75. package/src/host/pass-on.ts +73 -0
  76. package/src/host/types.ts +33 -0
  77. package/src/index.ts +5 -1
  78. package/src/isolation/types.ts +12 -0
  79. package/src/platform/focus-guard.ts +815 -0
  80. package/src/platform/types.ts +24 -0
  81. package/src/platform/web.ts +96 -2
  82. package/src/presets/presets.ts +3 -0
  83. package/src/react/frame.tsx +10 -0
  84. package/src/runtime/requests.ts +36 -14
  85. package/src/runtime/types.generated.ts +1 -1
  86. package/src/server/files.ts +19 -3
  87. package/src/server/index.ts +10 -0
  88. package/src/server/nested.ts +86 -0
  89. package/src/server/server.ts +65 -6
  90. package/src/shell/annotate.ts +157 -7
  91. package/src/shell/frame.ts +268 -0
  92. package/src/shell/plan.ts +2 -1
  93. package/src/shell/runtime.ts +49 -14
  94. package/types/runtime/v1/comments.d.ts +8 -4
@@ -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,268 @@
1
+ import { PAGE_SANDBOX_TOKENS } from "../compile/policy.ts";
2
+ import { hostOriginProblem } from "../isolation/served.ts";
3
+
4
+ /**
5
+ * Porthole's shell for a nested page (P111): the whole document at the address the host frames,
6
+ * with no content in it. It frames the page (the same origin's sealed files' address) in a child
7
+ * sandboxed without `allow-same-origin`, so the page's origin is opaque and nothing of the shell's
8
+ * realm is reachable from it: not its DOM, its globals, its storage, or the window the host hears.
9
+ *
10
+ * The shell:
11
+ * - passes every message between the host (its parent, from the host origins) and the page (its
12
+ * child's window, by `event.source` alone: the page's origin is "null") unchanged, and drops any
13
+ * the page sends in the shell's own namespace (`porthole/shell/`), so the shell's words to the
14
+ * host are only its own;
15
+ * - tells the host its own state (`porthole/shell/state`): whether its transient activation is on,
16
+ * and since when, and whether the page's focus is in it. A gesture in the page activates the
17
+ * page and its ancestors, the shell among them, and nothing on the host's page activates the
18
+ * shell (activation goes up, never down), so the shell's activation turning on is a press or
19
+ * key of the person's in this page. It is read at every animation frame, on its window's focus
20
+ * and blur, and before each message of the page's is passed on (a call made in a click's handler
21
+ * arrives after the state that says so). What it can't see: a gesture while its activation is
22
+ * already on (within 5 s of the last one) turns nothing on;
23
+ * - renews the page's sealed files' address before it ends, and gives the page the new one
24
+ * (`porthole/files-renewed`): the page's own loads aren't its origin's (an opaque origin's never
25
+ * are), so only the shell, on that origin, may renew it (P083);
26
+ * - passes its focus to the page (the host's own move into the frame, or a Tab).
27
+ *
28
+ * Plain ES2020, no imports and no build step, like the runtime. `__PLAN__` is its plan.
29
+ */
30
+ export const FRAME_SHELL_RUNTIME = String.raw`(() => {
31
+ "use strict";
32
+ const plan = __PLAN__;
33
+ const PREFIX = "porthole/shell/";
34
+ const own = location.origin;
35
+ let page = null;
36
+ try {
37
+ page = new URL(plan.page);
38
+ } catch (_) {}
39
+ // Only a page of this origin's sealed files: nothing else is ever framed here.
40
+ if (page === null || page.origin !== own || page.pathname.indexOf("/__porthole/f/") !== 0) {
41
+ return;
42
+ }
43
+ // Belt and braces: a plan that would give the page this origin frames nothing.
44
+ if (typeof plan.sandbox !== "string" || /allow-same-origin/i.test(plan.sandbox)) {
45
+ return;
46
+ }
47
+ const root = document.documentElement;
48
+ root.style.height = "100%";
49
+ document.body.style.margin = "0";
50
+ document.body.style.height = "100%";
51
+ document.body.style.background = "transparent";
52
+ const frame = document.createElement("iframe");
53
+ // Scripts only: never allow-same-origin (the page would have this origin, and so this realm).
54
+ frame.setAttribute("sandbox", plan.sandbox);
55
+ frame.setAttribute("allow", "clipboard-read 'none'; clipboard-write 'none'");
56
+ frame.setAttribute("referrerpolicy", "no-referrer");
57
+ frame.title = typeof plan.title === "string" ? plan.title : "Content";
58
+ frame.style.display = "block";
59
+ frame.style.border = "0";
60
+ frame.style.width = "100%";
61
+ frame.style.height = "100%";
62
+ frame.style.background = "transparent";
63
+ frame.src = page.href;
64
+ document.body.append(frame);
65
+
66
+ const framed = window.parent !== window;
67
+ const web = plan.origins.filter((origin) => origin.indexOf("https://") === 0 || origin.indexOf("http://") === 0);
68
+ // To the host: each web host origin (only the parent's is delivered); a desktop app's own scheme
69
+ // is no target a browser takes, so where one is listed and the parent isn't a known web origin,
70
+ // "*" (frame-ancestors holds the parent to the host origins; nothing said here is secret).
71
+ const toHost = (message) => {
72
+ if (!framed) {
73
+ return;
74
+ }
75
+ for (const origin of web) {
76
+ try {
77
+ window.parent.postMessage(message, origin);
78
+ } catch (_) {}
79
+ }
80
+ const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
81
+ if (web.length < plan.origins.length && (parent === null || web.indexOf(parent) === -1)) {
82
+ try {
83
+ window.parent.postMessage(message, "*");
84
+ } catch (_) {}
85
+ }
86
+ };
87
+
88
+ // The shell's own state: its transient activation (and when it turned on), the page's focus.
89
+ // "since" is when the shell saw activation turn on, which a page that holds the thread the shell
90
+ // shares with it (WebKit, Firefox) can push later than the press: so the shell looks every 50 ms
91
+ // and beats as often, and each report says how long it went without a look before (gap). The
92
+ // host takes an activation the shell saw after a stall for uncertain (P111, after its review).
93
+ const activation = navigator.userActivation;
94
+ let active = false;
95
+ let since = 0;
96
+ let focused = false;
97
+ let lookedAt = performance.now();
98
+ let toldAt = 0;
99
+ const tell = (gap) => {
100
+ toldAt = performance.now();
101
+ toHost({
102
+ jsonrpc: "2.0",
103
+ method: PREFIX + "state",
104
+ params: {
105
+ supported: activation !== undefined,
106
+ active,
107
+ ago: active ? Math.max(0, Math.round(performance.now() - since)) : null,
108
+ focused,
109
+ gap: Math.max(0, Math.round(gap)),
110
+ },
111
+ });
112
+ };
113
+ const look = () => {
114
+ const now = performance.now();
115
+ const gap = now - lookedAt;
116
+ lookedAt = now;
117
+ const on = activation !== undefined && activation.isActive === true;
118
+ const inside = document.hasFocus();
119
+ let changed = false;
120
+ if (on !== active) {
121
+ active = on;
122
+ if (on) {
123
+ since = performance.now();
124
+ }
125
+ changed = true;
126
+ }
127
+ if (inside !== focused) {
128
+ focused = inside;
129
+ changed = true;
130
+ }
131
+ if (changed) {
132
+ tell(gap);
133
+ } else if (now - toldAt >= 50) {
134
+ // The heartbeat: the host knows the shell was looking, every 50 ms.
135
+ toldAt = now;
136
+ toHost({ jsonrpc: "2.0", method: PREFIX + "beat", params: { gap: Math.max(0, Math.round(gap)) } });
137
+ }
138
+ };
139
+ const tick = () => {
140
+ look();
141
+ requestAnimationFrame(tick);
142
+ };
143
+ requestAnimationFrame(tick);
144
+ setInterval(look, 50);
145
+ addEventListener("blur", look);
146
+ addEventListener("focus", (event) => {
147
+ // The host's move into the frame (or a Tab) lands here: on to the page.
148
+ if (event.target === window && document.activeElement !== frame) {
149
+ frame.focus();
150
+ }
151
+ look();
152
+ });
153
+ document.addEventListener("visibilitychange", look);
154
+ tell(0);
155
+
156
+ addEventListener("message", (event) => {
157
+ const source = event.source;
158
+ if (source !== null && source === frame.contentWindow) {
159
+ const data = event.data;
160
+ // Never the shell's words in the page's mouth.
161
+ if (data !== null && typeof data === "object" && typeof data.method === "string" && data.method.indexOf(PREFIX) === 0) {
162
+ return;
163
+ }
164
+ // What the shell knows now goes first: a call in a click's handler follows its activation.
165
+ look();
166
+ toHost(data);
167
+ return;
168
+ }
169
+ if (framed && source === window.parent && plan.origins.indexOf(event.origin) !== -1) {
170
+ const child = frame.contentWindow;
171
+ if (child !== null) {
172
+ child.postMessage(event.data, "*");
173
+ }
174
+ }
175
+ });
176
+
177
+ // The page's sealed address, renewed before it ends (P083): the page can't, the shell can.
178
+ if (plan.renew && typeof plan.renew.url === "string" && typeof plan.renew.expires === "number") {
179
+ const prefix = own + "/__porthole/f/";
180
+ let renewUrl = plan.renew.url;
181
+ const renewIn = (expires) => Math.max(30000, expires - Date.now() - 300000);
182
+ const renew = () => {
183
+ fetch(renewUrl, { credentials: "omit", cache: "no-store" })
184
+ .then((answer) => (answer.ok ? answer.json() : null))
185
+ .then((renewed) => {
186
+ if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || renewed.base.indexOf(prefix) !== 0) {
187
+ setTimeout(renew, 60000);
188
+ return;
189
+ }
190
+ renewUrl = renewed.base + "__porthole/renew";
191
+ const child = frame.contentWindow;
192
+ if (child !== null) {
193
+ child.postMessage({ jsonrpc: "2.0", method: "porthole/files-renewed", params: { base: renewed.base } }, "*");
194
+ }
195
+ setTimeout(renew, renewIn(renewed.expires));
196
+ })
197
+ .catch(() => setTimeout(renew, 60000));
198
+ };
199
+ setTimeout(renew, renewIn(plan.renew.expires));
200
+ }
201
+ })();`;
202
+
203
+ export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.ts";
204
+
205
+ export interface FrameShellOptions {
206
+ /** The host origins: the shell takes messages from its parent only from these. */
207
+ readonly origins: readonly string[];
208
+ /** The page's address: absolute, on the shell's own origin, under `/__porthole/f/`. */
209
+ readonly page: string;
210
+ /** The page frame's accessible name. */
211
+ readonly title?: string;
212
+ /** Where the page's sealed address is renewed (`<base>__porthole/renew`), and when it ends. */
213
+ readonly renew?: { readonly url: string; readonly expires: number };
214
+ }
215
+
216
+ /** JSON that is safe inside a `<script>`. */
217
+ const scriptJson = (value: unknown): string =>
218
+ JSON.stringify(value)
219
+ .replace(/</gu, "\\u003c")
220
+ .replace(/\u2028/gu, "\\u2028")
221
+ .replace(/\u2029/gu, "\\u2029");
222
+
223
+ /** The shell's script for `options`: what its document runs, and what its CSP's hash names. */
224
+ export function frameShellScript(options: FrameShellOptions): string {
225
+ for (const origin of options.origins) {
226
+ const problem = hostOriginProblem(origin);
227
+ if (problem !== null) {
228
+ throw new TypeError(`frameShellScript: ${problem}`);
229
+ }
230
+ }
231
+ let page: URL;
232
+ try {
233
+ page = new URL(options.page);
234
+ } catch {
235
+ throw new TypeError("frameShellScript: page is an absolute URL");
236
+ }
237
+ if (!page.pathname.startsWith("/__porthole/f/") || page.hash !== "") {
238
+ throw new TypeError("frameShellScript: page is under /__porthole/f/, with no fragment");
239
+ }
240
+ return FRAME_SHELL_RUNTIME.replace("__PLAN__", () =>
241
+ scriptJson({
242
+ origins: options.origins,
243
+ page: page.href,
244
+ sandbox: PAGE_SANDBOX_TOKENS.join(" "),
245
+ ...(options.title === undefined ? {} : { title: options.title }),
246
+ ...(options.renew === undefined
247
+ ? {}
248
+ : { renew: { url: options.renew.url, expires: options.renew.expires } }),
249
+ }),
250
+ );
251
+ }
252
+
253
+ /** The shell's document around its script: nothing else (its CSP allows that script alone). */
254
+ export function frameShellDocument(script: string): string {
255
+ return `<!doctype html>
256
+ <html lang="en">
257
+ <head>
258
+ <meta charset="utf-8">
259
+ <meta name="color-scheme" content="light dark">
260
+ <meta name="referrer" content="no-referrer">
261
+ <title>Porthole</title>
262
+ </head>
263
+ <body>
264
+ <script>${script}</script>
265
+ </body>
266
+ </html>
267
+ `;
268
+ }
package/src/shell/plan.ts CHANGED
@@ -97,7 +97,8 @@ export function shellPlan(config: PortholeConfig): ShellPlan | null {
97
97
  themeVariables: Object.keys(config.theme.variables),
98
98
  themeEvent: config.theme.event,
99
99
  themeDocuments: config.theme.documents ?? "declared",
100
- storage: config.isolation === "opaque" ? "memory" : "native",
100
+ // An opaque origin has no storage: an opaque frame's, and a nested page's (P111).
101
+ storage: config.isolation === "opaque" || config.nested === true ? "memory" : "native",
101
102
  maxErrorReports: config.limits.maxErrorReports,
102
103
  maxPromptChars: config.limits.maxPromptChars,
103
104
  maxCopyChars: MAX_COPY_CHARS,
@@ -68,6 +68,9 @@ export const SHELL_RUNTIME = String.raw`(() => {
68
68
  }
69
69
  };
70
70
 
71
+ // Whether the page touched storage, told to the host once (P111): yes, never what it keeps.
72
+ let storageTouched = false;
73
+ let tellStorage = () => {};
71
74
  if (plan.storage === "memory") {
72
75
  // An opaque origin has no storage: a map stands in, for as long as the frame lives.
73
76
  const store = () => {
@@ -84,8 +87,18 @@ export const SHELL_RUNTIME = String.raw`(() => {
84
87
  };
85
88
  };
86
89
  for (const name of ["localStorage", "sessionStorage"]) {
90
+ const kept = store();
87
91
  try {
88
- Object.defineProperty(window, name, { configurable: true, value: store() });
92
+ Object.defineProperty(window, name, {
93
+ configurable: true,
94
+ get() {
95
+ if (!storageTouched) {
96
+ storageTouched = true;
97
+ tellStorage();
98
+ }
99
+ return kept;
100
+ },
101
+ });
89
102
  } catch (_) {}
90
103
  }
91
104
  }
@@ -115,6 +128,8 @@ export const SHELL_RUNTIME = String.raw`(() => {
115
128
  // takes the next load for that page, not for content that left). Anything else stays stopped:
116
129
  // another path of the origin, a file that isn't a page, another origin.
117
130
  let navigating = (_url) => {};
131
+ // A nested page's files' address renewed by its shell (P111), which the shell's message gives.
132
+ let adoptFiles = (_base) => false;
118
133
  let filesBase = plan.files && typeof plan.files.base === "string" ? plan.files.base : null;
119
134
  // Every address the page's files had (P083: a sealed one is renewed): what reports say as "./".
120
135
  const filesBases = filesBase === null ? [] : [filesBase];
@@ -880,6 +895,11 @@ export const SHELL_RUNTIME = String.raw`(() => {
880
895
  const filesSet = plan.files && plan.files.set && typeof plan.files.set === "object" ? { id: String(plan.files.set.id), version: String(plan.files.set.version) } : null;
881
896
  const notice = (url, more) => post({ method: "porthole/navigating", params: Object.assign({ url: ownAddresses(url).slice(0, 4096) }, filesSet === null ? {} : { set: filesSet }, more) });
882
897
  navigating = (url) => notice(url, {});
898
+ // The page used storage (P111): said once, as soon as the shell can speak; never keys or values.
899
+ tellStorage = () => post({ method: "porthole/storage-used", params: {} });
900
+ if (storageTouched) {
901
+ tellStorage();
902
+ }
883
903
  if (arrived) {
884
904
  notice(location.href, { arrived: true });
885
905
  }
@@ -887,28 +907,38 @@ export const SHELL_RUNTIME = String.raw`(() => {
887
907
  // it ends, the page moved to the new one in place (the same page, the same history entry). Its
888
908
  // modules keep the address they loaded from; the server serves their own loads till the session
889
909
  // ends.
910
+ const replace = History.prototype.replaceState;
911
+ // The files' origin, read from the address itself: a nested page's own origin is opaque (P111).
912
+ const filesOrigin = filesBase === null ? null : new NativeURL(filesBase).origin;
913
+ // A renewed sealed address (P083): one segment under the same origin's sealed prefix, checked
914
+ // through the platform's own functions (content may have replaced a prototype's, and the base
915
+ // decides where this page may go, ownPage); the page moves there in place.
916
+ const adopt = (base) => {
917
+ const prefix = filesOrigin + "/__porthole/f/";
918
+ if (filesBase === null || typeof base !== "string" || callOf(indexIn, base, [prefix]) !== 0 || callOf(indexIn, callOf(sliceOf, base, [prefix.length, -1]), ["/"]) !== -1 || callOf(sliceOf, base, [-1]) !== "/") {
919
+ return false;
920
+ }
921
+ const here = location.href;
922
+ if (here.indexOf(filesBase) === 0) {
923
+ try {
924
+ applyOf(replace, history, [history.state, "", base + here.slice(filesBase.length)]);
925
+ } catch (_) {}
926
+ }
927
+ filesBase = base;
928
+ filesBases.push(base);
929
+ return true;
930
+ };
931
+ adoptFiles = adopt;
890
932
  if (filesBase !== null && typeof plan.files.expires === "number") {
891
933
  const nativeFetch = window.fetch.bind(window);
892
- const replace = History.prototype.replaceState;
893
934
  const renewIn = (expires) => Math.max(30000, expires - Date.now() - 300000);
894
935
  const renew = () => {
895
936
  nativeFetch(filesBase + "__porthole/renew", { credentials: "omit", cache: "no-store" })
896
937
  .then((answer) => (answer.ok ? answer.json() : null))
897
938
  .then((renewed) => {
898
- // Checked through the platform's own functions: content may have replaced a prototype's,
899
- // and the base decides where this page may go (ownPage).
900
- const prefix = location.origin + "/__porthole/f/";
901
- if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || callOf(indexIn, renewed.base, [prefix]) !== 0 || callOf(indexIn, callOf(sliceOf, renewed.base, [prefix.length, -1]), ["/"]) !== -1 || callOf(sliceOf, renewed.base, [-1]) !== "/") {
939
+ if (!renewed || typeof renewed.expires !== "number" || !adopt(renewed.base)) {
902
940
  return;
903
941
  }
904
- const here = location.href;
905
- if (here.indexOf(filesBase) === 0) {
906
- try {
907
- applyOf(replace, history, [history.state, "", renewed.base + here.slice(filesBase.length)]);
908
- } catch (_) {}
909
- }
910
- filesBase = renewed.base;
911
- filesBases.push(renewed.base);
912
942
  setTimeout(renew, renewIn(renewed.expires));
913
943
  })
914
944
  .catch(() => setTimeout(renew, 60000));
@@ -1465,6 +1495,11 @@ export const SHELL_RUNTIME = String.raw`(() => {
1465
1495
  case "ui/notifications/tool-input":
1466
1496
  void render(params.arguments);
1467
1497
  break;
1498
+ case "porthole/files-renewed":
1499
+ // From the page's parent only (the listener's check): a nested page's shell renewed its
1500
+ // files' sealed address, which this page can't (its loads aren't its origin's own, P111).
1501
+ adoptFiles(params.base);
1502
+ break;
1468
1503
  case "ui/notifications/host-context-changed":
1469
1504
  applyTheme(params);
1470
1505
  break;
@@ -4,9 +4,9 @@
4
4
  interface PortholeCommentAnchor {
5
5
  /** A stable name the page chose: "slide-3", "refs/a.md#L12" (at most 256 characters). */
6
6
  readonly name: string;
7
- /** What the app shows for it (at most 200). */
7
+ /** What the app shows for it (at most 200; what a person can't see is taken out). */
8
8
  readonly label?: string;
9
- /** The text the comment is about (at most 2,000). */
9
+ /** The text the comment is about (at most 2,000; what a person can't see is taken out). */
10
10
  readonly quote?: string;
11
11
  }
12
12
 
@@ -15,7 +15,10 @@ interface PortholeCommentOptions {
15
15
  /**
16
16
  * Text the composer starts with (at most 2,000 characters): a draft the person edits, posts
17
17
  * or discards in the app. It is never posted without them. Visible text only: new lines and
18
- * tabs are fine; a draft with zero-width, bidi or tag characters is refused.
18
+ * tabs are fine (at most 32 blanks in a row, two blank lines in a row), and so are U+200C and
19
+ * U+200D between two letters or marks (Persian, the Indic scripts); a draft with zero-width
20
+ * characters, a joiner anywhere else (an emoji joined with U+200D too; ❤️ is fine), bidi or tag
21
+ * characters, or a line or paragraph separator (U+2028, U+2029) is refused.
19
22
  */
20
23
  readonly draft?: string;
21
24
  }
@@ -24,7 +27,8 @@ interface PortholeComments {
24
27
  /**
25
28
  * Opens the app's comment composer at the anchor (a name alone is { name }), starting with
26
29
  * `options.draft` if given. The person writes and posts it in the app. Resolves true if the
27
- * composer opened. Write-only: a page never reads comments. Call it from a click. Level: view.
30
+ * composer opened, false if it didn't (the app may refuse while the person is writing).
31
+ * Write-only: a page never reads comments. Call it from a click in the page. Level: view.
28
32
  */
29
33
  open(anchor: PortholeCommentAnchor | string, options?: PortholeCommentOptions): Promise<boolean>;
30
34
  }