@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
@@ -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, {
@@ -167,6 +287,11 @@ export function createContentHost(options) {
167
287
  hostOrigins: options.appOrigins,
168
288
  configs,
169
289
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
290
+ ...(options.assets === undefined
291
+ ? {}
292
+ : {
293
+ assets: typeof options.assets === "function" ? { get: options.assets } : options.assets,
294
+ }),
170
295
  ...(options.tickets === undefined ? {} : { tickets: options.tickets }),
171
296
  ...(options.upstream === undefined ? {} : { upstream: options.upstream }),
172
297
  ...(options.entry === undefined
@@ -463,6 +588,10 @@ export function createContentHost(options) {
463
588
  ? "This app serves no content frames"
464
589
  : `Content frames aren't served now: ${view.reason ?? "the content domain is checking"}`);
465
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
+ }
466
595
  let viewer;
467
596
  try {
468
597
  viewer = await viewerOf(request);
@@ -472,14 +601,20 @@ export function createContentHost(options) {
472
601
  }
473
602
  const key = options.rateLimit?.key?.(request, viewer) ??
474
603
  (viewer === null
475
- ? `address:${request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for") ?? ""}`
604
+ ? `address:${clientAddress(request, options.rateLimit?.trustedProxies ?? 0)}`
476
605
  : `viewer:${JSON.stringify(viewer)}`);
477
606
  if (!withinRate(key)) {
478
607
  return refusal(429, "rate-limited", "Too many frames asked for: try again in a minute");
479
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.
480
611
  let body;
481
612
  try {
482
- 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);
483
618
  }
484
619
  catch {
485
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";
@@ -46,4 +46,5 @@ export { statusPageOf as statusPage } from "./pages.ts";
46
46
  export { contentHostFor, type ContentHostFor } from "./bootstrap.ts";
47
47
  export { checkFileSet, DEFAULT_ENTRY, fileLimits, filePathProblem, type FileLimits, type FileSetProblem, } from "../files/paths.ts";
48
48
  export { fileTypeOf, type FileRole, type FileType } from "../files/types.ts";
49
- export type { Access, ArtifactStore, FileBody, StoredFile, StoredFiles, StoredVersion, AuthorizeAnswer, AuthorizeRequest, Authorizer, ContentDomain, EntryState, Grant, PortholeServer, ServerOptions, TicketRecord, TicketStore, Upstream, } from "./types.ts";
49
+ export { pseudonymFor } from "./pseudonym.ts";
50
+ export type { Access, ArtifactStore, AssetStore, StoredAsset, FileBody, StoredFile, StoredFiles, StoredVersion, AuthorizeAnswer, AuthorizeRequest, Authorizer, ContentDomain, EntryState, Grant, PortholeServer, ServerOptions, TicketRecord, TicketStore, Upstream, } from "./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";
@@ -46,3 +46,4 @@ export { contentHostFor } from "./bootstrap.js";
46
46
  // A version made of files (P081): the rules its paths follow, its limits and its types.
47
47
  export { checkFileSet, DEFAULT_ENTRY, fileLimits, filePathProblem, } from "../files/paths.js";
48
48
  export { fileTypeOf } from "../files/types.js";
49
+ export { pseudonymFor } from "./pseudonym.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
  },
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A person's id for one artifact's pages (P087, after the review): what `Grant.user.id` may be
3
+ * where pages shouldn't learn the account id or link one person across artifacts. Stable for the
4
+ * same secret, artifact and person (their `data/users/<id>` stays theirs across visits), a
5
+ * different one on every other artifact, not reversible without the secret. 26 lowercase base32
6
+ * characters: one db path segment. The secret is the host's (at least 32 random bytes); keep it
7
+ * apart from Porthole's server secret.
8
+ */
9
+ export declare function pseudonymFor(secret: Uint8Array, artifact: string, person: string): string;
@@ -0,0 +1,20 @@
1
+ import { hmacSha256, utf8 } from "./crypto.js";
2
+ import { base32 } from "./keys.js";
3
+ /**
4
+ * A person's id for one artifact's pages (P087, after the review): what `Grant.user.id` may be
5
+ * where pages shouldn't learn the account id or link one person across artifacts. Stable for the
6
+ * same secret, artifact and person (their `data/users/<id>` stays theirs across visits), a
7
+ * different one on every other artifact, not reversible without the secret. 26 lowercase base32
8
+ * characters: one db path segment. The secret is the host's (at least 32 random bytes); keep it
9
+ * apart from Porthole's server secret.
10
+ */
11
+ export function pseudonymFor(secret, artifact, person) {
12
+ if (!(secret instanceof Uint8Array) || secret.length < 32) {
13
+ throw new TypeError("pseudonymFor needs a secret of at least 32 random bytes");
14
+ }
15
+ if (artifact === "" || person === "") {
16
+ throw new TypeError("pseudonymFor needs an artifact and a person");
17
+ }
18
+ const mac = hmacSha256(secret, utf8(`porthole/pseudonym\u0000${artifact}\u0000${person}`));
19
+ return base32(mac.slice(0, 16)).slice(0, 26);
20
+ }
@@ -1,7 +1,2 @@
1
1
  import type { PortholeServer, ServerOptions } from "./types.ts";
2
- /**
3
- * Serving for domain, artifact and url modes, and the MCP Apps sandbox proxy (P016, P020): a
4
- * fetch-style handler a host's backend mounts in front of its own routes, plus `issue`, which the
5
- * host's authenticated API calls once it has decided a viewer may see an instance.
6
- */
7
2
  export declare function createServer(options: ServerOptions): PortholeServer;