@botiverse/porthole 0.7.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 (153) hide show
  1. package/README.md +9 -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 +25 -5
  6. package/dist/bridge/bridge.js +311 -73
  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.js +1 -0
  12. package/dist/bridge/types.d.ts +32 -1
  13. package/dist/check/page-source.js +1 -1
  14. package/dist/check/page.js +2 -0
  15. package/dist/compile/compile.d.ts +6 -0
  16. package/dist/compile/compile.js +3 -1
  17. package/dist/compile/policy.d.ts +38 -2
  18. package/dist/compile/policy.js +122 -7
  19. package/dist/config/capabilities.d.ts +23 -4
  20. package/dist/config/capabilities.js +12 -2
  21. package/dist/config/schema.d.ts +11 -0
  22. package/dist/config/validate.d.ts +8 -2
  23. package/dist/config/validate.js +28 -6
  24. package/dist/config/warnings.d.ts +20 -0
  25. package/dist/config/warnings.js +25 -0
  26. package/dist/conformance/behavior.js +46 -1
  27. package/dist/conformance/cookies.d.ts +15 -0
  28. package/dist/conformance/cookies.js +80 -0
  29. package/dist/conformance/harness/page.d.ts +1 -0
  30. package/dist/conformance/harness/page.js +9 -2
  31. package/dist/conformance/harness-source.js +1 -1
  32. package/dist/conformance/host-kit.js +5 -1
  33. package/dist/conformance/index.d.ts +10 -0
  34. package/dist/conformance/limits.js +38 -1
  35. package/dist/conformance/runtime.js +10 -0
  36. package/dist/conformance/served.d.ts +2 -0
  37. package/dist/conformance/served.js +737 -4
  38. package/dist/files/paths.js +4 -0
  39. package/dist/guide/gates.d.ts +7 -1
  40. package/dist/guide/gates.js +12 -0
  41. package/dist/guide/guide.js +2 -2
  42. package/dist/guide/runtime.js +11 -3
  43. package/dist/host/create-host.js +49 -37
  44. package/dist/host/pages-of-set.d.ts +43 -0
  45. package/dist/host/pages-of-set.js +196 -0
  46. package/dist/host/types.d.ts +8 -1
  47. package/dist/index.d.ts +5 -4
  48. package/dist/index.js +3 -2
  49. package/dist/mcp/adapter.js +11 -15
  50. package/dist/node/index.d.ts +36 -4
  51. package/dist/node/index.js +402 -101
  52. package/dist/presets/presets.d.ts +16 -8
  53. package/dist/presets/presets.js +39 -8
  54. package/dist/protocol/live-data.d.ts +6 -2
  55. package/dist/protocol/live-data.js +20 -1
  56. package/dist/protocol/mcp-apps.d.ts +13 -2
  57. package/dist/protocol/mcp-apps.js +10 -2
  58. package/dist/protocol/message-text.d.ts +8 -0
  59. package/dist/protocol/message-text.js +29 -0
  60. package/dist/protocol/runtime-calls.js +3 -0
  61. package/dist/protocol/shell-adapter.js +16 -22
  62. package/dist/react/context-notice.d.ts +32 -0
  63. package/dist/react/context-notice.js +28 -0
  64. package/dist/react/dialog.js +62 -18
  65. package/dist/react/frame.d.ts +12 -1
  66. package/dist/react/frame.js +79 -2
  67. package/dist/react/index.d.ts +2 -1
  68. package/dist/react/index.js +2 -1
  69. package/dist/runtime/contract.d.ts +9 -1
  70. package/dist/runtime/contract.js +31 -2
  71. package/dist/runtime/db.d.ts +41 -6
  72. package/dist/runtime/db.js +120 -16
  73. package/dist/runtime/declaration.d.ts +15 -1
  74. package/dist/runtime/declaration.js +184 -87
  75. package/dist/runtime/requests.js +27 -11
  76. package/dist/runtime/types.generated.js +1 -1
  77. package/dist/server/files.d.ts +5 -0
  78. package/dist/server/files.js +22 -7
  79. package/dist/server/host.d.ts +18 -1
  80. package/dist/server/host.js +132 -2
  81. package/dist/server/index.d.ts +1 -1
  82. package/dist/server/index.js +1 -1
  83. package/dist/server/peer.d.ts +4 -0
  84. package/dist/server/peer.js +19 -0
  85. package/dist/server/proxy.d.ts +6 -0
  86. package/dist/server/proxy.js +12 -3
  87. package/dist/server/server.js +113 -26
  88. package/dist/server/types.d.ts +6 -3
  89. package/dist/shell/document.d.ts +8 -0
  90. package/dist/shell/document.js +3 -0
  91. package/dist/shell/runtime.js +361 -14
  92. package/docs/ADOPTING.md +119 -14
  93. package/docs/ARCHITECTURE.md +13 -3
  94. package/docs/DECISIONS.md +1455 -8
  95. package/docs/DESIGN.md +79 -25
  96. package/docs/THREAT_MODEL.md +616 -0
  97. package/package.json +14 -3
  98. package/src/bridge/bounded-text.ts +240 -0
  99. package/src/bridge/bridge.ts +373 -84
  100. package/src/bridge/json-data.ts +95 -0
  101. package/src/bridge/navigation.ts +10 -0
  102. package/src/bridge/refusal.ts +1 -0
  103. package/src/bridge/types.ts +30 -1
  104. package/src/check/page.ts +2 -0
  105. package/src/compile/compile.ts +9 -1
  106. package/src/compile/policy.ts +130 -7
  107. package/src/config/capabilities.ts +22 -3
  108. package/src/config/schema.ts +11 -0
  109. package/src/config/validate.ts +43 -5
  110. package/src/config/warnings.ts +42 -0
  111. package/src/conformance/behavior.ts +54 -1
  112. package/src/conformance/cookies.ts +93 -0
  113. package/src/conformance/harness/page.ts +11 -2
  114. package/src/conformance/host-kit.ts +10 -1
  115. package/src/conformance/index.ts +10 -0
  116. package/src/conformance/limits.ts +39 -1
  117. package/src/conformance/runtime.ts +21 -0
  118. package/src/conformance/served.ts +888 -4
  119. package/src/files/paths.ts +4 -0
  120. package/src/guide/gates.ts +13 -1
  121. package/src/guide/guide.ts +3 -3
  122. package/src/guide/runtime.ts +12 -3
  123. package/src/host/create-host.ts +54 -36
  124. package/src/host/pages-of-set.ts +226 -0
  125. package/src/host/types.ts +15 -1
  126. package/src/index.ts +5 -0
  127. package/src/mcp/adapter.ts +16 -20
  128. package/src/node/index.ts +507 -116
  129. package/src/presets/presets.ts +60 -17
  130. package/src/protocol/live-data.ts +31 -3
  131. package/src/protocol/mcp-apps.ts +11 -2
  132. package/src/protocol/message-text.ts +36 -0
  133. package/src/protocol/runtime-calls.ts +3 -0
  134. package/src/protocol/shell-adapter.ts +27 -23
  135. package/src/react/context-notice.tsx +95 -0
  136. package/src/react/dialog.tsx +77 -17
  137. package/src/react/frame.tsx +101 -0
  138. package/src/react/index.ts +8 -1
  139. package/src/runtime/contract.ts +36 -2
  140. package/src/runtime/db.ts +140 -20
  141. package/src/runtime/declaration.ts +227 -89
  142. package/src/runtime/requests.ts +27 -11
  143. package/src/runtime/types.generated.ts +1 -1
  144. package/src/server/files.ts +29 -11
  145. package/src/server/host.ts +158 -3
  146. package/src/server/index.ts +1 -0
  147. package/src/server/peer.ts +21 -0
  148. package/src/server/proxy.ts +13 -3
  149. package/src/server/server.ts +139 -36
  150. package/src/server/types.ts +6 -3
  151. package/src/shell/document.ts +8 -0
  152. package/src/shell/runtime.ts +361 -14
  153. package/types/runtime/v1/context.d.ts +13 -2
