@botiverse/porthole 0.7.0 → 0.9.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 (166) hide show
  1. package/README.md +9 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/annotate/types.d.ts +40 -4
  4. package/dist/annotate/types.js +6 -1
  5. package/dist/annotate/validate.d.ts +10 -0
  6. package/dist/annotate/validate.js +24 -1
  7. package/dist/bridge/bounded-text.d.ts +34 -0
  8. package/dist/bridge/bounded-text.js +188 -0
  9. package/dist/bridge/bridge.d.ts +25 -5
  10. package/dist/bridge/bridge.js +311 -73
  11. package/dist/bridge/json-data.d.ts +28 -0
  12. package/dist/bridge/json-data.js +86 -0
  13. package/dist/bridge/navigation.d.ts +5 -0
  14. package/dist/bridge/navigation.js +7 -0
  15. package/dist/bridge/refusal.js +1 -0
  16. package/dist/bridge/types.d.ts +32 -1
  17. package/dist/check/page-source.js +1 -1
  18. package/dist/check/page.js +2 -0
  19. package/dist/compile/compile.d.ts +6 -0
  20. package/dist/compile/compile.js +3 -1
  21. package/dist/compile/policy.d.ts +38 -2
  22. package/dist/compile/policy.js +122 -7
  23. package/dist/config/capabilities.d.ts +23 -4
  24. package/dist/config/capabilities.js +12 -2
  25. package/dist/config/schema.d.ts +11 -0
  26. package/dist/config/validate.d.ts +8 -2
  27. package/dist/config/validate.js +28 -6
  28. package/dist/config/warnings.d.ts +20 -0
  29. package/dist/config/warnings.js +25 -0
  30. package/dist/conformance/behavior.js +46 -1
  31. package/dist/conformance/cookies.d.ts +15 -0
  32. package/dist/conformance/cookies.js +80 -0
  33. package/dist/conformance/harness/page.d.ts +1 -0
  34. package/dist/conformance/harness/page.js +9 -2
  35. package/dist/conformance/harness-source.js +1 -1
  36. package/dist/conformance/host-kit.js +5 -1
  37. package/dist/conformance/index.d.ts +10 -0
  38. package/dist/conformance/limits.js +38 -1
  39. package/dist/conformance/runtime.js +10 -0
  40. package/dist/conformance/served.d.ts +2 -0
  41. package/dist/conformance/served.js +737 -4
  42. package/dist/files/paths.js +4 -0
  43. package/dist/guide/gates.d.ts +7 -1
  44. package/dist/guide/gates.js +12 -0
  45. package/dist/guide/guide.js +2 -2
  46. package/dist/guide/runtime.js +11 -3
  47. package/dist/host/create-host.js +81 -39
  48. package/dist/host/pages-of-set.d.ts +43 -0
  49. package/dist/host/pages-of-set.js +196 -0
  50. package/dist/host/types.d.ts +8 -1
  51. package/dist/index.d.ts +5 -4
  52. package/dist/index.js +3 -2
  53. package/dist/mcp/adapter.js +11 -15
  54. package/dist/node/index.d.ts +36 -4
  55. package/dist/node/index.js +402 -101
  56. package/dist/platform/types.d.ts +9 -0
  57. package/dist/platform/web.js +8 -0
  58. package/dist/presets/presets.d.ts +16 -8
  59. package/dist/presets/presets.js +39 -8
  60. package/dist/protocol/live-data.d.ts +6 -2
  61. package/dist/protocol/live-data.js +20 -1
  62. package/dist/protocol/mcp-apps.d.ts +13 -2
  63. package/dist/protocol/mcp-apps.js +10 -2
  64. package/dist/protocol/message-text.d.ts +8 -0
  65. package/dist/protocol/message-text.js +29 -0
  66. package/dist/protocol/runtime-calls.js +3 -0
  67. package/dist/protocol/shell-adapter.js +16 -22
  68. package/dist/react/context-notice.d.ts +32 -0
  69. package/dist/react/context-notice.js +28 -0
  70. package/dist/react/dialog.js +62 -18
  71. package/dist/react/frame.d.ts +18 -3
  72. package/dist/react/frame.js +79 -2
  73. package/dist/react/index.d.ts +2 -1
  74. package/dist/react/index.js +2 -1
  75. package/dist/runtime/contract.d.ts +9 -1
  76. package/dist/runtime/contract.js +31 -2
  77. package/dist/runtime/db.d.ts +41 -6
  78. package/dist/runtime/db.js +120 -16
  79. package/dist/runtime/declaration.d.ts +15 -1
  80. package/dist/runtime/declaration.js +184 -87
  81. package/dist/runtime/requests.js +27 -11
  82. package/dist/runtime/types.generated.js +1 -1
  83. package/dist/server/files.d.ts +5 -0
  84. package/dist/server/files.js +22 -7
  85. package/dist/server/host.d.ts +18 -1
  86. package/dist/server/host.js +132 -2
  87. package/dist/server/index.d.ts +1 -1
  88. package/dist/server/index.js +1 -1
  89. package/dist/server/peer.d.ts +4 -0
  90. package/dist/server/peer.js +19 -0
  91. package/dist/server/proxy.d.ts +6 -0
  92. package/dist/server/proxy.js +12 -3
  93. package/dist/server/server.js +113 -26
  94. package/dist/server/types.d.ts +6 -3
  95. package/dist/shell/annotate.d.ts +7 -2
  96. package/dist/shell/annotate.js +233 -15
  97. package/dist/shell/document.d.ts +8 -0
  98. package/dist/shell/document.js +3 -0
  99. package/dist/shell/runtime.js +361 -14
  100. package/docs/ADOPTING.md +119 -14
  101. package/docs/ARCHITECTURE.md +15 -4
  102. package/docs/DECISIONS.md +1610 -9
  103. package/docs/DESIGN.md +114 -30
  104. package/docs/THREAT_MODEL.md +652 -0
  105. package/package.json +14 -3
  106. package/src/annotate/types.ts +37 -5
  107. package/src/annotate/validate.ts +30 -1
  108. package/src/bridge/bounded-text.ts +240 -0
  109. package/src/bridge/bridge.ts +373 -84
  110. package/src/bridge/json-data.ts +95 -0
  111. package/src/bridge/navigation.ts +10 -0
  112. package/src/bridge/refusal.ts +1 -0
  113. package/src/bridge/types.ts +30 -1
  114. package/src/check/page.ts +2 -0
  115. package/src/compile/compile.ts +9 -1
  116. package/src/compile/policy.ts +130 -7
  117. package/src/config/capabilities.ts +22 -3
  118. package/src/config/schema.ts +11 -0
  119. package/src/config/validate.ts +43 -5
  120. package/src/config/warnings.ts +42 -0
  121. package/src/conformance/behavior.ts +54 -1
  122. package/src/conformance/cookies.ts +93 -0
  123. package/src/conformance/harness/page.ts +11 -2
  124. package/src/conformance/host-kit.ts +10 -1
  125. package/src/conformance/index.ts +10 -0
  126. package/src/conformance/limits.ts +39 -1
  127. package/src/conformance/runtime.ts +21 -0
  128. package/src/conformance/served.ts +888 -4
  129. package/src/files/paths.ts +4 -0
  130. package/src/guide/gates.ts +13 -1
  131. package/src/guide/guide.ts +3 -3
  132. package/src/guide/runtime.ts +12 -3
  133. package/src/host/create-host.ts +88 -38
  134. package/src/host/pages-of-set.ts +226 -0
  135. package/src/host/types.ts +15 -1
  136. package/src/index.ts +5 -0
  137. package/src/mcp/adapter.ts +16 -20
  138. package/src/node/index.ts +507 -116
  139. package/src/platform/types.ts +6 -0
  140. package/src/platform/web.ts +10 -0
  141. package/src/presets/presets.ts +60 -17
  142. package/src/protocol/live-data.ts +31 -3
  143. package/src/protocol/mcp-apps.ts +11 -2
  144. package/src/protocol/message-text.ts +36 -0
  145. package/src/protocol/runtime-calls.ts +3 -0
  146. package/src/protocol/shell-adapter.ts +27 -23
  147. package/src/react/context-notice.tsx +95 -0
  148. package/src/react/dialog.tsx +77 -17
  149. package/src/react/frame.tsx +107 -2
  150. package/src/react/index.ts +8 -1
  151. package/src/runtime/contract.ts +36 -2
  152. package/src/runtime/db.ts +140 -20
  153. package/src/runtime/declaration.ts +227 -89
  154. package/src/runtime/requests.ts +27 -11
  155. package/src/runtime/types.generated.ts +1 -1
  156. package/src/server/files.ts +29 -11
  157. package/src/server/host.ts +158 -3
  158. package/src/server/index.ts +1 -0
  159. package/src/server/peer.ts +21 -0
  160. package/src/server/proxy.ts +13 -3
  161. package/src/server/server.ts +139 -36
  162. package/src/server/types.ts +6 -3
  163. package/src/shell/annotate.ts +233 -15
  164. package/src/shell/document.ts +8 -0
  165. package/src/shell/runtime.ts +361 -14
  166. package/types/runtime/v1/context.d.ts +13 -2
