@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
@@ -47,11 +47,25 @@ export const SHELL_RUNTIME = String.raw`(() => {
47
47
  // script the shell runs for the content carries it.
48
48
  const nonce = document.currentScript && document.currentScript.nonce ? document.currentScript.nonce : "";
49
49
  const declared = (name) => Object.prototype.hasOwnProperty.call(plan.capabilities, name);
50
- // Fixed in place: content can neither restore what is removed nor replace what is wrapped.
50
+ // Fixed in place: content can neither restore what is removed nor replace what is wrapped. A
51
+ // property something fixed before the shell ran (an extension, an engine's own) can't be: each
52
+ // such name goes on the shell's own script element (data-porthole-unfixed, for a test or a
53
+ // person to see) and, once the shell can speak, to the host as an error report.
54
+ const shellScript = document.currentScript;
55
+ const unfixed = [];
56
+ let tellUnfixed = (_name) => {};
51
57
  const lock = (target, name, value) => {
52
58
  try {
53
59
  Object.defineProperty(target, name, { configurable: false, writable: false, value });
54
- } catch (_) {}
60
+ } catch (_) {
61
+ unfixed.push(String(name));
62
+ try {
63
+ if (shellScript) {
64
+ shellScript.setAttribute("data-porthole-unfixed", unfixed.join(" "));
65
+ }
66
+ } catch (_) {}
67
+ tellUnfixed(String(name));
68
+ }
55
69
  };
56
70
 
57
71
  if (plan.storage === "memory") {
@@ -113,13 +127,28 @@ export const SHELL_RUNTIME = String.raw`(() => {
113
127
  }
114
128
  return out.replace(SEALED, "./");
115
129
  };