@@ -2,6 +2,7 @@ import { embedderFrameSourcesOf } from "../compile/policy.js";
2
2
  import { base64url, fromBase64url, fromUtf8, hmacSha256, timingSafeEqual, utf8 } from "./crypto.js";
3
3
  import { ContentDomainError, contentDomain, serverDomain, } from "./domain.js";
4
4
  import { reservedLabels } from "./naming.js";
5
+ import { peerAddress } from "./peer.js";
5
6
  import { appStatusPage } from "./pages.js";
6
7
  import { createServer } from "./server.js";
7
8
  /**
@@ -95,6 +96,125 @@ const authorizeSource = (url) => {
95
96
  const parsed = new URL(url);
96
97
  return `${parsed.origin}${parsed.pathname}`;
97
98
  };
99
+ /**
100
+ * The most an issue request's body may be (S06, P092). `{ instance }` is a few hundred bytes; an
101
+ * MCP view's declared egress, the largest proposal, a few KiB.
102
+ */
103
+ export const ISSUE_BODY_BYTES = 65_536;
104
+ /** Whether a request came through Workers: Cloudflare's own `cf`, which no client can send. */
105
+ const onWorkers = (request) => {
106
+ const cf = request.cf;
107
+ return typeof cf === "object" && cf !== null;
108
+ };
109
+ /**
110
+ * The address an anonymous viewer's rate is keyed by (P092): one the host trusts, never what a
111
+ * client says. Behind `trustedProxies` proxies, the X-Forwarded-For entry the outermost appended
112
+ * (a header with fewer entries came past them: its peer); else the socket's peer, as the Node
113
+ * adapter saw it; on Workers, CF-Connecting-IP (Cloudflare's edge sets it); else none known.
114
+ */
115
+ function clientAddress(request, trustedProxies) {
116
+ if (trustedProxies > 0) {
117
+ const hops = (request.headers.get("x-forwarded-for") ?? "")
118
+ .split(",")
119
+ .map((hop) => hop.trim())
120
+ .filter((hop) => hop !== "");
121
+ const hop = hops[hops.length - trustedProxies];
122
+ if (hop !== undefined) {
123
+ return clientOf(hop);
124
+ }
125
+ }
126
+ const peer = peerAddress(request);
127
+ if (peer !== null) {
128
+ return clientOf(peer);
129
+ }
130
+ const edge = onWorkers(request) ? request.headers.get("cf-connecting-ip") : null;
131
+ return edge === null || edge === "" ? "unknown" : clientOf(edge);
132
+ }
133
+ /** An IPv6 address's groups (8; an embedded IPv4 tail as two), or null where it is no IPv6. */
134
+ function ipv6Groups(address) {
135
+ const halves = address.toLowerCase().split("::");
136
+ if (halves.length > 2) {
137
+ return null;
138
+ }
139
+ const groupsOf = (part) => part === undefined || part === ""
140
+ ? []
141
+ : part.split(":").flatMap((group) => (group.includes(".") ? ["0", "0"] : [group]));
142
+ const head = groupsOf(halves[0]);
143
+ const tail = groupsOf(halves[1]);
144
+ const groups = halves.length === 2
145
+ ? [...head, ...Array(Math.max(0, 8 - head.length - tail.length)).fill("0"), ...tail]
146
+ : head;
147
+ return groups.length === 8 && groups.every((group) => /^[0-9a-f]{1,4}$/u.test(group))
148
+ ? groups
149
+ : null;
150
+ }
151
+ /**
152
+ * The part of an address that names one client (P092): an IPv6 address by its /64, since a host
153
+ * or a subscriber is given a /64 and rotating addresses within it costs nothing (one key each
154
+ * would let one client fill the limiter and wipe every bucket); an IPv4-mapped one as its IPv4;
155
+ * anything else as it is.
156
+ */
157
+ function clientOf(address) {
158
+ const bare = (address.startsWith("[") ? address.slice(1, address.indexOf("]")) : address).split("%")[0];
159
+ if (bare === undefined || !bare.includes(":")) {
160
+ return address;
161
+ }
162
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/iu.exec(bare)?.[1];
163
+ if (mapped !== undefined) {
164
+ return mapped;
165
+ }
166
+ const groups = ipv6Groups(bare);
167
+ return groups === null
168
+ ? address
169
+ : `${groups
170
+ .slice(0, 4)
171
+ .map((group) => group.replace(/^0+(?=.)/u, ""))
172
+ .join(":")}::/64`;
173
+ }
174
+ const tooLarge = () => refusal(413, "too-large", `The body is { instance }: at most ${ISSUE_BODY_BYTES} bytes`);
175
+ /** Whether a request declares a body longer than `limit` (an early refusal; never the bound). */
176
+ const declaresMoreThan = (request, limit) => {
177
+ const declared = request.headers.get("content-length")?.trim() ?? "";
178
+ return /^\d+$/u.test(declared) && Number(declared) > limit;
179
+ };
180
+ /**
181
+ * A request's body as text, reading at most `limit` bytes (S06, P092): past it the read stops,
182
+ * the body is cancelled, and the answer is null. The bytes read are counted, whatever the
183
+ * request's Content-Length says (absent, chunked, or not the truth). Throws where the body can't
184
+ * be read (the client went away mid-way).
185
+ */
186
+ async function boundedText(request, limit) {
187
+ if (request.body === null) {
188
+ return "";
189
+ }
190
+ const reader = request.body.getReader();
191
+ const chunks = [];
192
+ let size = 0;
193
+ for (;;) {
194
+ const { done, value } = await reader.read();
195
+ if (done) {
196
+ break;
197
+ }
198
+ if (!(value instanceof Uint8Array)) {
199
+ reader.cancel().catch(() => undefined);
200
+ throw new TypeError("A body is bytes");
201
+ }
202
+ size += value.byteLength;
203
+ if (size > limit) {
204
+ reader.cancel().catch(() => undefined);
205
+ return null;
206
+ }
207
+ chunks.push(value);
208
+ }
209
+ const bytes = new Uint8Array(size);
210
+ let at = 0;
211
+ for (const chunk of chunks) {
212
+ bytes.set(chunk, at);
213
+ at += chunk.byteLength;
214
+ }
215
+ // As `Request.json()` decodes: UTF-8, a byte-order mark dropped.
216
+ return new TextDecoder().decode(bytes);
217
+ }
98
218
  /** The default probe: the runtime's `fetch`, no redirects followed, a timeout. */
