@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
@@ -6,8 +6,10 @@ 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, serveFile } from "./files.js";
10
- import { INERT_FILE_CSP } from "../compile/policy.js";
9
+ import { ownLoad, serveAsset, serveFile } from "./files.js";
10
+ import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
11
+ import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
12
+ import { parseViewer } from "../runtime/levels.js";
11
13
  import { memoryTicketStore } from "./tickets.js";
12
14
  /**
13
15
  * Paths on a content origin. Porthole's own live under `/__porthole/`; on a url-mode app's origin
@@ -22,6 +24,10 @@ const DOCUMENT_PATH = /^\/__porthole\/d\/([a-z2-7]{16})$/u;
22
24
  */
23
25
  const FILES_PATH = /^\/__porthole\/f\/([A-Za-z0-9_-]{40,4096})(\/.*)?$/u;
24
26
  const FILES_PREFIX = "/__porthole/f/";
27
+ /** An asset's address (P089): `/_blob/` and 32 lowercase hex characters (`ASSET_ID`). */
28
+ const ASSET_ROUTE = /^\/_blob\/([0-9a-f]{32})$/u;
29
+ /** The same, under a frame's sealed files' address (P091): `<base>__porthole/blob/<id>`. */
30
+ const SEALED_ASSET = /^\/__porthole\/blob\/([0-9a-f]{32})$/u;
25
31
  /** How long a sealed files' address opens a page's files on its own (P083); the shell renews it. */
26
32
  const FILES_ADDRESS_MS = 3_600_000;
27
33
  /** Below a sealed address: where the page's shell renews it (no file has a `__porthole/` path). */
@@ -159,23 +165,49 @@ function seconds(value, fallback, max, what) {
159
165
  }
160
166
  return value;
161
167
  }
162
- /** The cookies a request carries, as name → values (a name may come twice: partitioned or not). */
168
+ /**
169
+ * The cookies a request carries, as name → values (a name may come twice: partitioned or not).
170
+ * Only spaces and tabs are trimmed, as browsers trim them (P101): a name a sibling set with a
171
+ * leading U+00A0 is no `__Host-` name, though JavaScript's `trim` would make it one.
172
+ */
163
173
  function cookiesOf(request) {
164
174
  const header = request.headers.get("cookie") ?? "";
165
175
  const pairs = [];
176
+ const blank = /^[ \t]+|[ \t]+$/gu;
166
177
  for (const part of header.split(";")) {
167
178
  const at = part.indexOf("=");
168
179
  if (at > 0) {
169
- pairs.push([part.slice(0, at).trim(), part.slice(at + 1).trim()]);
180
+ pairs.push([part.slice(0, at).replace(blank, ""), part.slice(at + 1).replace(blank, "")]);
170
181
  }
171
182
  }
172
183
  return pairs;
173
184
  }
185
+ /** The artifact version a file set is, for its pages' notices to the host (P098). */
186
+ const versionOf = (instance) => instance.document.kind === "artifact"
187
+ ? { artifact: { id: instance.document.id, version: instance.document.version } }
188
+ : {};
174
189
  /**
175
190
  * Serving for domain, artifact and url modes, and the MCP Apps sandbox proxy (P016, P020): a
176
191
  * fetch-style handler a host's backend mounts in front of its own routes, plus `issue`, which the
177
192
  * host's authenticated API calls once it has decided a viewer may see an instance.
178
193
  */