@@ -11,6 +11,7 @@ import {
11
11
  type ContentDomainInfo,
12
12
  } from "./domain.ts";
13
13
  import { reservedLabels, type Naming } from "./naming.ts";
14
+ import { peerAddress } from "./peer.ts";
14
15
  import { appStatusPage } from "./pages.ts";
15
16
  import { createServer } from "./server.ts";
16
17
  import type {
@@ -170,10 +171,22 @@ export interface ContentHostOptions<V> {
170
171
  * served throw at startup.
171
172
  */
172
173
  readonly health?: HealthOptions;
173
- /** Issues per viewer (or address) per minute, in this process. */
174
+ /**
175
+ * Issues per viewer (or, with no viewer, per address) per minute, in this process. The address
176
+ * is one the host trusts, never one a client says (P092): the socket's peer (the Node adapter
177
+ * leaves it on the request), or on Workers `CF-Connecting-IP`. Behind proxies, say how many
178
+ * append to `X-Forwarded-For` (`trustedProxies`), or key it yourself (`key`); otherwise every
179
+ * request through a proxy is that proxy's address.
180
+ */
174
181
  readonly rateLimit?: {
175
182
  readonly perMinute: number;
176
183
  readonly key?: (request: Request, viewer: V | null) => string;
184
+ /**
185
+ * How many proxies in front of the app each append the address they saw to
186
+ * `X-Forwarded-For` (default 0: it is never read). The address is the entry the outermost
187
+ * appended; the entries before it are the client's to write.
188
+ */
189
+ readonly trustedProxies?: number;
177
190
  };
178
191
  /** The kit's events: a function, or a logger (`{ info, warn, error }`). */
179
192
  readonly log?: ((event: ContentHostEvent) => void) | ContentLogger;
@@ -449,6 +462,138 @@ const authorizeSource = (url: string): string => {
449
462
  return `${parsed.origin}${parsed.pathname}`;
450
463
  };
451
464
 
465
+ /**
466
+ * The most an issue request's body may be (S06, P092). `{ instance }` is a few hundred bytes; an
467
+ * MCP view's declared egress, the largest proposal, a few KiB.
468
+ */
469
+ export const ISSUE_BODY_BYTES = 65_536;
470
+
471
+ /** Whether a request came through Workers: Cloudflare's own `cf`, which no client can send. */
472
+ const onWorkers = (request: Request): boolean => {
473
+ const cf: unknown = (request as { readonly cf?: unknown }).cf;
474
+ return typeof cf === "object" && cf !== null;
475
+ };
476
+
477
+ /**
478
+ * The address an anonymous viewer's rate is keyed by (P092): one the host trusts, never what a
479
+ * client says. Behind `trustedProxies` proxies, the X-Forwarded-For entry the outermost appended
480
+ * (a header with fewer entries came past them: its peer); else the socket's peer, as the Node
481
+ * adapter saw it; on Workers, CF-Connecting-IP (Cloudflare's edge sets it); else none known.
482
+ */
483
+ function clientAddress(request: Request, trustedProxies: number): string {
484
+ if (trustedProxies > 0) {
485
+ const hops = (request.headers.get("x-forwarded-for") ?? "")
486
+ .split(",")
487
+ .map((hop) => hop.trim())
488
+ .filter((hop) => hop !== "");
489
+ const hop = hops[hops.length - trustedProxies];
490
+ if (hop !== undefined) {
491
+ return clientOf(hop);
492
+ }
493
+ }
494
+ const peer = peerAddress(request);
495
+ if (peer !== null) {
496
+ return clientOf(peer);
497
+ }
498
+ const edge = onWorkers(request) ? request.headers.get("cf-connecting-ip") : null;
499
+ return edge === null || edge === "" ? "unknown" : clientOf(edge);
500
+ }
501
+
502
+ /** An IPv6 address's groups (8; an embedded IPv4 tail as two), or null where it is no IPv6. */
503
+ function ipv6Groups(address: string): string[] | null {
504
+ const halves = address.toLowerCase().split("::");
505
+ if (halves.length > 2) {
506
+ return null;
507
+ }
508
+ const groupsOf = (part: string | undefined) =>
509
+ part === undefined || part === ""
510
+ ? []
511
+ : part.split(":").flatMap((group) => (group.includes(".") ? ["0", "0"] : [group]));
512
+ const head = groupsOf(halves[0]);
513
+ const tail = groupsOf(halves[1]);
514
+ const groups =
515
+ halves.length === 2
516
+ ? [...head, ...Array<string>(Math.max(0, 8 - head.length - tail.length)).fill("0"), ...tail]
517
+ : head;
518
+ return groups.length === 8 && groups.every((group) => /^[0-9a-f]{1,4}$/u.test(group))
519
+ ? groups
520
+ : null;
521
+ }
522
+
523
+ /**
524
+ * The part of an address that names one client (P092): an IPv6 address by its /64, since a host
525
+ * or a subscriber is given a /64 and rotating addresses within it costs nothing (one key each
526
+ * would let one client fill the limiter and wipe every bucket); an IPv4-mapped one as its IPv4;
527
+ * anything else as it is.
528
+ */
529
+ function clientOf(address: string): string {
530
+ const bare = (address.startsWith("[") ? address.slice(1, address.indexOf("]")) : address).split(
531
+ "%",
532
+ )[0];
533
+ if (bare === undefined || !bare.includes(":")) {
534
+ return address;
535
+ }
536
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/iu.exec(bare)?.[1];
537
+ if (mapped !== undefined) {
538
+ return mapped;
539
+ }
540
+ const groups = ipv6Groups(bare);
541
+ return groups === null
542
+ ? address
543
+ : `${groups
544
+ .slice(0, 4)
545
+ .map((group) => group.replace(/^0+(?=.)/u, ""))
546
+ .join(":")}::/64`;
547
+ }
548
+
549
+ const tooLarge = () =>
550
+ refusal(413, "too-large", `The body is { instance }: at most ${ISSUE_BODY_BYTES} bytes`);
551
+
552
+ /** Whether a request declares a body longer than `limit` (an early refusal; never the bound). */
553
+ const declaresMoreThan = (request: Request, limit: number): boolean => {
554
+ const declared = request.headers.get("content-length")?.trim() ?? "";
555
+ return /^\d+$/u.test(declared) && Number(declared) > limit;
556
+ };
557
+
558
+ /**
559
+ * A request's body as text, reading at most `limit` bytes (S06, P092): past it the read stops,
560
+ * the body is cancelled, and the answer is null. The bytes read are counted, whatever the
561
+ * request's Content-Length says (absent, chunked, or not the truth). Throws where the body can't
562
+ * be read (the client went away mid-way).
563
+ */
564
+ async function boundedText(request: Request, limit: number): Promise<string | null> {
565
+ if (request.body === null) {
566
+ return "";
567
+ }
568
+ const reader = request.body.getReader();
569
+ const chunks: Uint8Array[] = [];
570
+ let size = 0;
571
+ for (;;) {
572
+ const { done, value } = await reader.read();
573
+ if (done) {
574
+ break;
575
+ }
576
+ if (!(value instanceof Uint8Array)) {
577
+ reader.cancel().catch(() => undefined);
578
+ throw new TypeError("A body is bytes");
579
+ }
580
+ size += value.byteLength;
581
+ if (size > limit) {
582
+ reader.cancel().catch(() => undefined);
583
+ return null;
584
+ }
585
+ chunks.push(value);
586
+ }
587
+ const bytes = new Uint8Array(size);
588
+ let at = 0;
589
+ for (const chunk of chunks) {
590
+ bytes.set(chunk, at);
591
+ at += chunk.byteLength;
592
+ }
593
+ // As `Request.json()` decodes: UTF-8, a byte-order mark dropped.
594
+ return new TextDecoder().decode(bytes);
595
+ }
596
+
452
597
  /** The default probe: the runtime's `fetch`, no redirects followed, a timeout. */
453
598
  const fetchProbe: HealthProbe = async (url, timeoutMs) => {
454
599
  const response = await fetch(url, {
@@ -863,6 +1008,10 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
863
1008
  : `Content frames aren't served now: ${view.reason ?? "the content domain is checking"}`,
864
1009
  );
865
1010
  }
1011
+ // Before anything is asked or read: the cheap refusal of a body that says it is too big.
1012
+ if (declaresMoreThan(request, ISSUE_BODY_BYTES)) {
1013
+ return tooLarge();
1014
+ }
866
1015
  let viewer: V | null;
867
1016
  try {
868
1017
  viewer = await viewerOf(request);
@@ -872,14 +1021,20 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
872
1021
  const key =
873
1022
  options.rateLimit?.key?.(request, viewer) ??
874
1023
  (viewer === null
875
- ? `address:${request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for") ?? ""}`
1024
+ ? `address:${clientAddress(request, options.rateLimit?.trustedProxies ?? 0)}`
876
1025
  : `viewer:${JSON.stringify(viewer)}`);
877
1026
  if (!withinRate(key)) {
878
1027
  return refusal(429, "rate-limited", "Too many frames asked for: try again in a minute");
879
1028
  }
1029
+ // Bounded by the bytes read, never by what the request declares (S06, P092): the viewer
1030
+ // may be no one (a public link), and access is asked only once the body says what of.
880
1031
  let body: unknown;
881
1032
  try {
882
- body = await request.json();
1033
+ const text = await boundedText(request, ISSUE_BODY_BYTES);
1034
+ if (text === null) {
1035
+ return tooLarge();
1036
+ }
1037
+ body = JSON.parse(text);
883
1038
  } catch {
884
1039
  return refusal(400, "bad-json", "The body is JSON: { instance }");
885
1040
  }
@@ -36,6 +36,7 @@ export { createServer } from "./server.ts";
36
36
  export {
37
37
  createContentHost,
38
38
  HEALTH_PATH,
39
+ ISSUE_BODY_BYTES,
39
40
  type ContentHealthView,
40
41
  type ContentHost,
41
42
  type ContentHostEvent,
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The address a request came from, as the server that took it saw it: its socket's peer. The Node
3
+ * adapter leaves it on the fetch `Request` under a symbol no client can send (P092), and the issue
4
+ * endpoint's rate limit keys an anonymous viewer by it. No Node API here: `/server` stays free of
5
+ * Node.
6
+ */
7
+ const PEER = Symbol.for("@botiverse/porthole/peer-address");
8
+
9
+ /** Leaves the socket's peer on a request (the Node adapter does). */
10
+ export function withPeerAddress(request: Request, address: string | undefined): Request {
11
+ if (address !== undefined && address !== "") {
12
+ Object.defineProperty(request, PEER, { value: address });
13
+ }
14
+ return request;
15
+ }
16
+
17
+ /** The socket's peer the Node adapter left on a request, or null. */
18
+ export function peerAddress(request: Request): string | null {
19
+ const address: unknown = (request as unknown as Record<symbol, unknown>)[PEER];
20
+ return typeof address === "string" ? address : null;
21
+ }
@@ -164,6 +164,18 @@ function headersOf(input: HeaderInput): Headers {
164
164
  export const isPortholeCookie = (name: string): boolean =>
165
165
  /^(?:__Host-|__Secure-)?porthole-/u.test(name);
166
166
 
167
+ /**
168
+ * Whether a `Set-Cookie` header sets one of Porthole's own names. A nameless cookie
169
+ * (`=__Host-porthole-…=…`) counts by its value: an engine that sends one sends its value alone,
170
+ * which reads as that name (P101).
171
+ */
172
+ export function setsPortholeCookie(header: string): boolean {
173
+ const [pair = ""] = header.split(";");
174
+ const at = pair.indexOf("=");
175
+ const name = (at < 0 ? pair : pair.slice(0, at)).trim();
176
+ return isPortholeCookie(name) || (name === "" && isPortholeCookie(pair.slice(at + 1).trim()));
177
+ }
178
+
167
179
  /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
168
180
  export function withoutPortholeCookies(cookie: string | null | undefined): string | null {
169
181
  const kept = (cookie ?? "")
@@ -210,9 +222,7 @@ export const upstreamHeaders = {
210
222
  options: { readonly origin: string; readonly target: string },
211
223
  ): [string, string][] {
212
224
  const answer = upstreamResponseHeaders(headersOf(input), options.origin, options.target);
213
- const cookies = answer
214
- .getSetCookie()
215
- .filter((each) => !isPortholeCookie(each.split("=")[0]?.trim() ?? ""));
225
+ const cookies = answer.getSetCookie().filter((each) => !setsPortholeCookie(each));
216
226
  answer.delete("set-cookie");
217
227
  return [...answer, ...cookies.map((each): [string, string] => ["set-cookie", each])];
218
228
  },
@@ -14,11 +14,13 @@ import { isHostLabel, reservedLabels } from "./naming.ts";
14
14
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.ts";
15
15
  import { libraryFile } from "./libraries.ts";
16
16
  import { ownLoad, serveAsset, serveFile } from "./files.ts";
17
+ import { isPortholeCookie, setsPortholeCookie } from "./proxy.ts";
17
18
  import {
18
19
  assetCodeRuns,
19
20
  assetCspDirectives,
20
21
  INERT_FILE_CSP,
21
- serializeCsp,
22
+ servedDocumentCsp,
23
+ servedPermissionsPolicy,
22
24
  } from "../compile/policy.ts";
23
25
  import { parseViewer, type ViewerInfo } from "../runtime/levels.ts";
24
26
  import type { FrameBlock } from "../host/types.ts";
@@ -231,19 +233,30 @@ function seconds(value: number | undefined, fallback: number, max: number, what:
231
233
  return value;
232
234
  }
233
235
 
234
- /** The cookies a request carries, as name → values (a name may come twice: partitioned or not). */
236
+ /**
237
+ * The cookies a request carries, as name → values (a name may come twice: partitioned or not).
238
+ * Only spaces and tabs are trimmed, as browsers trim them (P101): a name a sibling set with a
239
+ * leading U+00A0 is no `__Host-` name, though JavaScript's `trim` would make it one.
240
+ */
235
241
  function cookiesOf(request: Request): [string, string][] {
236
242
  const header = request.headers.get("cookie") ?? "";
237
243
  const pairs: [string, string][] = [];
244
+ const blank = /^[ \t]+|[ \t]+$/gu;
238
245
  for (const part of header.split(";")) {
239
246
  const at = part.indexOf("=");
240
247
  if (at > 0) {
241
- pairs.push([part.slice(0, at).trim(), part.slice(at + 1).trim()]);
248
+ pairs.push([part.slice(0, at).replace(blank, ""), part.slice(at + 1).replace(blank, "")]);
242
249
  }
243
250
  }
244
251
  return pairs;
245
252
  }
246
253
 
254
+ /** The artifact version a file set is, for its pages' notices to the host (P098). */
255
+ const versionOf = (instance: InstanceRef): { artifact?: { id: string; version: string } } =>
256
+ instance.document.kind === "artifact"
257
+ ? { artifact: { id: instance.document.id, version: instance.document.version } }
258
+ : {};
259
+
247
260
  /**
248
261
  * Serving for domain, artifact and url modes, and the MCP Apps sandbox proxy (P016, P020): a
249
262
  * fetch-style handler a host's backend mounts in front of its own routes, plus `issue`, which the
@@ -504,10 +517,13 @@ export function createServer(options: ServerOptions): PortholeServer {
504
517
  }
505
518
  }
506
519
 
507
- async function documentOf(
508
- instance: InstanceRef,
509
- ): Promise<
510
- | { readonly html: string; readonly csp: string; readonly compiled?: CompiledConfig }
520
+ async function documentOf(instance: InstanceRef): Promise<
521
+ | {
522
+ readonly html: string;
523
+ readonly compiled: CompiledConfig;
524
+ /** Whether its CSP opens its artifact's asset library (P089): an artifact's page. */
525
+ readonly assets: boolean;
526
+ }
511
527
  | { readonly files: StoredFiles; readonly compiled: CompiledConfig }
512
528
  | null
513
529
  > {
@@ -519,7 +535,11 @@ export function createServer(options: ServerOptions): PortholeServer {
519
535
  const origins = options.hostOrigins;
520
536
  switch (document.kind) {
521
537
  case "shell":
522
- return { html: config.shellDocument({ origins, cspMeta: false }), csp: config.csp };
538
+ return {
539
+ html: config.shellDocument({ origins, cspMeta: false }),
540
+ compiled: config,
541
+ assets: false,
542
+ };
523
543
  case "artifact": {
524
544
  const stored = await options.artifacts?.get(document.id, document.version);
525
545
  if (stored === null || stored === undefined) {
@@ -534,12 +554,12 @@ export function createServer(options: ServerOptions): PortholeServer {
534
554
  }
535
555
  return {
536
556
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
537
- csp: config.csp,
538
557
  compiled: config,
558
+ assets: true,
539
559
  };
540
560
  }
541
561
  case "mcp-proxy":
542
- return { html: sandboxProxyDocument(config, origins), csp: config.csp };
562
+ return { html: sandboxProxyDocument(config, origins), compiled: config, assets: false };
543
563
  case "external":
544
564
  return null;
545
565
  }
@@ -547,8 +567,21 @@ export function createServer(options: ServerOptions): PortholeServer {
547
567
 
548
568
  const cookieName = (key: string): string =>
549
569
  secure ? `__Host-porthole-${key}` : `porthole-${key}`;
570
+ /**
571
+ * Whether a cookie is one this server set, by its name (P101). Over https only `__Host-` names:
572
+ * every label is same-site with every other (P047), and a sibling label (a url-mode app, an
573
+ * app's preview) can set any other name for the whole content domain (`Domain=`), never a
574
+ * `__Host-` one, which the browser keeps to the origin that set it. Over plain http (loopback
575
+ * dev only: `createServer` refuses http elsewhere) the names have no prefix, set and read:
576
+ * `__Host-` needs `Secure`, and WebKit keeps no `Secure` cookie on a tab of http://*.localhost
577
+ * (measured). A sibling there can set the very name, so a copy of one of this label's own
578
+ * sessions or nonces is read: someone must hold one to plant it, on a developer's own server.
579
+ * Another label's session is never this label's, either scheme (its signed scope). Case and
580
+ * every byte count: `__host-` or a name with anything before the prefix is not ours. What
581
+ * Porthole strips from an app's requests and answers is wider (`isPortholeCookie`).
582
+ */
550
583
  const ourCookie = (name: string): boolean =>
551
- name.startsWith("porthole-") || name.startsWith("__Host-porthole-");
584
+ name.startsWith(secure ? "__Host-porthole-" : "porthole-");
552
585
 
553
586
  /**
554
587
  * The cookie a taken ticket buys: this origin only (`__Host-` over https), never readable by the
@@ -591,8 +624,38 @@ export function createServer(options: ServerOptions): PortholeServer {
591
624
 
592
625
  /** The cookie a redirect entry's browser holds while it is away (P068), by its nonce. */
593
626
  const nonceCookie = (nonce: string): string => cookieName(`n-${nonce}`);
594
- /** What an entered path's nonce cookie says after its code was redeemed: the loop guard. */
595
- const enteredMark = (pathname: string): string => `e.${keys.instanceKey({ entered: pathname })}`;
627
+ /**
628
+ * What an entered path's nonce cookie says after its code was redeemed: the loop guard. Its
629
+ * label's and its path's (P101): a mark redeemed on one label, planted on another, is nothing.
630
+ */
631
+ const enteredMark = (label: string, pathname: string): string =>
632
+ `e.${keys.instanceKey({ entered: pathname, label })}`;
633
+
634
+ /**
635
+ * Whether a url-mode app's request may ride its cookie (P101): what the app's own origin asks
636
+ * (its `Origin`, or `Sec-Fetch-Site` `same-origin`; `none` is the person's own address bar),
637
+ * and, where `navigable`, a navigation that opens it (GET or HEAD: the host's frame, a link, a
638
+ * redirect back from sign-in). Another origin (a sibling label's app, another frame on the
639
+ * host's page, an opaque origin's `null`) gets no write, no subresource, no socket. A request
640
+ * with neither header is no browser's (a browser always sends `Origin` on a socket and on a
641
+ * write, and fetch metadata on everything, where it sends them at all).
642
+ */
643
+ function fromItsOwnOrigin(request: Request, label: string, navigable: boolean): boolean {
644
+ const origin = request.headers.get("origin");
645
+ if (origin !== null && origin !== originOfLabel(label)) {
646
+ return false;
647
+ }
648
+ const site = request.headers.get("sec-fetch-site");
649
+ if (site === null || site === "same-origin" || site === "none") {
650
+ return true;
651
+ }
652
+ const method = request.method.toUpperCase();
653
+ return (
654
+ navigable &&
655
+ request.headers.get("sec-fetch-mode") === "navigate" &&
656
+ (method === "GET" || method === "HEAD")
657
+ );
658
+ }
596
659
 
597
660
  /** The access a request's own cookies give on `label`'s origin, for `key`'s instance or the app. */
598
661
  function accessOf(request: Request, label: string, key: string | null): Access | null {
@@ -744,10 +807,12 @@ export function createServer(options: ServerOptions): PortholeServer {
744
807
  }
745
808
  }
746
809
 
747
- function documentHeaders(csp: string): Headers {
810
+ function documentHeaders(csp: string, permissions: string | null): Headers {
748
811
  return new Headers({
749
812
  "content-type": "text/html; charset=utf-8",
750
813
  "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
814
+ // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
815
+ ...(permissions === null ? {} : { "permissions-policy": permissions }),
751
816
  "cache-control": "no-store",
752
817
  "referrer-policy": "no-referrer",
753
818
  "x-content-type-options": "nosniff",
@@ -970,6 +1035,7 @@ export function createServer(options: ServerOptions): PortholeServer {
970
1035
  compiled: served.compiled,
971
1036
  hostOrigins: options.hostOrigins,
972
1037
  frameAncestors,
1038
+ ...versionOf(access.instance),
973
1039
  });
974
1040
  }
975
1041
  // A frame's document (a ticket's): its files carry its access in their path (P083). The
@@ -989,23 +1055,22 @@ export function createServer(options: ServerOptions): PortholeServer {
989
1055
  hostOrigins: options.hostOrigins,
990
1056
  frameAncestors,
991
1057
  ticket: { expires: sealed.expires },
1058
+ ...versionOf(access.instance),
992
1059
  });
993
1060
  }
994
1061
  // One page at a file set's base (P081): its base is the page, nothing under it is.
995
1062
  if (at !== undefined && at.rest !== "") {
996
1063
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
997
1064
  }
998
- // A page that may use its artifact's assets loads them from its own origin (P089).
1065
+ // A page that may use its artifact's assets loads them from its own origin (P089); every
1066
+ // served page carries its frame's sandbox, a tab of its own included (P099).
1067
+ const { config, cspDirectives } = served.compiled;
999
1068
  const headers = documentHeaders(
1000
- served.compiled === undefined
1001
- ? served.csp
1002
- : serializeCsp(
1003
- assetCspDirectives(
1004
- served.compiled.config,
1005
- served.compiled.cspDirectives,
1006
- access.origin,
1007
- ),
1008
- ),
1069
+ servedDocumentCsp(
1070
+ config,
1071
+ served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives,
1072
+ ),
1073
+ servedPermissionsPolicy(config),
1009
1074
  );
1010
1075
  if (cookie !== null) {
1011
1076
  headers.set("set-cookie", cookie);
@@ -1037,7 +1102,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1037
1102
  if (store.bearer === true) {
1038
1103
  const asset = await store.get(id, null);
1039
1104
  return scoped(asset)
1040
- ? serveAsset({ request, asset, frameAncestors, code: asset.trusted === true })
1105
+ ? serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, null) })
1041
1106
  : none();
1042
1107
  }
1043
1108
  const accesses = await assetAccessesOf(request, label);
@@ -1082,9 +1147,28 @@ export function createServer(options: ServerOptions): PortholeServer {
1082
1147
  if (refusal !== null) {
1083
1148
  return refusal;
1084
1149
  }
1085
- const config = compiledFor(access.instance)?.config;
1086
- const code = asset.trusted === true && config !== undefined && assetCodeRuns(config);
1087
- return serveAsset({ request, asset, frameAncestors, code });
1150
+ return serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, access) });
1151
+ }
1152
+
1153
+ /**
1154
+ * Whether a code-typed asset goes out as code (P089, P103): only where it was trusted when it
1155
+ * was uploaded and the config its artifact's page is served under still lets uploaded code
1156
+ * run, asked at every request, so a stricter config wins at once. An access names that config.
1157
+ * By id alone (bearer mode) the server can't tell which of its artifact configs the page is
1158
+ * under: the strictest it might be decides (every one must let uploaded code run).
1159
+ */
1160
+ function runsAsCode(asset: StoredAsset, access: Access | null): boolean {
1161
+ if (asset.trusted !== true) {
1162
+ return false;
1163
+ }
1164
+ if (access !== null) {
1165
+ const config = compiledFor(access.instance)?.config;
1166
+ return config !== undefined && assetCodeRuns(config);
1167
+ }
1168
+ const artifacts = [...compiled.values()]
1169
+ .map((each) => each.config)
1170
+ .filter((config) => config.mode === "artifact" && config.isolation === "domain");
1171
+ return artifacts.length > 0 && artifacts.every((config) => assetCodeRuns(config));
1088
1172
  }
1089
1173
 
1090
1174
  /**
@@ -1195,8 +1279,9 @@ export function createServer(options: ServerOptions): PortholeServer {
1195
1279
  if (path.length > MAX_PATH) {
1196
1280
  return page(414, "Address too long", "This address is too long to open.", method);
1197
1281
  }
1198
- const mark = enteredMark(url.pathname);
1199
- if (cookiesOf(request).some(([name, value]) => ourCookie(name) && value === mark)) {
1282
+ const mark = enteredMark(label, url.pathname);
1283
+ const marked = cookieName("n-");
1284
+ if (cookiesOf(request).some(([name, value]) => name.startsWith(marked) && value === mark)) {
1200
1285
  return page(
1201
1286
  401,
1202
1287
  "Open this in a new tab",
@@ -1304,7 +1389,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1304
1389
  headers.append(
1305
1390
  "set-cookie",
1306
1391
  [
1307
- `${named}=${enteredMark(target.pathname)}`,
1392
+ `${named}=${enteredMark(label, target.pathname)}`,
1308
1393
  "Path=/",
1309
1394
  "HttpOnly",
1310
1395
  `Max-Age=${ENTERED_SECONDS}`,
@@ -1367,7 +1452,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1367
1452
  function forUpstream(request: Request): Request {
1368
1453
  const headers = new Headers(request.headers);
1369
1454
  const kept = cookiesOf(request)
1370
- .filter(([name]) => !ourCookie(name))
1455
+ .filter(([name]) => !isPortholeCookie(name))
1371
1456
  .map(([name, value]) => `${name}=${value}`);
1372
1457
  if (kept.length > 0) {
1373
1458
  headers.set("cookie", kept.join("; "));
@@ -1382,8 +1467,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1382
1467
  const headers = new Headers(response.headers);
1383
1468
  headers.delete("set-cookie");
1384
1469
  for (const cookie of response.headers.getSetCookie()) {
1385
- const name = cookie.split("=")[0]?.trim() ?? "";
1386
- if (!ourCookie(name)) {
1470
+ if (!setsPortholeCookie(cookie)) {
1387
1471
  headers.append("set-cookie", cookie);
1388
1472
  }
1389
1473
  }
@@ -1398,6 +1482,15 @@ export function createServer(options: ServerOptions): PortholeServer {
1398
1482
 
1399
1483
  async function serveApp(request: Request, label: string): Promise<Response> {
1400
1484
  const method = request.method.toUpperCase();
1485
+ // Before the cookie is read: another origin's request is refused whatever it carries.
1486
+ if (!fromItsOwnOrigin(request, label, true)) {
1487
+ return page(
1488
+ 403,
1489
+ "Not from this app",
1490
+ "A request from another site doesn't ride this app's sign-in.",
1491
+ method,
1492
+ );
1493
+ }
1401
1494
  const access = accessOf(request, label, null);
1402
1495
  if (access === null) {
1403
1496
  return page(
@@ -1648,7 +1741,13 @@ export function createServer(options: ServerOptions): PortholeServer {
1648
1741
 
1649
1742
  async access(request) {
1650
1743
  const at = labelOf(request);
1651
- if (at === null || at === "mismatch" || !ours(at.label)) {
1744
+ // A socket is never a navigation: the app's own origin only (P101).
1745
+ if (
1746
+ at === null ||
1747
+ at === "mismatch" ||
1748
+ !ours(at.label) ||
1749
+ !fromItsOwnOrigin(request, at.label, false)
1750
+ ) {
1652
1751
  return null;
1653
1752
  }
1654
1753
  const access = accessOf(request, at.label, null);
@@ -1685,7 +1784,11 @@ export function createServer(options: ServerOptions): PortholeServer {
1685
1784
  return script;
1686
1785
  }
1687
1786
  if (url.pathname === SESSION_PATH) {
1688
- // Whether this request's cookie opens its origin's app: the entry page asks.
1787
+ // Whether this request's cookie opens its origin's app: the entry page asks, from the
1788
+ // app's origin (P101).
1789
+ if (!fromItsOwnOrigin(request, label, false)) {
1790
+ return new Response(null, { status: 403, headers: { "cache-control": "no-store" } });
1791
+ }
1689
1792
  const access = accessOf(request, label, null);
1690
1793
  const status =
1691
1794
  access === null ? 401 : (await denied(request, access)) === null ? 204 : 403;
@@ -163,7 +163,9 @@ export interface StoredAsset {
163
163
  /**
164
164
  * Whether it may run as code (P089, after the review): a script, stylesheet or WebAssembly an
165
165
  * admin uploaded where uploaded code may run (the upload's `trusted`). Any other code-typed
166
- * asset is served as a download, whatever the config says now.
166
+ * asset is served as a download, whatever the config says now; a trusted one too, once the
167
+ * config no longer lets uploaded code run (P103: asked at every request; in bearer mode, every
168
+ * artifact config the server has must).
167
169
  */
168
170
  readonly trusted?: boolean;
169
171
  /** Its file name (its extension types it). */
@@ -322,8 +324,9 @@ export interface PortholeServer {
322
324
  issue(instance: InstanceRef, grant: Grant): Promise<FrameLocation>;
323
325
  /**
324
326
  * The access a request's cookie carries for a url-mode app on the request's origin, or null
325
- * (no good cookie, or the host's check denies it): for a host's own WebSocket upgrade path,
326
- * which a fetch-style handler can't take.
327
+ * (no good cookie, an `Origin` or `Sec-Fetch-Site` of another origin's (P101), or the host's
328
+ * check denies it): for a host's own WebSocket upgrade path, which a fetch-style handler can't
329
+ * take.
327
330
  */
328
331
  access(request: Request): Promise<Access | null>;
329
332
  /** The frame source every content origin matches (`https://*.example-usercontent.com`). */