99
219
  const fetchProbe = async (url, timeoutMs) => {
100
220
  const response = await fetch(url, {
@@ -468,6 +588,10 @@ export function createContentHost(options) {
468
588
  ? "This app serves no content frames"
469
589
  : `Content frames aren't served now: ${view.reason ?? "the content domain is checking"}`);
470
590
  }
591
+ // Before anything is asked or read: the cheap refusal of a body that says it is too big.
592
+ if (declaresMoreThan(request, ISSUE_BODY_BYTES)) {
593
+ return tooLarge();
594
+ }
471
595
  let viewer;
472
596
  try {
473
597
  viewer = await viewerOf(request);
@@ -477,14 +601,20 @@ export function createContentHost(options) {
477
601
  }
478
602
  const key = options.rateLimit?.key?.(request, viewer) ??
479
603
  (viewer === null
480
- ? `address:${request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for") ?? ""}`
604
+ ? `address:${clientAddress(request, options.rateLimit?.trustedProxies ?? 0)}`
481
605
  : `viewer:${JSON.stringify(viewer)}`);
482
606
  if (!withinRate(key)) {
483
607
  return refusal(429, "rate-limited", "Too many frames asked for: try again in a minute");
484
608
  }
609
+ // Bounded by the bytes read, never by what the request declares (S06, P092): the viewer
610
+ // may be no one (a public link), and access is asked only once the body says what of.
485
611
  let body;
486
612
  try {
487
- body = await request.json();
613
+ const text = await boundedText(request, ISSUE_BODY_BYTES);
614
+ if (text === null) {
615
+ return tooLarge();
616
+ }
617
+ body = JSON.parse(text);
488
618
  }
489
619
  catch {
490
620
  return refusal(400, "bad-json", "The body is JSON: { instance }");
@@ -33,7 +33,7 @@
33
33
  * content without a valid ticket or cookie gets nothing of the content.
34
34
  */
35
35
  export { createServer } from "./server.ts";
36
- export { createContentHost, HEALTH_PATH, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, ASSET_LIBRARY_PATH, type FileAddress, isFileAddress, versionBase, versionedAddress, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
36
+ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, ASSET_LIBRARY_PATH, type FileAddress, isFileAddress, versionBase, versionedAddress, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
@@ -33,7 +33,7 @@
33
33
  * content without a valid ticket or cookie gets nothing of the content.
34
34
  */
35
35
  export { createServer } from "./server.js";
36
- export { createContentHost, HEALTH_PATH, ASSET_LIBRARY_PATH, isFileAddress, versionBase, versionedAddress, } from "./host.js";
36
+ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, ASSET_LIBRARY_PATH, isFileAddress, versionBase, versionedAddress, } from "./host.js";
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domain.js";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.js";
@@ -0,0 +1,4 @@
1
+ /** Leaves the socket's peer on a request (the Node adapter does). */
2
+ export declare function withPeerAddress(request: Request, address: string | undefined): Request;
3
+ /** The socket's peer the Node adapter left on a request, or null. */
4
+ export declare function peerAddress(request: Request): string | null;
@@ -0,0 +1,19 @@
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
+ /** Leaves the socket's peer on a request (the Node adapter does). */
9
+ export function withPeerAddress(request, address) {
10
+ if (address !== undefined && address !== "") {
11
+ Object.defineProperty(request, PEER, { value: address });
12
+ }
13
+ return request;
14
+ }
15
+ /** The socket's peer the Node adapter left on a request, or null. */
16
+ export function peerAddress(request) {
17
+ const address = request[PEER];
18
+ return typeof address === "string" ? address : null;
19
+ }
@@ -22,6 +22,12 @@ export declare function proxyTo(options?: ProxyOptions): Upstream;
22
22
  type HeaderInput = Headers | Iterable<readonly [string, string]> | Readonly<Record<string, string | readonly string[] | undefined>>;
23
23
  /** Whether a cookie is Porthole's own (sessions, entry nonces, the handoff). */
24
24
  export declare const isPortholeCookie: (name: string) => boolean;
25
+ /**
26
+ * Whether a `Set-Cookie` header sets one of Porthole's own names. A nameless cookie
27
+ * (`=__Host-porthole-…=…`) counts by its value: an engine that sends one sends its value alone,
28
+ * which reads as that name (P101).
29
+ */
30
+ export declare function setsPortholeCookie(header: string): boolean;
25
31
  /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
26
32
  export declare function withoutPortholeCookies(cookie: string | null | undefined): string | null;
27
33
  /**
@@ -127,6 +127,17 @@ function headersOf(input) {
127
127
  }
128
128
  /** Whether a cookie is Porthole's own (sessions, entry nonces, the handoff). */
129
129
  export const isPortholeCookie = (name) => /^(?:__Host-|__Secure-)?porthole-/u.test(name);
130
+ /**
131
+ * Whether a `Set-Cookie` header sets one of Porthole's own names. A nameless cookie
132
+ * (`=__Host-porthole-…=…`) counts by its value: an engine that sends one sends its value alone,
133
+ * which reads as that name (P101).
134
+ */
135
+ export function setsPortholeCookie(header) {
136
+ const [pair = ""] = header.split(";");
137
+ const at = pair.indexOf("=");
138
+ const name = (at < 0 ? pair : pair.slice(0, at)).trim();
139
+ return isPortholeCookie(name) || (name === "" && isPortholeCookie(pair.slice(at + 1).trim()));
140
+ }
130
141
  /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
131
142
  export function withoutPortholeCookies(cookie) {
132
143
  const kept = (cookie ?? "")
@@ -167,9 +178,7 @@ export const upstreamHeaders = {
167
178
  },
168
179
  response(input, options) {
169
180
  const answer = upstreamResponseHeaders(headersOf(input), options.origin, options.target);
170
- const cookies = answer
171
- .getSetCookie()
172
- .filter((each) => !isPortholeCookie(each.split("=")[0]?.trim() ?? ""));
181
+ const cookies = answer.getSetCookie().filter((each) => !setsPortholeCookie(each));
173
182
  answer.delete("set-cookie");
174
183
  return [...answer, ...cookies.map((each) => ["set-cookie", each])];
175
184
  },
@@ -7,7 +7,8 @@ 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
9
  import { ownLoad, serveAsset, serveFile } from "./files.js";
10
- import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, serializeCsp, } from "../compile/policy.js";
10
+ import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
11
+ import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
11
12
  import { parseViewer } from "../runtime/levels.js";
12
13
  import { memoryTicketStore } from "./tickets.js";
13
14
  /**
@@ -164,18 +165,27 @@ function seconds(value, fallback, max, what) {
164
165
  }
165
166
  return value;
166
167
  }
167
- /** 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
+ */
168
173
  function cookiesOf(request) {
169
174
  const header = request.headers.get("cookie") ?? "";
170
175
  const pairs = [];
176
+ const blank = /^[ \t]+|[ \t]+$/gu;
171
177
  for (const part of header.split(";")) {
172
178
  const at = part.indexOf("=");
173
179
  if (at > 0) {
174
- 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, "")]);
175
181
  }
176
182
  }
177
183
  return pairs;
178
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
+ : {};
179
189
  /**
180
190
  * Serving for domain, artifact and url modes, and the MCP Apps sandbox proxy (P016, P020): a
181
191
  * fetch-style handler a host's backend mounts in front of its own routes, plus `issue`, which the
@@ -396,7 +406,11 @@ export function createServer(options) {
396
406
  const origins = options.hostOrigins;
397
407
  switch (document.kind) {
398
408
  case "shell":
399
- 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
+ };
400
414
  case "artifact": {
401
415
  const stored = await options.artifacts?.get(document.id, document.version);
402
416
  if (stored === null || stored === undefined) {
@@ -411,18 +425,31 @@ export function createServer(options) {
411
425
  }
412
426
  return {
413
427
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
414
- csp: config.csp,
415
428
  compiled: config,
429
+ assets: true,
416
430
  };
417
431
  }
418
432
  case "mcp-proxy":
419
- return { html: sandboxProxyDocument(config, origins), csp: config.csp };
433
+ return { html: sandboxProxyDocument(config, origins), compiled: config, assets: false };
420
434
  case "external":
421
435
  return null;
422
436
  }
423
437
  }
424
438
  const cookieName = (key) => secure ? `__Host-porthole-${key}` : `porthole-${key}`;
425
- 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-");
426
453
  /**
427
454
  * The cookie a taken ticket buys: this origin only (`__Host-` over https), never readable by the
428
455
  * content (`HttpOnly`). In a frame it is a third party's: `SameSite=None`, partitioned by the
@@ -458,8 +485,34 @@ export function createServer(options) {
458
485
  }
459
486
  /** The cookie a redirect entry's browser holds while it is away (P068), by its nonce. */
460
487
  const nonceCookie = (nonce) => cookieName(`n-${nonce}`);
461
- /** What an entered path's nonce cookie says after its code was redeemed: the loop guard. */
462
- 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
+ }
463
516
  /** The access a request's own cookies give on `label`'s origin, for `key`'s instance or the app. */
464
517
  function accessOf(request, label, key) {
465
518
  let best = null;
@@ -595,10 +648,12 @@ export function createServer(options) {
595
648
  return null;
596
649
  }
597
650
  }
598
- function documentHeaders(csp) {
651
+ function documentHeaders(csp, permissions) {
599
652
  return new Headers({
600
653
  "content-type": "text/html; charset=utf-8",
601
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 }),
602
657
  "cache-control": "no-store",
603
658
  "referrer-policy": "no-referrer",
604
659
  "x-content-type-options": "nosniff",
@@ -774,6 +829,7 @@ export function createServer(options) {
774
829
  compiled: served.compiled,
775
830
  hostOrigins: options.hostOrigins,
776
831
  frameAncestors,
832
+ ...versionOf(access.instance),
777
833
  });
778
834
  }
779
835
  // A frame's document (a ticket's): its files carry its access in their path (P083). The
@@ -793,16 +849,17 @@ export function createServer(options) {
793
849
  hostOrigins: options.hostOrigins,
794
850
  frameAncestors,
795
851
  ticket: { expires: sealed.expires },
852
+ ...versionOf(access.instance),
796
853
  });