194
+ /** A grant's viewer for the display's bridge (P087), checked; null without a level. */
195
+ function viewerOfGrant(grant) {
196
+ if (grant.level === undefined) {
197
+ if (grant.user !== undefined) {
198
+ throw new TypeError("A grant's user comes with its level");
199
+ }
200
+ return null;
201
+ }
202
+ const viewer = parseViewer({
203
+ level: grant.level,
204
+ ...(grant.user === undefined ? {} : { id: grant.user.id, name: grant.user.name }),
205
+ });
206
+ if (viewer === null) {
207
+ throw new TypeError("A grant's level is view, interact, admin or owner; its user's id and name 1 to 256 characters");
208
+ }
209
+ return viewer;
210
+ }
179
211
  export function createServer(options) {
180
212
  const { content } = options;
181
213
  const domain = content.domain;
@@ -374,7 +406,11 @@ export function createServer(options) {
374
406
  const origins = options.hostOrigins;
375
407
  switch (document.kind) {
376
408
  case "shell":
377
- return { html: config.shellDocument({ origins, cspMeta: false }), csp: config.csp };
409
+ return {
410
+ html: config.shellDocument({ origins, cspMeta: false }),
411
+ compiled: config,
412
+ assets: false,
413
+ };
378
414
  case "artifact": {
379
415
  const stored = await options.artifacts?.get(document.id, document.version);
380
416
  if (stored === null || stored === undefined) {
@@ -389,17 +425,31 @@ export function createServer(options) {
389
425
  }
390
426
  return {
391
427
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
392
- csp: config.csp,
428
+ compiled: config,
429
+ assets: true,
393
430
  };
394
431
  }
395
432
  case "mcp-proxy":
396
- return { html: sandboxProxyDocument(config, origins), csp: config.csp };
433
+ return { html: sandboxProxyDocument(config, origins), compiled: config, assets: false };
397
434
  case "external":
398
435
  return null;
399
436
  }
400
437
  }
401
438
  const cookieName = (key) => secure ? `__Host-porthole-${key}` : `porthole-${key}`;
402
- const ourCookie = (name) => name.startsWith("porthole-") || name.startsWith("__Host-porthole-");
439
+ /**
440
+ * Whether a cookie is one this server set, by its name (P101). Over https only `__Host-` names:
441
+ * every label is same-site with every other (P047), and a sibling label (a url-mode app, an
442
+ * app's preview) can set any other name for the whole content domain (`Domain=`), never a
443
+ * `__Host-` one, which the browser keeps to the origin that set it. Over plain http (loopback
444
+ * dev only: `createServer` refuses http elsewhere) the names have no prefix, set and read:
445
+ * `__Host-` needs `Secure`, and WebKit keeps no `Secure` cookie on a tab of http://*.localhost
446
+ * (measured). A sibling there can set the very name, so a copy of one of this label's own
447
+ * sessions or nonces is read: someone must hold one to plant it, on a developer's own server.
448
+ * Another label's session is never this label's, either scheme (its signed scope). Case and
449
+ * every byte count: `__host-` or a name with anything before the prefix is not ours. What
450
+ * Porthole strips from an app's requests and answers is wider (`isPortholeCookie`).
451
+ */
452
+ const ourCookie = (name) => name.startsWith(secure ? "__Host-porthole-" : "porthole-");
403
453
  /**
404
454
  * The cookie a taken ticket buys: this origin only (`__Host-` over https), never readable by the
405
455
  * content (`HttpOnly`). In a frame it is a third party's: `SameSite=None`, partitioned by the
@@ -435,8 +485,34 @@ export function createServer(options) {
435
485
  }
436
486
  /** The cookie a redirect entry's browser holds while it is away (P068), by its nonce. */
437
487
  const nonceCookie = (nonce) => cookieName(`n-${nonce}`);
438
- /** What an entered path's nonce cookie says after its code was redeemed: the loop guard. */
439
- const enteredMark = (pathname) => `e.${keys.instanceKey({ entered: pathname })}`;
488
+ /**
489
+ * What an entered path's nonce cookie says after its code was redeemed: the loop guard. Its
490
+ * label's and its path's (P101): a mark redeemed on one label, planted on another, is nothing.
491
+ */
492
+ const enteredMark = (label, pathname) => `e.${keys.instanceKey({ entered: pathname, label })}`;
493
+ /**
494
+ * Whether a url-mode app's request may ride its cookie (P101): what the app's own origin asks
495
+ * (its `Origin`, or `Sec-Fetch-Site` `same-origin`; `none` is the person's own address bar),
496
+ * and, where `navigable`, a navigation that opens it (GET or HEAD: the host's frame, a link, a
497
+ * redirect back from sign-in). Another origin (a sibling label's app, another frame on the
498
+ * host's page, an opaque origin's `null`) gets no write, no subresource, no socket. A request
499
+ * with neither header is no browser's (a browser always sends `Origin` on a socket and on a
500
+ * write, and fetch metadata on everything, where it sends them at all).
501
+ */
502
+ function fromItsOwnOrigin(request, label, navigable) {
503
+ const origin = request.headers.get("origin");
504
+ if (origin !== null && origin !== originOfLabel(label)) {
505
+ return false;
506
+ }
507
+ const site = request.headers.get("sec-fetch-site");
508
+ if (site === null || site === "same-origin" || site === "none") {
509
+ return true;
510
+ }
511
+ const method = request.method.toUpperCase();
512
+ return (navigable &&
513
+ request.headers.get("sec-fetch-mode") === "navigate" &&
514
+ (method === "GET" || method === "HEAD"));
515
+ }
440
516
  /** The access a request's own cookies give on `label`'s origin, for `key`'s instance or the app. */
441
517
  function accessOf(request, label, key) {
442
518
  let best = null;
@@ -572,16 +648,52 @@ export function createServer(options) {
572
648
  return null;
573
649
  }
574
650
  }
575
- function documentHeaders(csp) {
651
+ function documentHeaders(csp, permissions) {
576
652
  return new Headers({
577
653
  "content-type": "text/html; charset=utf-8",
578
654
  "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
655
+ // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
656
+ ...(permissions === null ? {} : { "permissions-policy": permissions }),
579
657
  "cache-control": "no-store",
580
658
  "referrer-policy": "no-referrer",
581
659
  "x-content-type-options": "nosniff",
582
660
  "x-robots-tag": "noindex, nofollow",
583
661
  });
584
662
  }
663
+ /**
664
+ * The access a sealed files' address carries (P083), if it holds for this origin now: on its own
665
+ * for its hour (`x`), then only for the running page's own loads until the session ends (`e`).
666
+ */
667
+ async function sealedAccess(request, label, token) {
668
+ const session = await keys.unseal(token);
669
+ const now = Date.now();
670
+ if (!isRecord(session) ||
671
+ typeof session.w !== "string" ||
672
+ typeof session.x !== "number" ||
673
+ typeof session.e !== "number" ||
674
+ (session.s !== undefined && typeof session.s !== "string")) {
675
+ return null;
676
+ }
677
+ const open = session.x > now || (session.e > now && ownLoad(request));
678
+ let instance;
679
+ try {
680
+ instance = cleanInstance(session.i);
681
+ }
682
+ catch {
683
+ return null;
684
+ }
685
+ if (!open || instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
686
+ return null;
687
+ }
688
+ return {
689
+ instance,
690
+ viewer: session.w,
691
+ origin: originOfLabel(label),
692
+ expiresAt: session.e,
693
+ ...(session.a === 1 ? { anonymous: true } : {}),
694
+ ...(typeof session.s === "string" ? { subject: session.s } : {}),
695
+ };
696
+ }
585
697
  /**
586
698
  * A file set's file in a frame (P083): the sealed access in its path opens it, once it holds
587
699
  * for this origin and the host's check lets it in; every path under it is the same version's.
@@ -616,39 +728,20 @@ export function createServer(options) {
616
728
  headers: { location: `${origin}${base}${url.search}`, "cache-control": "no-store" },
617
729
  });
618
730
  }
619
- const session = await keys.unseal(token);
620
- const now = Date.now();
621
- let instance = null;
622
- let end = 0;
623
- if (isRecord(session) &&
624
- typeof session.w === "string" &&
625
- typeof session.x === "number" &&
626
- typeof session.e === "number" &&
627
- (session.s === undefined || typeof session.s === "string")) {
628
- end = session.e;
629
- const open = session.x > now || (session.e > now && ownLoad(request));
630
- try {
631
- const clean = cleanInstance(session.i);
632
- instance =
633
- open && clean.document.kind === "artifact" && nameOf(clean.scope) === label
634
- ? clean
635
- : null;
636
- }
637
- catch {
638
- instance = null;
639
- }
640
- }
641
- if (instance === null || !isRecord(session)) {
731
+ const access = await sealedAccess(request, label, token);
732
+ if (access === null) {
642
733
  return page(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", method, "session");
643
734
  }
644
- const access = {
645
- instance,
646
- viewer: session.w,
647
- origin,
648
- expiresAt: end,
649
- ...(session.a === 1 ? { anonymous: true } : {}),
650
- ...(typeof session.s === "string" ? { subject: session.s } : {}),
651
- };
735
+ // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
736
+ // sends a frame's path, where some send no Referer that names it.
737
+ const blob = SEALED_ASSET.exec(rest)?.[1];
738
+ if (blob !== undefined) {
739
+ if (options.assets === undefined) {
740
+ return page(404, "Not found", "This address names no content.", method);
741
+ }
742
+ return ((await assetFor(request, label, access, blob)) ??
743
+ page(404, "Not found", "This address names no content.", method));
744
+ }
652
745
  if (rest === RENEW_PATH) {
653
746
  // Only the page itself renews its address, while its session lasts and the host lets it.
654
747
  if (method !== "GET" || !ownLoad(request)) {
@@ -736,6 +829,7 @@ export function createServer(options) {
736
829
  compiled: served.compiled,
737
830
  hostOrigins: options.hostOrigins,
738
831
  frameAncestors,
832
+ ...versionOf(access.instance),
739
833
  });
740
834
  }
741
835
  // A frame's document (a ticket's): its files carry its access in their path (P083). The
@@ -755,18 +849,170 @@ export function createServer(options) {
755
849
  hostOrigins: options.hostOrigins,
756
850
  frameAncestors,
757
851
  ticket: { expires: sealed.expires },
852
+ ...versionOf(access.instance),
758
853
  });
759
854
  }
760
855
  // One page at a file set's base (P081): its base is the page, nothing under it is.
761
856
  if (at !== undefined && at.rest !== "") {
762
857
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
763
858
  }
764
- const headers = documentHeaders(served.csp);
859
+ // A page that may use its artifact's assets loads them from its own origin (P089); every
860
+ // served page carries its frame's sandbox, a tab of its own included (P099).
861
+ const { config, cspDirectives } = served.compiled;
862
+ const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config));
765
863
  if (cookie !== null) {
766
864
  headers.set("set-cookie", cookie);
767
865
  }
768
866
  return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
769
867
  }
868
+ /**
869
+ * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
870
+ * artifact of this origin (its page's sealed files' address, as its `Referer` says, P091; or a
871
+ * session cookie), then the host's check for that access, then the host's store asked with it;
872
+ * served only when the asset is that artifact's, on its scope's origin. Never an entry. By id
873
+ * alone only where the host opted into it (`assets.bearer`).
874
+ */
875
+ async function serveAssetAt(request, label, id) {
876
+ const method = request.method.toUpperCase();
877
+ const store = options.assets;
878
+ const none = () => page(404, "Not found", "This address names no content.", method);
879
+ if (store === undefined) {
880
+ return none();
881
+ }
882
+ const scoped = (asset) => {
883
+ try {
884
+ return asset !== null && nameOf(asset.scope) === label;
885
+ }
886
+ catch {
887
+ return false;
888
+ }
889
+ };
890
+ if (store.bearer === true) {
891
+ const asset = await store.get(id, null);
892
+ return scoped(asset)
893
+ ? serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, null) })
894
+ : none();
895
+ }
896
+ const accesses = await assetAccessesOf(request, label);
897
+ if (accesses.length === 0) {
898
+ return new Response(null, { status: 401, headers: { "cache-control": "no-store" } });
899
+ }
900
+ for (const access of accesses) {
901
+ const answer = await assetFor(request, label, access, id);
902
+ if (answer !== null) {
903
+ return answer;
904
+ }
905
+ }
906
+ return none();
907
+ }
908
+ /**
909
+ * An asset for one access (P089, P091): the store asked with it, served only when the asset is
910
+ * its artifact's on its scope's origin, after the host's check; its code only where it was
911
+ * trusted and the artifact's config still lets uploaded code run. Null: not this access's.
912
+ */
913
+ async function assetFor(request, label, access, id) {
914
+ const store = options.assets;
915
+ if (store === undefined || access.instance.document.kind !== "artifact") {
916
+ return null;
917
+ }
918
+ const asset = await store.get(id, access);
919
+ let named = null;
920
+ try {
921
+ named = asset === null ? null : nameOf(asset.scope);
922
+ }
923
+ catch {
924
+ named = null;
925
+ }
926
+ if (asset === null || named !== label || asset.artifact !== access.instance.document.id) {
927
+ return null;
928
+ }
929
+ const refusal = await denied(request, access);
930
+ if (refusal !== null) {
931
+ return refusal;
932
+ }
933
+ return serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, access) });
934
+ }
935
+ /**
936
+ * Whether a code-typed asset goes out as code (P089, P103): only where it was trusted when it
937
+ * was uploaded and the config its artifact's page is served under still lets uploaded code
938
+ * run, asked at every request, so a stricter config wins at once. An access names that config.
939
+ * By id alone (bearer mode) the server can't tell which of its artifact configs the page is
940
+ * under: the strictest it might be decides (every one must let uploaded code run).
941
+ */
942
+ function runsAsCode(asset, access) {
943
+ if (asset.trusted !== true) {
944
+ return false;
945
+ }
946
+ if (access !== null) {
947
+ const config = compiledFor(access.instance)?.config;
948
+ return config !== undefined && assetCodeRuns(config);
949
+ }
950
+ const artifacts = [...compiled.values()]
951
+ .map((each) => each.config)
952
+ .filter((config) => config.mode === "artifact" && config.isolation === "domain");
953
+ return artifacts.length > 0 && artifacts.every((config) => assetCodeRuns(config));
954
+ }
955
+ /**
956
+ * The accesses a request carries to artifacts of `label`'s origin, most specific first: the
957
+ * sealed files' address its page is at (a frame's, which keeps no cookie, P083), as its
958
+ * same-origin `Referer` names it; then its session cookies.
959
+ */
960
+ async function assetAccessesOf(request, label) {
961
+ const found = [];
962
+ const referer = request.headers.get("referer");
963
+ if (referer !== null) {
964
+ try {
965
+ const from = new URL(referer);
966
+ const token = FILES_PATH.exec(from.pathname)?.[1];
967
+ if (from.origin === originOfLabel(label) && token !== undefined) {
968
+ const sealed = await sealedAccess(request, label, token);
969
+ if (sealed !== null) {
970
+ found.push(sealed);
971
+ }
972
+ }
973
+ }
974
+ catch {
975
+ // Not an address: no access from it.
976
+ }
977
+ }
978
+ return [...found, ...artifactAccessesOf(request, label)];
979
+ }
980
+ /** The accesses a request's cookies give to artifacts of `label`'s origin, latest first. */
981
+ function artifactAccessesOf(request, label) {
982
+ const found = [];
983
+ for (const [name, value] of cookiesOf(request)) {
984
+ if (!ourCookie(name)) {
985
+ continue;
986
+ }
987
+ const session = keys.verify(value);
988
+ if (!isRecord(session) ||
989
+ typeof session.w !== "string" ||
990
+ typeof session.x !== "number" ||
991
+ session.x <= Date.now() ||
992
+ (session.s !== undefined && typeof session.s !== "string")) {
993
+ continue;
994
+ }
995
+ let instance;
996
+ try {
997
+ instance = cleanInstance(session.i);
998
+ if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
999
+ continue;
1000
+ }
1001
+ }
1002
+ catch {
1003
+ continue;
1004
+ }
1005
+ found.push({
1006
+ instance,
1007
+ viewer: session.w,
1008
+ origin: originOfLabel(label),
1009
+ expiresAt: session.x,
1010
+ ...(session.a === 1 ? { anonymous: true } : {}),
1011
+ ...(typeof session.s === "string" ? { subject: session.s } : {}),
1012
+ });
1013
+ }
1014
+ return found.sort((a, b) => b.expiresAt - a.expiresAt);
1015
+ }
770
1016
  /**
771
1017
  * A clean address without a cookie for it (P068): off to the host's authorize route with a
772
1018
  * signed state, the browser holding the state's nonce in a cookie of this origin. A path just
@@ -804,8 +1050,9 @@ export function createServer(options) {
804
1050
  if (path.length > MAX_PATH) {
805
1051
  return page(414, "Address too long", "This address is too long to open.", method);
806
1052
  }
807
- const mark = enteredMark(url.pathname);
808
- if (cookiesOf(request).some(([name, value]) => ourCookie(name) && value === mark)) {
1053
+ const mark = enteredMark(label, url.pathname);
1054
+ const marked = cookieName("n-");
1055
+ if (cookiesOf(request).some(([name, value]) => name.startsWith(marked) && value === mark)) {
809
1056
  return page(401, "Open this in a new tab", "This browser keeps no sign-in for it inside a frame.", method, "cookies");
810
1057
  }
811
1058
  const nonce = base32(randomBytes(10));
@@ -885,7 +1132,7 @@ export function createServer(options) {
885
1132
  ? { b: base, ...(pinned === true ? { k: 1 } : {}) }
886
1133
  : { p: target.pathname }));
887
1134
  headers.append("set-cookie", [
888
- `${named}=${enteredMark(target.pathname)}`,
1135
+ `${named}=${enteredMark(label, target.pathname)}`,
889
1136
  "Path=/",
890
1137
  "HttpOnly",
891
1138
  `Max-Age=${ENTERED_SECONDS}`,
@@ -934,7 +1181,7 @@ export function createServer(options) {
934
1181
  function forUpstream(request) {
935
1182
  const headers = new Headers(request.headers);
936
1183
  const kept = cookiesOf(request)
937
- .filter(([name]) => !ourCookie(name))
1184
+ .filter(([name]) => !isPortholeCookie(name))
938
1185
  .map(([name, value]) => `${name}=${value}`);
939
1186
  if (kept.length > 0) {
940
1187
  headers.set("cookie", kept.join("; "));
@@ -949,8 +1196,7 @@ export function createServer(options) {
949
1196
  const headers = new Headers(response.headers);
950
1197
  headers.delete("set-cookie");
951
1198
  for (const cookie of response.headers.getSetCookie()) {
952
- const name = cookie.split("=")[0]?.trim() ?? "";
953
- if (!ourCookie(name)) {
1199
+ if (!setsPortholeCookie(cookie)) {
954
1200
  headers.append("set-cookie", cookie);
955
1201
  }
956
1202
  }
@@ -964,6 +1210,10 @@ export function createServer(options) {
964
1210
  }
965
1211
  async function serveApp(request, label) {
966
1212
  const method = request.method.toUpperCase();
1213
+ // Before the cookie is read: another origin's request is refused whatever it carries.
1214
+ if (!fromItsOwnOrigin(request, label, true)) {
1215
+ return page(403, "Not from this app", "A request from another site doesn't ride this app's sign-in.", method);
1216
+ }
967
1217
  const access = accessOf(request, label, null);
968
1218
  if (access === null) {
969
1219
  return page(401, "Open this from the app", "This address shows an app only to the people the app opens it for.", method, "session");
@@ -1085,7 +1335,9 @@ export function createServer(options) {
1085
1335
  const path = clean.document.kind === "external"
1086
1336
  ? `${ENTER_PATH}?ticket=${ticket}`
1087
1337
  : `${PREFIX}d/${key}?ticket=${ticket}`;
1088
- return { url: `${origin}${path}`, origin, reports: true };
1338
+ // The viewer's level, as the host's access decided it now (P087): for the display's bridge.
1339
+ const viewer = viewerOfGrant(grant);
1340
+ return { url: `${origin}${path}`, origin, reports: true, ...(viewer ? { viewer } : {}) };
1089
1341
  },
1090
1342
  forget(filter = {}) {
1091
1343
  for (const [key, each] of answers) {
@@ -1168,7 +1420,11 @@ export function createServer(options) {
1168
1420
  },
1169
1421
  async access(request) {
1170
1422
  const at = labelOf(request);
1171
- if (at === null || at === "mismatch" || !ours(at.label)) {
1423
+ // A socket is never a navigation: the app's own origin only (P101).
1424
+ if (at === null ||
1425
+ at === "mismatch" ||
1426
+ !ours(at.label) ||
1427
+ !fromItsOwnOrigin(request, at.label, false)) {
1172
1428
  return null;
1173
1429
  }
1174
1430
  const access = accessOf(request, at.label, null);
@@ -1199,11 +1455,21 @@ export function createServer(options) {
1199
1455
  return script;
1200
1456
  }
1201
1457
  if (url.pathname === SESSION_PATH) {
1202
- // Whether this request's cookie opens its origin's app: the entry page asks.
1458
+ // Whether this request's cookie opens its origin's app: the entry page asks, from the
1459
+ // app's origin (P101).
1460
+ if (!fromItsOwnOrigin(request, label, false)) {
1461
+ return new Response(null, { status: 403, headers: { "cache-control": "no-store" } });
1462
+ }
1203
1463
  const access = accessOf(request, label, null);
1204
1464
  const status = access === null ? 401 : (await denied(request, access)) === null ? 204 : 403;
1205
1465
  return new Response(null, { status, headers: { "cache-control": "no-store" } });
1206
1466
  }
1467
+ // An artifact's asset library (P089), outside every version: `/_blob/<id>` only; any
1468
+ // other path there is a clean address as before (after the review).
1469
+ const asset = options.assets === undefined ? null : ASSET_ROUTE.exec(url.pathname);
1470
+ if (asset?.[1] !== undefined) {
1471
+ return await serveAssetAt(request, label, asset[1]);
1472
+ }
1207
1473
  const document = DOCUMENT_PATH.exec(url.pathname);
1208
1474
  if (document?.[1] !== undefined) {
1209
1475
  return await serveDocument(request, url, label, document[1]);
@@ -1,5 +1,6 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
2
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
3
+ import type { ViewerLevel } from "../runtime/levels.ts";
3
4
  import type { Naming } from "./naming.ts";
4
5
  export interface ContentDomain {
5
6
  /**
@@ -57,6 +58,23 @@ export type Grant = ({
57
58
  * url-mode app's every request, rides on.
58
59
  */
