@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
@@ -11,11 +11,13 @@ 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 {
17
18
  Access,
18
19
  ArtifactStore,
20
+ AssetStore,
19
21
  AuthorizeAnswer,
20
22
  AuthorizeRequest,
21
23
  Grant,
@@ -156,6 +158,11 @@ export interface ContentHostOptions<V> {
156
158
  readonly authorizeTtlSeconds?: number;
157
159
  /** Policy 4, source: a stored page by id and version (artifact documents). */
158
160
  readonly source?: ArtifactStore["get"];
161
+ /**
162
+ * Policy 5, assets (P089): an artifact's asset library by id, served at `/_blob/<id>` to an
163
+ * access for its artifact; or the store itself, with `bearer` (an explicit opt-in).
164
+ */
165
+ readonly assets?: AssetStore["get"] | AssetStore;
159
166
  readonly upstream?: Upstream;
160
167
  /**
161
168
  * The health gate, and with it the opaque fallback (P066): the kit checks the content domain
@@ -164,10 +171,22 @@ export interface ContentHostOptions<V> {
164
171
  * served throw at startup.
165
172
  */
166
173
  readonly health?: HealthOptions;
167
- /** 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
+ */
168
181
  readonly rateLimit?: {
169
182
  readonly perMinute: number;
170
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;
171
190
  };
172
191
  /** The kit's events: a function, or a logger (`{ info, warn, error }`). */
173
192
  readonly log?: ((event: ContentHostEvent) => void) | ContentLogger;
@@ -443,6 +462,138 @@ const authorizeSource = (url: string): string => {
443
462
  return `${parsed.origin}${parsed.pathname}`;
444
463
  };
445
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
+
446
597
  /** The default probe: the runtime's `fetch`, no redirects followed, a timeout. */
447
598
  const fetchProbe: HealthProbe = async (url, timeoutMs) => {
448
599
  const response = await fetch(url, {
@@ -527,6 +678,12 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
527
678
  hostOrigins: options.appOrigins,
528
679
  configs,
529
680
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
681
+ ...(options.assets === undefined
682
+ ? {}
683
+ : {
684
+ assets:
685
+ typeof options.assets === "function" ? { get: options.assets } : options.assets,
686
+ }),
530
687
  ...(options.tickets === undefined ? {} : { tickets: options.tickets }),
531
688
  ...(options.upstream === undefined ? {} : { upstream: options.upstream }),
532
689
  ...(options.entry === undefined
@@ -851,6 +1008,10 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
851
1008
  : `Content frames aren't served now: ${view.reason ?? "the content domain is checking"}`,
852
1009
  );
853
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
+ }
854
1015
  let viewer: V | null;
855
1016
  try {
856
1017
  viewer = await viewerOf(request);
@@ -860,14 +1021,20 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
860
1021
  const key =
861
1022
  options.rateLimit?.key?.(request, viewer) ??
862
1023
  (viewer === null
863
- ? `address:${request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for") ?? ""}`
1024
+ ? `address:${clientAddress(request, options.rateLimit?.trustedProxies ?? 0)}`
864
1025
  : `viewer:${JSON.stringify(viewer)}`);
865
1026
  if (!withinRate(key)) {
866
1027
  return refusal(429, "rate-limited", "Too many frames asked for: try again in a minute");
867
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.
868
1031
  let body: unknown;
869
1032
  try {
870
- 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);
871
1038
  } catch {
872
1039
  return refusal(400, "bad-json", "The body is JSON: { instance }");
873
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,
@@ -94,9 +95,12 @@ export {
94
95
  type FileSetProblem,
95
96
  } from "../files/paths.ts";
96
97
  export { fileTypeOf, type FileRole, type FileType } from "../files/types.ts";
98
+ export { pseudonymFor } from "./pseudonym.ts";
97
99
  export type {
98
100
  Access,
99
101
  ArtifactStore,
102
+ AssetStore,
103
+ StoredAsset,
100
104
  FileBody,
101
105
  StoredFile,
102
106
  StoredFiles,
@@ -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
  },
@@ -0,0 +1,21 @@
1
+ import { hmacSha256, utf8 } from "./crypto.ts";
2
+ import { base32 } from "./keys.ts";
3
+
4
+ /**
5
+ * A person's id for one artifact's pages (P087, after the review): what `Grant.user.id` may be
6
+ * where pages shouldn't learn the account id or link one person across artifacts. Stable for the
7
+ * same secret, artifact and person (their `data/users/<id>` stays theirs across visits), a
8
+ * different one on every other artifact, not reversible without the secret. 26 lowercase base32
9
+ * characters: one db path segment. The secret is the host's (at least 32 random bytes); keep it
10
+ * apart from Porthole's server secret.
11
+ */
12
+ export function pseudonymFor(secret: Uint8Array, artifact: string, person: string): string {
13
+ if (!(secret instanceof Uint8Array) || secret.length < 32) {
14
+ throw new TypeError("pseudonymFor needs a secret of at least 32 random bytes");
15
+ }
16
+ if (artifact === "" || person === "") {
17
+ throw new TypeError("pseudonymFor needs an artifact and a person");
18
+ }
19
+ const mac = hmacSha256(secret, utf8(`porthole/pseudonym\u0000${artifact}\u0000${person}`));
20
+ return base32(mac.slice(0, 16)).slice(0, 26);
21
+ }