797
854
  }
798
855
  // One page at a file set's base (P081): its base is the page, nothing under it is.
799
856
  if (at !== undefined && at.rest !== "") {
800
857
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
801
858
  }
802
- // A page that may use its artifact's assets loads them from its own origin (P089).
803
- const headers = documentHeaders(served.compiled === undefined
804
- ? served.csp
805
- : serializeCsp(assetCspDirectives(served.compiled.config, served.compiled.cspDirectives, access.origin)));
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));
806
863
  if (cookie !== null) {
807
864
  headers.set("set-cookie", cookie);
808
865
  }
@@ -833,7 +890,7 @@ export function createServer(options) {
833
890
  if (store.bearer === true) {
834
891
  const asset = await store.get(id, null);
835
892
  return scoped(asset)
836
- ? serveAsset({ request, asset, frameAncestors, code: asset.trusted === true })
893
+ ? serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, null) })
837
894
  : none();
838
895
  }
839
896
  const accesses = await assetAccessesOf(request, label);
@@ -873,9 +930,27 @@ export function createServer(options) {
873
930
  if (refusal !== null) {
874
931
  return refusal;
875
932
  }
876
- const config = compiledFor(access.instance)?.config;
877
- const code = asset.trusted === true && config !== undefined && assetCodeRuns(config);
878
- return serveAsset({ request, asset, frameAncestors, code });
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));
879
954
  }