59
60
  readonly sessionSeconds?: number;
61
+ /**
62
+ * The viewer's level on this instance (P087), as the host decided it now: carried in the
63
+ * issue's answer (`FrameLocation.viewer`) to the display's bridge, which checks each runtime
64
+ * method's level against it. Never in the ticket or the cookie, never shown to content but by
65
+ * the `user` capability.
66
+ */
67
+ readonly level?: ViewerLevel;
68
+ /**
69
+ * Who the viewer is to pages that declare `user` (P087): the host's public id for them (whose
70
+ * per-user data, `data/users/<id>`, the page reaches: one path segment, never `me`) and a name.
71
+ * Never `viewer`, unless the host means it to be seen; `pseudonymFor(secret, artifact, person)`
72
+ * gives an id per artifact, so pages can't link a person across artifacts. Only with `level`.
73
+ */
74
+ readonly user?: {
75
+ readonly id: string;
76
+ readonly name?: string;
77
+ };
60
78
  };
61
79
  export interface TicketRecord {
62
80
  readonly instance: InstanceRef;
@@ -122,6 +140,52 @@ export interface StoredFiles {
122
140
  export type StoredVersion = {
123
141
  readonly html: string;
124
142
  } | StoredFiles;
143
+ /**
144
+ * One asset of an artifact's library (P089), as the host stored it: served at `/_blob/<id>` on
145
+ * the origin of `scope`, and nowhere else. Its type is Porthole's for `name`'s extension, never
146
+ * the uploader's; it is never served as a page.
147
+ */
148
+ export interface StoredAsset {
149
+ /** The storage scope whose origin serves it (the artifact's). */
150
+ readonly scope: string;
151
+ /**
152
+ * The artifact whose library holds it (`ServedDocument`'s `id`, after the review): served only
153
+ * to an access for that artifact, never another one sharing the scope.
154
+ */
155
+ readonly artifact: string;
156
+ /**
157
+ * Whether it may run as code (P089, after the review): a script, stylesheet or WebAssembly an
158
+ * admin uploaded where uploaded code may run (the upload's `trusted`). Any other code-typed
159
+ * asset is served as a download, whatever the config says now; a trusted one too, once the
160
+ * config no longer lets uploaded code run (P103: asked at every request; in bearer mode, every
161
+ * artifact config the server has must).
162
+ */
163
+ readonly trusted?: boolean;
164
+ /** Its file name (its extension types it). */
165
+ readonly name: string;
166
+ readonly size: number;
167
+ /** The SHA-256 of its bytes, lowercase hex: its strong ETag. */
168
+ readonly sha256: string;
169
+ read(): Promise<FileBody | null>;
170
+ }
171
+ /**
172
+ * Where an artifact's assets are kept (P089): the host's library, by id. Ids are the host's, 32
173
+ * lowercase hex characters made at random (`ASSET_ID`): an asset's address is known only to those
174
+ * shown it; Porthole serves one only on its own scope's origin.
175
+ */
176
+ export interface AssetStore {
177
+ /**
178
+ * The asset, for `access` (who asks, for which artifact: the host decides, and its check runs
179
+ * after); null if it isn't there for them. `access` is null only in bearer mode.
180
+ */
181
+ get(id: string, access: Access | null): Promise<StoredAsset | null>;
182
+ /**
183
+ * Bearer mode, an explicit opt-in (after the review): serve an asset to anyone holding its id,
184
+ * with no access and no host check (a public artifact's library). Its id is then a capability:
185
+ * whoever saw it keeps it until the asset is removed.
186
+ */
187
+ readonly bearer?: boolean;
188
+ }
125
189
  /** Stored pages (artifact mode). Versions are immutable: a new page is a new version. */
126
190
  export interface ArtifactStore {
127
191
  get(id: string, version: string): Promise<StoredVersion | null>;
@@ -188,6 +252,13 @@ export interface ServerOptions {
188
252
  */
189
253
  readonly configs: Readonly<Record<string, PortholeConfig>>;
190
254
  readonly artifacts?: ArtifactStore;
255
+ /**
256
+ * Artifacts' asset libraries (P089): `/_blob/<id>` on each content origin, for a request that
257
+ * carries an access to the asset's own artifact (a frame's sealed files' address as its
258
+ * `Referer`, or a session cookie), after the host's check. Absent: `/_blob/` is a clean address
259
+ * like any other.
260
+ */
261
+ readonly assets?: AssetStore;
191
262
  readonly tickets?: TicketStore;
192
263
  /** Url mode: where an external instance's requests go once let in. Absent: nothing serves them. */
193
264
  readonly upstream?: Upstream;
@@ -236,8 +307,9 @@ export interface PortholeServer {
236
307
  issue(instance: InstanceRef, grant: Grant): Promise<FrameLocation>;
237
308
  /**
238
309
  * The access a request's cookie carries for a url-mode app on the request's origin, or null
239
- * (no good cookie, or the host's check denies it): for a host's own WebSocket upgrade path,
240
- * which a fetch-style handler can't take.
310
+ * (no good cookie, an `Origin` or `Sec-Fetch-Site` of another origin's (P101), or the host's
311
+ * check denies it): for a host's own WebSocket upgrade path, which a fetch-style handler can't
312
+ * take.
241
313
  */
242
314
  access(request: Request): Promise<Access | null>;
243
315
  /** The frame source every content origin matches (`https://*.example-usercontent.com`). */