130
+ // The platform's own string and URL functions, kept now (P099): the rules that decide where this
131
+ // document may go must read an address as the platform does, whatever content later puts on
132
+ // String.prototype, URL or Reflect.
133
+ const callOf = Reflect.apply;
134
+ const NativeString = String;
135
+ const NativeURL = URL;
136
+ const urlHref = Object.getOwnPropertyDescriptor(URL.prototype, "href").get;
137
+ const indexIn = String.prototype.indexOf;
138
+ const lastIndexIn = String.prototype.lastIndexOf;
139
+ const sliceOf = String.prototype.slice;
140
+ const lowerOf = String.prototype.toLowerCase;
141
+ const before = (text, mark) => {
142
+ const at = callOf(indexIn, text, [mark]);
143
+ return at < 0 ? text : callOf(sliceOf, text, [0, at]);
144
+ };
116
145
  const ownPage = (url) => {
117
- if (filesBase === null || typeof url !== "string" || url.indexOf(filesBase) !== 0) {
146
+ if (filesBase === null || typeof url !== "string" || callOf(indexIn, url, [filesBase]) !== 0) {
118
147
  return false;
119
148
  }
120
- const path = url.slice(filesBase.length).split("#")[0].split("?")[0];
121
- const last = path.slice(path.lastIndexOf("/") + 1);
122
- return last === "" || last.indexOf(".") < 0 || /\.html?$/i.test(last);
149
+ const path = before(before(callOf(sliceOf, url, [filesBase.length]), "#"), "?");
150
+ const last = callOf(lowerOf, callOf(sliceOf, path, [callOf(lastIndexIn, path, ["/"]) + 1]), []);
151
+ return last === "" || callOf(indexIn, last, ["."]) < 0 || callOf(sliceOf, last, [-5]) === ".html" || callOf(sliceOf, last, [-4]) === ".htm";
123
152
  };
124
153
  const navigationApi = window.navigation;
125
154
  const getterOf = (proto, name) => {
@@ -134,7 +163,13 @@ export const SHELL_RUNTIME = String.raw`(() => {
134
163
  const urlOf = getterOf(destinationProto, "url");
135
164
  const preventNavigation = Event.prototype.preventDefault;
136
165
  const applyOf = Reflect.apply;
166
+ // A page of a set that a navigation opened (not its ticket's answer) says so as it arrives
167
+ // (P098), below, once the shell can speak: the notice its last page sent as it left can reach
168
+ // the host after this page's load, or never (Chromium forwards a cross-process message from a
169
+ // task of the sending document's, which a navigation that commits first drops).
170
+ let arrived = false;
137
171
  if (navigationApi && typeof navigationApi.addEventListener === "function" && destinationOf !== null && sameDocumentOf !== null && navigationTypeOf !== null) {
172
+ arrived = filesBase !== null && typeof plan.files.address !== "string";
138
173
  navigationApi.addEventListener("navigate", (event) => {
139
174
  const destination = applyOf(destinationOf, event, []);
140
175
  if (!applyOf(sameDocumentOf, destination, []) && applyOf(navigationTypeOf, event, []) !== "reload") {
@@ -149,6 +184,257 @@ export const SHELL_RUNTIME = String.raw`(() => {
149
184
  }, true);
150
185
  }
151
186
 
187
+ // The calls that start a navigation and can be asked first ask the guard's rule before they
188
+ // start one (P099): WebKit sends navigation.navigate()'s request though the navigate event
189
+ // cancels it (measured on a tab: an outside site heard it). Within the document (a fragment, the
190
+ // same address) or another page of its own set (P084) goes on, as the guard lets it; anything
191
+ // else is stopped here, before any request, and the host told, as the guard does.
192
+ // The address is read once (String() and resolved here), and the call is given that address,
193
+ // absolute: what was checked is what goes, whatever an object's toString says the next time.
194
+ const mayNavigate = (url) => {
195
+ const text = NativeString(url);
196
+ let target = "";
197
+ try {
198
+ target = callOf(urlHref, new NativeURL(text, document.baseURI), []);
199
+ } catch (_) {
200
+ throw new DOMException("Not a URL", "SyntaxError");
201
+ }
202
+ return { go: before(target, "#") === before(location.href, "#") || ownPage(target), target };
203
+ };
204
+ const navigationProto = typeof Navigation === "function" ? Navigation.prototype : null;
205
+ if (navigationProto !== null && typeof navigationProto.navigate === "function") {
206
+ const navigateOriginal = navigationProto.navigate;
207
+ lock(navigationProto, "navigate", function (url, options) {
208
+ const asked = mayNavigate(url);
209
+ if (asked.go) {
210
+ return applyOf(navigateOriginal, this, [asked.target, options]);
211
+ }
212
+ navigationBlocked(asked.target);
213
+ const aborted = Promise.reject(new DOMException("Navigation was aborted", "AbortError"));
214
+ aborted.catch(() => {});
215
+ return { committed: aborted, finished: aborted };
216
+ });
217
+ }
218
+
219
+ // A page on a tab of its own opens no window (P099): a window would carry what a visitor typed
220
+ // out in its address. Its document's CSP sandbox is the wall (no allow-popups); this is the
221
+ // second, for an edge that drops the header. In a frame the frame's sandbox answers already
222
+ // (null; a throw on Firefox). "_self" stays a navigation of this document, where the guard's
223
+ // rule lets one (mayNavigate, above); every other target opens nothing. Nor a picture-in-picture document (Chromium,
224
+ // Firefox): a window of this origin in a fresh realm, where nothing above ever ran (only a
225
+ // top-level page may open one, so a frame can't).
226
+ if (window.top === window) {
227
+ const openWindow = window.open;
228
+ lock(window, "open", function (url, target, features) {
229
+ if (typeof target !== "string" || target.trim().toLowerCase() !== "_self") {
230
+ return null;
231
+ }
232
+ const asked = mayNavigate(url);
233
+ if (!asked.go) {
234
+ navigationBlocked(asked.target);
235
+ return null;
236
+ }
237
+ return applyOf(openWindow, window, [asked.target, "_self", features]);
238
+ });
239
+ if (typeof DocumentPictureInPicture === "function") {
240
+ lock(DocumentPictureInPicture.prototype, "requestWindow", () => Promise.reject(new DOMException("A page here opens no other window", "NotAllowedError")));
241
+ }
242
+ }
243
+ // A link on a tab (P099) is followed by the shell, never by the browser: WebKit sends a link's
244
+ // request though the navigate event cancels it (measured), and the browser follows a link with
245
+ // the href and target it has once every listener ran, which content may change after any check.
246
+ // So the first click listener there is (the shell's, on window, capturing) takes each plain click
247
+ // on a link (found through the composed path, shadow roots included) from the browser: it
248
+ // cancels it, reads the link once, and, after every listener ran and unless content cancelled
249
+ // the click itself, follows what it read with a link of its own, detached (no listener of
250
+ // content's sees its click), where the guard's rule lets it go: within the document (a
251
+ // fragment), another page of the set (P084), a download of the page's own (which the sandbox
252
+ // decides). A link to a new window does nothing (the sandbox refuses it anyway); a modified or
253
+ // middle click is left to the browser (a window or a download: the sandbox refuses both).
254
+ let linksTaken = false;
255
+ if (window.top === window) {
256
+ linksTaken = true;
257
+ const pathOf = Event.prototype.composedPath;
258
+ const matchesOf = Element.prototype.matches;
259
+ const attributeOf = Element.prototype.getAttribute;
260
+ const attributeNSOf = Element.prototype.getAttributeNS;
261
+ const hasAttributeOf = Element.prototype.hasAttribute;
262
+ const setAttributeOf = Element.prototype.setAttribute;
263
+ const makeElement = Document.prototype.createElement;
264
+ const clickOf = HTMLElement.prototype.click;
265
+ const later = window.setTimeout;
266
+ const addTo = WeakSet.prototype.add;
267
+ const hasIn = WeakSet.prototype.has;
268
+ const modifierGetters = [getterOf(MouseEvent.prototype, "ctrlKey"), getterOf(MouseEvent.prototype, "metaKey"), getterOf(MouseEvent.prototype, "shiftKey"), getterOf(MouseEvent.prototype, "altKey")];
269
+ const buttonOf = getterOf(MouseEvent.prototype, "button");
270
+ // A click content cancelled itself, through preventDefault or returnValue (the shell's own
271
+ // cancels call the platform's function, kept above, and aren't counted).
272
+ const cancelledByContent = new WeakSet();
273
+ lock(Event.prototype, "preventDefault", function () {
274
+ callOf(addTo, cancelledByContent, [this]);
275
+ return callOf(preventNavigation, this, []);
276
+ });
277
+ const returnValue = Object.getOwnPropertyDescriptor(Event.prototype, "returnValue");
278
+ if (returnValue && returnValue.get && returnValue.set) {
279
+ try {
280
+ Object.defineProperty(Event.prototype, "returnValue", {
281
+ configurable: false,
282
+ enumerable: returnValue.enumerable,
283
+ get() {
284
+ return callOf(returnValue.get, this, []);
285
+ },
286
+ set(value) {
287
+ if (!value) {
288
+ callOf(addTo, cancelledByContent, [this]);
289
+ }
290
+ callOf(returnValue.set, this, [value]);
291
+ },
292
+ });
293
+ } catch (_) {
294
+ unfixed.push("returnValue");
295
+ }
296
+ }
297
+ const follow = (address, download) => {
298
+ const anchor = callOf(makeElement, document, ["a"]);
299
+ callOf(setAttributeOf, anchor, ["href", address]);
300
+ if (download !== null) {
301
+ callOf(setAttributeOf, anchor, ["download", download]);
302
+ }
303
+ callOf(clickOf, anchor, []);
304
+ };
305
+ window.addEventListener("click", (event) => {
306
+ let link = null;
307
+ try {
308
+ const path = callOf(pathOf, event, []);
309
+ for (let i = 0; i < path.length && link === null; i += 1) {
310
+ try {
311
+ if (callOf(matchesOf, path[i], ["a, area"])) {
312
+ link = path[i];
313
+ }
314
+ } catch (_) {}
315
+ }
316
+ } catch (_) {}
317
+ if (link === null) {
318
+ return;
319
+ }
320
+ let plain = true;
321
+ try {
322
+ plain = callOf(buttonOf, event, []) === 0;
323
+ for (let i = 0; i < modifierGetters.length; i += 1) {
324
+ if (callOf(modifierGetters[i], event, [])) {
325
+ plain = false;
326
+ }
327
+ }
328
+ } catch (_) {}
329
+ if (!plain) {
330
+ return;
331
+ }
332
+ callOf(preventNavigation, event, []);
333
+ // Read once, now: what is followed is what was read.
334
+ const named = callOf(lowerOf, NativeString(callOf(attributeOf, link, ["target"]) || ""), []);
335
+ const self = named === "" || named === "_self" || named === "_top" || named === "_parent";
336
+ const href = callOf(attributeOf, link, ["href"]) ?? callOf(attributeNSOf, link, ["http://www.w3.org/1999/xlink", "href"]);
337
+ const download = callOf(hasAttributeOf, link, ["download"]) ? NativeString(callOf(attributeOf, link, ["download"]) || "") : null;
338
+ callOf(later, window, [
339
+ () => {
340
+ if (callOf(hasIn, cancelledByContent, [event]) || href === null) {
341
+ return;
342
+ }
343
+ let asked = null;
344
+ try {
345
+ asked = mayNavigate(href);
346
+ } catch (_) {
347
+ return;
348
+ }
349
+ const own = callOf(indexIn, asked.target, [location.origin + "/"]) === 0 || callOf(indexIn, asked.target, ["blob:" + location.origin + "/"]) === 0 || callOf(indexIn, asked.target, ["data:"]) === 0;
350
+ if (download !== null && own) {
351
+ follow(asked.target, download);
352
+ } else if (self && asked.go) {
353
+ follow(asked.target, null);
354
+ } else if (self) {
355
+ navigationBlocked(asked.target);
356
+ }
357
+ },
358
+ 0,
359
+ ]);
360
+ }, true);
361
+ }
362
+
363
+ // Nor, on a tab, the camera, the microphone, the screen, location, full screen, passkeys, the
364
+ // share sheet or payments (P099): a frame has none of them (its allow grants none), a tab has
365
+ // no allow, and its Permissions-Policy header, the wall on Chromium, isn't applied to them by
366
+ // WebKit and Firefox (measured). Each refuses as a denial does, at once, with no prompt.
367
+ if (window.top === window) {
368
+ const deny = () => Promise.reject(new DOMException("Not available here", "NotAllowedError"));
369
+ if (typeof MediaDevices === "function") {
370
+ for (const name of ["getUserMedia", "getDisplayMedia", "selectAudioOutput"]) {
371
+ if (typeof MediaDevices.prototype[name] === "function") {
372
+ lock(MediaDevices.prototype, name, deny);
373
+ }
374
+ }
375
+ }
376
+ for (const name of ["getUserMedia", "webkitGetUserMedia", "mozGetUserMedia"]) {
377
+ if (typeof Navigator.prototype[name] === "function") {
378
+ lock(Navigator.prototype, name, function (_constraints, _success, failure) {
379
+ if (typeof failure === "function") {
380
+ setTimeout(() => failure(new DOMException("Not available here", "NotAllowedError")), 0);
381
+ }
382
+ });
383
+ }
384
+ }
385
+ if (typeof Geolocation === "function") {
386
+ const deniedPosition = { code: 1, message: "Not available here", PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 };
387
+ const denyPosition = function (_success, failure) {
388
+ if (typeof failure === "function") {
389
+ setTimeout(() => failure(deniedPosition), 0);
390
+ }
391
+ return 0;
392
+ };
393
+ lock(Geolocation.prototype, "getCurrentPosition", denyPosition);
394
+ lock(Geolocation.prototype, "watchPosition", denyPosition);
395
+ }
396
+ lock(Element.prototype, "requestFullscreen", () => Promise.reject(new TypeError("Full screen isn't available here")));
397
+ for (const name of ["webkitRequestFullscreen", "webkitRequestFullScreen", "mozRequestFullScreen"]) {
398
+ if (typeof Element.prototype[name] === "function") {
399
+ lock(Element.prototype, name, () => undefined);
400
+ }
401
+ }
402
+ // A video's own full screen (WebKit), passkeys and saved passwords, the share sheet, and
403
+ // payments (whose method's address the browser fetches outside the CSP; WebKit's Apple Pay
404
+ // sheet): each a prompt or a way out a frame never has.
405
+ const notHere = () => {
406
+ throw new DOMException("Not available here", "NotAllowedError");
407
+ };
408
+ if (typeof HTMLVideoElement === "function") {
409
+ for (const name of ["webkitEnterFullscreen", "webkitEnterFullScreen"]) {
410
+ if (typeof HTMLVideoElement.prototype[name] === "function") {
411
+ lock(HTMLVideoElement.prototype, name, notHere);
412
+ }
413
+ }
414
+ }
415
+ if (typeof CredentialsContainer === "function") {
416
+ for (const name of ["create", "get", "store"]) {
417
+ if (typeof CredentialsContainer.prototype[name] === "function") {
418
+ lock(CredentialsContainer.prototype, name, deny);
419
+ }
420
+ }
421
+ }
422
+ if (typeof Navigator.prototype.share === "function") {
423
+ lock(Navigator.prototype, "share", deny);
424
+ lock(Navigator.prototype, "canShare", () => false);
425
+ }
426
+ if (typeof PaymentRequest === "function") {
427
+ lock(window, "PaymentRequest", function () {
428
+ throw new DOMException("Payments aren't available here", "SecurityError");
429
+ });
430
+ }
431
+ if (typeof ApplePaySession === "function") {
432
+ lock(window, "ApplePaySession", function () {
433
+ throw new DOMException("Payments aren't available here", "SecurityError");
434
+ });
435
+ }
436
+ }
437
+
152
438
  // No nested frames (each would be a fresh realm with WebRTC intact), no resource hints and no
153
439
  // refreshes (they reach the network outside the CSP's fetch directives). Removed as they are
154
440
  // added: a mutation observer's microtask runs before a child frame's document loads.
@@ -195,13 +481,61 @@ export const SHELL_RUNTIME = String.raw`(() => {
195
481
  };
196
482
  guardRoot(document);
197
483
 
198
- // Every shadow root content makes, open or closed, is guarded as it is made.
484
+ // Every shadow root content makes, open or closed, is guarded as it is made. On a tab (P099) a
485
+ // closed one is made open, to the platform, and closed to content (its host's shadowRoot is
486
+ // null, its mode "closed"): a click on a link inside it must show the link to the shell's first
487
+ // listener through the event's composed path, which a closed tree hides.
199
488
  const attachShadow = Element.prototype.attachShadow;
489
+ const shownOpen = new WeakSet();
490
+ const addShown = WeakSet.prototype.add;
491
+ const shadowInit = (init) => {
492
+ if (window.top !== window || init === null || typeof init !== "object" || init.mode !== "closed") {
493
+ return { init, closed: false };
494
+ }
495
+ const copy = { mode: "open" };
496
+ for (const key of ["delegatesFocus", "slotAssignment", "clonable", "serializable", "customElementRegistry", "referenceTarget"]) {
497
+ if (init[key] !== undefined) {
498
+ copy[key] = init[key];
499
+ }
500
+ }
501
+ return { init: copy, closed: true };
502
+ };
200
503
  lock(Element.prototype, "attachShadow", function (init) {
504
+ const asked = shadowInit(init);
505
+ init = asked.init;
201
506
  const root = attachShadow.call(this, init);
202
507
  guardRoot(root);
508
+ if (asked.closed) {
509
+ callOf(addShown, shownOpen, [root]);
510
+ }
203
511
  return root;
204
512
  });
513
+ if (window.top === window) {
514
+ const shadowRootOf = getterOf(Element.prototype, "shadowRoot");
515
+ const modeOf = typeof ShadowRoot === "function" ? getterOf(ShadowRoot.prototype, "mode") : null;
516
+ const shown = WeakSet.prototype.has;
517
+ try {
518
+ if (shadowRootOf !== null) {
519
+ Object.defineProperty(Element.prototype, "shadowRoot", {
520
+ configurable: false,
521
+ get() {
522
+ const root = callOf(shadowRootOf, this, []);
523
+ return root !== null && callOf(shown, shownOpen, [root]) ? null : root;
524
+ },
525
+ });
526
+ }
527
+ if (modeOf !== null) {
528
+ Object.defineProperty(ShadowRoot.prototype, "mode", {
529
+ configurable: false,
530
+ get() {
531
+ return callOf(shown, shownOpen, [this]) ? "closed" : callOf(modeOf, this, []);
532
+ },
533
+ });
534
+ }
535
+ } catch (_) {
536
+ unfixed.push("shadowRoot");
537
+ }
538
+ }
205
539
 
206
540
  // The parser builds declarative shadow roots (template shadowrootmode) without attachShadow, and
207
541
  // a closed one is out of the guard's reach. Fragment parsing doesn't build them, so the entry
@@ -359,7 +693,7 @@ export const SHELL_RUNTIME = String.raw`(() => {
359
693
  // the person makes (their keys, their menu) copies their selection as the browser makes it: no
360
694
  // copy or cut listener of the content's runs, so none can swap what goes on the clipboard.
361
695
  const noClipboard = function () {
362
- return Promise.reject(new DOMException("Content can't use the clipboard here" + (declared("copyText") ? ": call copyText(text) from a click" : ""), "NotAllowedError"));
696
+ return Promise.reject(new DOMException("Content can't use the clipboard here" + (declared("copyText") ? (plan.runtime ? ': call (await porthole.use("clipboard")).copy(text) from a click' : ": call copyText(text) from a click") : ""), "NotAllowedError"));
363
697
  };
364
698
  if (typeof Clipboard === "function") {
365
699
  for (const name of ["write", "writeText", "read", "readText"]) {
@@ -540,10 +874,15 @@ export const SHELL_RUNTIME = String.raw`(() => {
540
874
  reported += 1;
541
875
  post({ method: "porthole/navigation-blocked", params: { url: ownAddresses(url).slice(0, 4096) } });
542
876
  };
543
- // Another page of the set opening in the frame (P084): the host takes the next load for it.
544
- navigating = (url) => {
545
- post({ method: "porthole/navigating", params: { url: ownAddresses(url).slice(0, 4096) } });
546
- };
877
+ // Another page of the set opening in the frame (P084): the host takes the next load for it. Each
878
+ // notice names the version the files are (P098): the host takes one only for the version it
879
+ // mounted.
880
+ 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
+ const notice = (url, more) => post({ method: "porthole/navigating", params: Object.assign({ url: ownAddresses(url).slice(0, 4096) }, filesSet === null ? {} : { set: filesSet }, more) });
882
+ navigating = (url) => notice(url, {});
883
+ if (arrived) {
884
+ notice(location.href, { arrived: true });
885
+ }
547
886
  // A sealed files' address opens the page's files on its own for a while (P083): renewed before
548
887
  // it ends, the page moved to the new one in place (the same page, the same history entry). Its
549
888
  // modules keep the address they loaded from; the server serves their own loads till the session
@@ -556,7 +895,10 @@ export const SHELL_RUNTIME = String.raw`(() => {
556
895
  nativeFetch(filesBase + "__porthole/renew", { credentials: "omit", cache: "no-store" })
557
896
  .then((answer) => (answer.ok ? answer.json() : null))
558
897
  .then((renewed) => {
559
- if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || renewed.base.indexOf(location.origin + "/__porthole/f/") !== 0 || renewed.base.slice(-1) !== "/") {
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]) !== "/") {
560
902
  return;
561
903
  }
562
904
  const here = location.href;
@@ -574,6 +916,10 @@ export const SHELL_RUNTIME = String.raw`(() => {
574
916
  setTimeout(renew, renewIn(plan.files.expires));
575
917
  }
576
918
 
919
+ // What the shell couldn't fix in place (above), told to the host now that it can be, and after.
920
+ tellUnfixed = (name) => report("Porthole couldn't fix " + name + " in place: a defense here may be missing");
921
+ unfixed.forEach((name) => tellUnfixed(name));
922
+
577
923
  // A parsed tree's scripts are held (each replaced by a numbered marker) and run later, in order,
578
924
  // as the page's parser would run them: each made again, live, in its marker's place, and each
579
925
  // external one loaded before the next runs. Markers are found in the live document by number, so
@@ -799,41 +1145,6 @@ export const SHELL_RUNTIME = String.raw`(() => {
799
1145
  return !(capability && capability.userActivation) || !activation || activation.isActive;
800
1146
  };
801
1147
  const refuse = (message) => Promise.reject(new Error(message));
802
- if (declared("sendPrompt")) {
803
- lock(window, "sendPrompt", (text) => {
804
- if (!gestured("sendPrompt")) {
805
- return refuse("sendPrompt needs a click: call it from a button's handler");
806
- }
807
- const words = String(text);
808
- if (words.trim() === "" || words.length > plan.maxPromptChars) {
809
- return refuse("sendPrompt takes 1 to " + plan.maxPromptChars + " characters");
810
- }
811
- return request("ui/message", { role: "user", content: [{ type: "text", text: words }] }).then(
812
- (result) => !(result && result.isError),
813
- );
814
- });
815
- }
816
- if (declared("copyText")) {
817
- lock(window, "copyText", (text) => {
818
- if (!gestured("copyText")) {
819
- return refuse("copyText needs a click: call it from a button's handler");
820
- }
821
- const words = String(text);
822
- if (words === "" || words.length > plan.maxCopyChars) {
823
- return refuse("copyText takes 1 to " + plan.maxCopyChars + " characters");
824
- }
825
- return request("porthole/copy-text", { text: words }).then((result) => !(result && result.isError));
826
- });
827
- }
828
- if (declared("openLink")) {
829
- lock(window, "openLink", (url) => {
830
- if (!gestured("openLink")) {
831
- return refuse("openLink needs a click: call it from a link's or button's handler");
832
- }
833
- return request("ui/open-link", { url: String(url) }).then((result) => !(result && result.isError));
834
- });
835
- }
836
-
837
1148
  // Data (P079): readData reads a resource the host names, subscribeData follows one, through
838
1149
  // MCP's resources/* requests, which the host gates (the viewer's consent, a rate). A value is the
839
1150
  // first content's: JSON parsed when it says it is JSON, else its text.
@@ -857,9 +1168,10 @@ export const SHELL_RUNTIME = String.raw`(() => {
857
1168
  const later = (error) => setTimeout(() => {
858
1169
  throw error;
859
1170
  });
860
- if (declared("readData")) {
861
- lock(window, "readData", (uri) => request("resources/read", { uri: String(uri) }).then(valueOf));
862
- }
1171
+ // Reads a resource (readData, the runtime's data.read).
1172
+ const readValue = (uri) => request("resources/read", { uri: String(uri) }).then(valueOf);
1173
+ // Follows one (subscribeData, the runtime's data.subscribe), where the config declares it.
1174
+ let follow = null;
863
1175
  if (declared("subscribeData")) {
864
1176
  // One subscription per URI, however many follow it; a read at a time, one more if it changed
865
1177
  // meanwhile; a late follower gets the last value at once.
@@ -913,7 +1225,7 @@ export const SHELL_RUNTIME = String.raw`(() => {
913
1225
  refresh(entry);
914
1226
  }
915
1227
  };
916
- lock(window, "subscribeData", (uri, onData, onError) => {
1228
+ follow = (uri, onData, onError) => {
917
1229
  if (typeof onData !== "function") {
918
1230
  throw new TypeError("subscribeData(uri, onData, onError): onData must be a function");
919
1231
  }
@@ -957,9 +1269,19 @@ export const SHELL_RUNTIME = String.raw`(() => {
957
1269
  request("resources/unsubscribe", { uri: key }).catch(() => {});
958
1270
  }
959
1271
  };
960
- });
1272
+ };
961
1273
  }
962
1274
 
1275
+
1276
+ // The capability runtime's hooks (P085): the host's offer from the handshake (null: no host
1277
+ // answered), and a watch's updates. The runtime, where the config has one, takes them.
1278
+ let runtimeOffer = (_offer) => {};
1279
+ let runtimeEvent = (_params) => {};
1280
+
1281
+ __LEGACY__
1282
+
1283
+ __RUNTIME__
1284
+
963
1285
  window.addEventListener("error", (event) => {
964
1286
  const error = event.error;
965
1287
  const where = event.lineno ? " (line " + event.lineno + ")" : "";
@@ -986,10 +1308,11 @@ export const SHELL_RUNTIME = String.raw`(() => {
986
1308
  return;
987
1309
  }
988
1310
  const href = link.getAttribute("href") || link.getAttributeNS("http://www.w3.org/1999/xlink", "href") || "";
989
- if (href === "" || href.charAt(0) === "#") {
1311
+ // On a tab the shell's first listener took it (above).
1312
+ if (linksTaken || href === "" || href.charAt(0) === "#") {
990
1313
  return;
991
1314
  }
992
- event.preventDefault();
1315
+ callOf(preventNavigation, event, []);
993
1316
  let url = "";
994
1317
  try {
995
1318
  url = new URL(href, document.baseURI).href;
@@ -1150,6 +1473,9 @@ export const SHELL_RUNTIME = String.raw`(() => {
1150
1473
  resourceUpdated(params.uri);
1151
1474
  }
1152
1475
  break;
1476
+ case "porthole/event":
1477
+ runtimeEvent(params);
1478
+ break;
1153
1479
  case "ui/resource-teardown":
1154
1480
  case "ping":
1155
1481
  if (data.id !== undefined) {
@@ -1177,7 +1503,12 @@ export const SHELL_RUNTIME = String.raw`(() => {
1177
1503
  let initialized = false;
1178
1504
  let tries = 0;
1179
1505
  const initialize = () => {
1180
- if (initialized || tries >= 40) {
1506
+ if (initialized) {
1507
+ return;
1508
+ }
1509
+ if (tries >= 40) {
1510
+ // No host answered: the runtime has nothing to offer.
1511
+ runtimeOffer(null);
1181
1512
  return;
1182
1513
  }
1183
1514
  tries += 1;
@@ -1190,6 +1521,9 @@ export const SHELL_RUNTIME = String.raw`(() => {
1190
1521
  return;
1191
1522
  }
1192
1523
  initialized = true;
1524
+ const capabilities = result && result.hostCapabilities;
1525
+ const experimental = capabilities && capabilities.experimental;
1526
+ runtimeOffer(experimental && typeof experimental === "object" ? experimental["porthole/runtime"] : null);
1193
1527
  applyTheme(result && result.hostContext);
1194
1528
  notify("ui/notifications/initialized", {});
1195
1529
  schedule();