880
955
  /**
881
956
  * The accesses a request carries to artifacts of `label`'s origin, most specific first: the
@@ -975,8 +1050,9 @@ export function createServer(options) {
975
1050
  if (path.length > MAX_PATH) {
976
1051
  return page(414, "Address too long", "This address is too long to open.", method);
977
1052
  }
978
- const mark = enteredMark(url.pathname);
979
- 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)) {
980
1056
  return page(401, "Open this in a new tab", "This browser keeps no sign-in for it inside a frame.", method, "cookies");
981
1057
  }
982
1058
  const nonce = base32(randomBytes(10));
@@ -1056,7 +1132,7 @@ export function createServer(options) {
1056
1132
  ? { b: base, ...(pinned === true ? { k: 1 } : {}) }
1057
1133
  : { p: target.pathname }));
1058
1134
  headers.append("set-cookie", [
1059
- `${named}=${enteredMark(target.pathname)}`,
1135
+ `${named}=${enteredMark(label, target.pathname)}`,
1060
1136
  "Path=/",
1061
1137
  "HttpOnly",
1062
1138
  `Max-Age=${ENTERED_SECONDS}`,
@@ -1105,7 +1181,7 @@ export function createServer(options) {
1105
1181
  function forUpstream(request) {
1106
1182
  const headers = new Headers(request.headers);
1107
1183
  const kept = cookiesOf(request)
1108
- .filter(([name]) => !ourCookie(name))
1184
+ .filter(([name]) => !isPortholeCookie(name))
1109
1185
  .map(([name, value]) => `${name}=${value}`);
1110
1186
  if (kept.length > 0) {
1111
1187
  headers.set("cookie", kept.join("; "));
@@ -1120,8 +1196,7 @@ export function createServer(options) {
1120
1196
  const headers = new Headers(response.headers);
1121
1197
  headers.delete("set-cookie");
1122
1198
  for (const cookie of response.headers.getSetCookie()) {
1123
- const name = cookie.split("=")[0]?.trim() ?? "";
1124
- if (!ourCookie(name)) {
1199
+ if (!setsPortholeCookie(cookie)) {
1125
1200
  headers.append("set-cookie", cookie);
1126
1201
  }
1127
1202
  }
@@ -1135,6 +1210,10 @@ export function createServer(options) {
1135
1210
  }
1136
1211
  async function serveApp(request, label) {
1137
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
+ }
1138
1217
  const access = accessOf(request, label, null);
1139
1218
  if (access === null) {
1140
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");
@@ -1341,7 +1420,11 @@ export function createServer(options) {
1341
1420
  },
1342
1421
  async access(request) {
1343
1422
  const at = labelOf(request);
1344
- 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)) {
1345
1428
  return null;
1346
1429
  }
1347
1430
  const access = accessOf(request, at.label, null);
@@ -1372,7 +1455,11 @@ export function createServer(options) {
1372
1455
  return script;
1373
1456
  }
1374
1457
  if (url.pathname === SESSION_PATH) {
1375
- // 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
+ }
1376
1463
  const access = accessOf(request, label, null);
1377
1464
  const status = access === null ? 401 : (await denied(request, access)) === null ? 204 : 403;
1378
1465
  return new Response(null, { status, headers: { "cache-control": "no-store" } });
@@ -156,7 +156,9 @@ export interface StoredAsset {
156
156
  /**
157
157
  * Whether it may run as code (P089, after the review): a script, stylesheet or WebAssembly an
158
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.
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).
160
162
  */
161
163
  readonly trusted?: boolean;
162
164
  /** Its file name (its extension types it). */
@@ -305,8 +307,9 @@ export interface PortholeServer {
305
307
  issue(instance: InstanceRef, grant: Grant): Promise<FrameLocation>;
306
308
  /**
307
309
  * The access a request's cookie carries for a url-mode app on the request's origin, or null
308
- * (no good cookie, or the host's check denies it): for a host's own WebSocket upgrade path,
309
- * 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.
310
313
  */
311
314
  access(request: Request): Promise<Access | null>;
312
315
  /** The frame source every content origin matches (`https://*.example-usercontent.com`). */
@@ -47,6 +47,14 @@ export interface ShellDocumentOptions {
47
47
  * renews it before then, at `<base>__porthole/renew`, and moves the page there.
48
48
  */
49
49
  readonly expires?: number;
50
+ /**
51
+ * The artifact version the files are (P098): the shell names it in its notices, and the host
52
+ * takes a notice only for the version it mounted. Not secret; the content can read it.
53
+ */
54
+ readonly set?: {
55
+ readonly id: string;
56
+ readonly version: string;
57
+ };
50
58
  };
51
59
  }
52
60
  /**
@@ -105,6 +105,9 @@ export function shellDocument(plan, csp, options) {
105
105
  base: options.files.base,
106
106
  ...(options.files.address === undefined ? {} : { address: options.files.address }),
107
107
  ...(options.files.expires === undefined ? {} : { expires: options.files.expires }),
108
+ ...(options.files.set === undefined
109
+ ? {}
110
+ : { set: { id: options.files.set.id, version: options.files.set.version } }),
108
111
  },
109
112
  }),
110
113
  }));