@botiverse/porthole 0.2.3 → 0.3.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 (75) hide show
  1. package/README.md +14 -9
  2. package/dist/check/check.d.ts +83 -0
  3. package/dist/check/check.js +169 -0
  4. package/dist/check/drivers.d.ts +24 -0
  5. package/dist/check/drivers.js +110 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/lint.d.ts +21 -0
  9. package/dist/check/lint.js +131 -0
  10. package/dist/check/page-source.d.ts +2 -0
  11. package/dist/check/page-source.js +2 -0
  12. package/dist/check/page.d.ts +51 -0
  13. package/dist/check/page.js +150 -0
  14. package/dist/check/tools.d.ts +61 -0
  15. package/dist/check/tools.js +140 -0
  16. package/dist/conformance/host-kit.d.ts +10 -2
  17. package/dist/conformance/host-kit.js +9 -2
  18. package/dist/displays/displays.d.ts +61 -0
  19. package/dist/displays/displays.js +113 -0
  20. package/dist/host/client.d.ts +92 -0
  21. package/dist/host/client.js +259 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.js +6 -0
  24. package/dist/node/index.d.ts +22 -1
  25. package/dist/node/index.js +46 -1
  26. package/dist/react/frame.d.ts +71 -3
  27. package/dist/react/frame.js +120 -19
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.js +1 -0
  30. package/dist/react/view.d.ts +54 -0
  31. package/dist/react/view.js +146 -0
  32. package/dist/server/bootstrap.d.ts +27 -0
  33. package/dist/server/bootstrap.js +63 -0
  34. package/dist/server/host.d.ts +74 -7
  35. package/dist/server/host.js +237 -9
  36. package/dist/server/index.d.ts +4 -2
  37. package/dist/server/index.js +3 -1
  38. package/dist/server/pages.d.ts +19 -0
  39. package/dist/server/pages.js +8 -0
  40. package/dist/server/proxy.d.ts +24 -0
  41. package/dist/server/proxy.js +67 -0
  42. package/dist/server/server.js +14 -1
  43. package/dist/server/types.d.ts +8 -0
  44. package/docs/ADOPTING.md +356 -0
  45. package/docs/DECISIONS.md +146 -0
  46. package/docs/DESIGN.md +58 -0
  47. package/examples/app.mjs +62 -64
  48. package/examples/conformance/page.spec.mjs +23 -0
  49. package/examples/conformance/playwright.config.mjs +1 -1
  50. package/examples/conformance/porthole.spec.mjs +5 -3
  51. package/examples/displays.mjs +19 -0
  52. package/examples/mcp/server.mjs +121 -0
  53. package/package.json +9 -1
  54. package/src/check/check.ts +278 -0
  55. package/src/check/drivers.ts +144 -0
  56. package/src/check/index.ts +15 -0
  57. package/src/check/lint.ts +238 -0
  58. package/src/check/page-source.ts +19 -0
  59. package/src/check/page.ts +204 -0
  60. package/src/check/tools.ts +206 -0
  61. package/src/conformance/host-kit.ts +20 -11
  62. package/src/displays/displays.ts +191 -0
  63. package/src/host/client.ts +364 -0
  64. package/src/index.ts +25 -0
  65. package/src/node/index.ts +66 -2
  66. package/src/react/frame.tsx +191 -33
  67. package/src/react/index.ts +8 -0
  68. package/src/react/view.tsx +232 -0
  69. package/src/server/bootstrap.ts +97 -0
  70. package/src/server/host.ts +331 -15
  71. package/src/server/index.ts +11 -1
  72. package/src/server/pages.ts +28 -0
  73. package/src/server/proxy.ts +86 -0
  74. package/src/server/server.ts +26 -2
  75. package/src/server/types.ts +5 -0
@@ -1,7 +1,9 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
2
  import { embedderFrameSourcesOf } from "../compile/policy.ts";
3
3
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
4
- import { base64url, hmacSha256, utf8 } from "./crypto.ts";
4
+ import type { Displays } from "../displays/displays.ts";
5
+ import type { ContentClientMeta } from "../host/client.ts";
6
+ import { base64url, fromBase64url, fromUtf8, hmacSha256, timingSafeEqual, utf8 } from "./crypto.ts";
5
7
  import {
6
8
  ContentDomainError,
7
9
  contentDomain,
@@ -53,6 +55,11 @@ export interface HealthOptions {
53
55
  * its clients whether frames are served pushes it from here.
54
56
  */
55
57
  readonly onChange?: (view: ContentHealthView) => void;
58
+ /**
59
+ * Told when frames start or stop being served (P072): `meta().served` flipped. Deduplicated:
60
+ * once per flip, not per check.
61
+ */
62
+ readonly onServedChange?: (served: boolean) => void;
56
63
  }
57
64
 
58
65
  /** Where content stands, for the app's own meta and logs. */
@@ -82,6 +89,15 @@ export interface ContentMeta {
82
89
  readonly health: ContentHealthView | null;
83
90
  }
84
91
 
92
+ export type { ContentClientMeta } from "../host/client.ts";
93
+
94
+ /** A logger (pino, console, winston): the kit's events at their level (P072). */
95
+ export interface ContentLogger {
96
+ readonly info?: (message: string, event: ContentHostEvent) => void;
97
+ readonly warn?: (message: string, event: ContentHostEvent) => void;
98
+ readonly error?: (message: string, event: ContentHostEvent) => void;
99
+ }
100
+
85
101
  type Awaitable<T> = T | Promise<T>;
86
102
 
87
103
  export interface ContentHostOptions<V> {
@@ -92,10 +108,20 @@ export interface ContentHostOptions<V> {
92
108
  /** At least 32 random bytes (or a string of at least 32 bytes). */
93
109
  readonly secret: Uint8Array | string;
94
110
  readonly tickets?: TicketStore;
95
- /** The configs content is served under, given the content source (`https://*.<domain>`). */
96
- readonly configs:
111
+ /**
112
+ * The configs content is served under, given the content source (`https://*.<domain>`). Or
113
+ * `displays` (P072), which says it for every kind once.
114
+ */
115
+ readonly configs?:
97
116
  | Readonly<Record<string, PortholeConfig>>
98
117
  | ((source: string) => Readonly<Record<string, PortholeConfig>>);
118
+ /** The app's display kinds (`defineDisplays`): their served configs, in place of `configs`. */
119
+ readonly displays?: Displays;
120
+ /**
121
+ * Where `routes` answers on the app's origin (P072): `<prefix>/frames`, `/authorize`, `/meta`,
122
+ * `/handoff`. Default `/porthole`.
123
+ */
124
+ readonly prefix?: string;
99
125
  /**
100
126
  * How a scope is named (`prefixedName("a-")`); default: keyed labels. Redirect entry needs one
101
127
  * that says which scope a label names (`prefixedName` does).
@@ -143,7 +169,8 @@ export interface ContentHostOptions<V> {
143
169
  readonly perMinute: number;
144
170
  readonly key?: (request: Request, viewer: V | null) => string;
145
171
  };
146
- readonly log?: (event: ContentHostEvent) => void;
172
+ /** The kit's events: a function, or a logger (`{ info, warn, error }`). */
173
+ readonly log?: ((event: ContentHostEvent) => void) | ContentLogger;
147
174
  /**
148
175
  * Redirect entry (P068): clean addresses (`urlOf`) that open directly, in a new tab, on a
149
176
  * reload, from a bookmark or a link someone with access was sent. Without a cookie, the content
@@ -154,8 +181,11 @@ export interface ContentHostOptions<V> {
154
181
  }
155
182
 
156
183
  export interface EntryOptions<V> {
157
- /** The app's authorize route (`ContentHost.authorize`), an absolute URL on an app origin. */
158
- readonly authorizeUrl: string;
184
+ /**
185
+ * The app's authorize route (`ContentHost.authorize`), an absolute URL on an app origin.
186
+ * Default: `<first app origin><prefix>/authorize`, where `routes` answers it.
187
+ */
188
+ readonly authorizeUrl?: string;
159
189
  /**
160
190
  * Policy 1 for a clean address: the instance a scope's path means, or null/undefined: nothing
161
191
  * (404). The path is the address's pathname; its query rides along but never chooses the
@@ -175,7 +205,32 @@ export interface EntryOptions<V> {
175
205
  * Only ever on a tab: in a frame, the person is asked to open a new tab instead. `entry` is the
176
206
  * address being opened, decoded (P070).
177
207
  */
178
- readonly signIn: (returnTo: string, request: Request, entry: EntryContext) => Awaitable<Response>;
208
+ readonly signIn?: (
209
+ returnTo: string,
210
+ request: Request,
211
+ entry: EntryContext,
212
+ ) => Awaitable<Response>;
213
+ /**
214
+ * A single-page app's sign-in route (P072): the default `signIn` sends the person there with
215
+ * `?next=<authorize URL>`, and the app goes on to `next` once signed in (check it with
216
+ * `entryTarget`).
217
+ */
218
+ readonly spa?: { readonly route: string };
219
+ /**
220
+ * The clean path of an instance (the reverse of `at`), or null: `issue` then answers its clean
221
+ * address as `link` (P072), for "open in a new tab" and "copy link".
222
+ */
223
+ readonly pathOf?: (instance: InstanceRef) => string | null;
224
+ /**
225
+ * A viewer handoff, for an app whose page authenticates with a token rather than a cookie
226
+ * (P072): `POST <prefix>/handoff`, made with the app's own credential, leaves a short-lived key
227
+ * for its viewer in a cookie only the authorize route gets. `id` says who the viewer is (at
228
+ * most 512 characters); `viewer` turns it back into the app's viewer, or null.
229
+ */
230
+ readonly handoff?: {
231
+ readonly id: (viewer: V) => string;
232
+ readonly viewer: (id: string, request: Request) => Awaitable<V | null>;
233
+ };
179
234
  /**
180
235
  * The app's refusal page on a tab (a frame gets Porthole's plain one), for the address in
181
236
  * `entry`. Nothing (null, undefined): Porthole's own (P070).
@@ -230,6 +285,24 @@ export interface ContentHost<V> {
230
285
  * nothing is served. Opens through redirect entry (`entry`); frames take tickets (`issue`).
231
286
  */
232
287
  urlOf(scope: string, path?: string): string | null;
288
+ /** Where `routes` answers (`/porthole`). */
289
+ readonly prefix: string;
290
+ /**
291
+ * The app's Porthole routes in one handler (P072): `POST <prefix>/frames` (`issue`), `GET
292
+ * <prefix>/authorize`, `GET <prefix>/meta` (`clientMeta`), `POST`/`DELETE <prefix>/handoff`.
293
+ * Null for any other request: the app's own routes.
294
+ */
295
+ routes(
296
+ viewerOf: (request: Request) => Awaitable<V | null>,
297
+ ): (request: Request) => Promise<Response | null>;
298
+ /** What `GET <prefix>/meta` answers the page. */
299
+ clientMeta(): ContentClientMeta;
300
+ /** The viewer handoff (`entry.handoff`), as a fetch handler: POST sets it, DELETE clears it. */
301
+ handoff(
302
+ viewerOf: (request: Request) => Awaitable<V | null>,
303
+ ): (request: Request) => Promise<Response>;
304
+ /** Drops cached `authorize` answers (`authorizeTtlSeconds`): all, or a scope's, or a subject's. */
305
+ forget(filter?: { readonly scope?: string; readonly subject?: string }): void;
233
306
  /** The app's authorize route for redirect entry (`entry.authorizeUrl`), as a fetch handler. */
234
307
  authorize(
235
308
  viewerOf: (request: Request) => Awaitable<V | null>,
@@ -276,6 +349,34 @@ const plain = (status: number, text: string): Response =>
276
349
 
277
350
  type FrameBlockReason = Parameters<typeof appStatusPage>[4];
278
351
 
352
+ /** How long a viewer handoff holds (P072): the app's page refreshes it on load and focus. */
353
+ const HANDOFF_SECONDS = 600;
354
+
355
+ /** The kit's events to the app's `log`: its function, or its logger at each event's level. */
356
+ function logOf(given: ContentHostOptions<unknown>["log"]): (event: ContentHostEvent) => void {
357
+ if (given === undefined) {
358
+ return () => {};
359
+ }
360
+ if (typeof given === "function") {
361
+ return given;
362
+ }
363
+ return (event) => {
364
+ const message =
365
+ event.evt === "porthole.content.healthy"
366
+ ? "Porthole: the content domain answers; frames are served"
367
+ : event.evt === "porthole.content.unhealthy"
368
+ ? `Porthole: frames aren't served: ${event.reason}`
369
+ : `Porthole: the content domain can't be served (${event.code}): ${event.reason}`;
370
+ if (event.evt === "porthole.content.healthy") {
371
+ given.info?.(message, event);
372
+ } else if (event.evt === "porthole.content.unhealthy") {
373
+ given.warn?.(message, event);
374
+ } else {
375
+ given.error?.(message, event);
376
+ }
377
+ };
378
+ }
379
+
279
380
  /** The CSP source for an authorize route: its origin and path, so nothing else there frames. */
280
381
  const authorizeSource = (url: string): string => {
281
382
  const parsed = new URL(url);
@@ -295,7 +396,16 @@ const fetchProbe: HealthProbe = async (url, timeoutMs) => {
295
396
 
296
397
  export function createContentHost<V>(options: ContentHostOptions<V>): ContentHost<V> {
297
398
  const gate = options.health;
298
- const log = options.log ?? (() => {});
399
+ const log = logOf(options.log);
400
+ const prefix = (options.prefix ?? "/porthole").replace(/\/+$/u, "");
401
+ if (!/^\/[\w./-]*$/u.test(prefix)) {
402
+ throw new TypeError("A route prefix is a path: /porthole");
403
+ }
404
+ const authorizeUrl =
405
+ options.entry?.authorizeUrl ?? `${options.appOrigins[0] ?? ""}${prefix}/authorize`;
406
+ if (options.configs === undefined && options.displays === undefined) {
407
+ throw new TypeError("createContentHost needs configs or displays");
408
+ }
299
409
  const secret = typeof options.secret === "string" ? utf8(options.secret.trim()) : options.secret;
300
410
  const healthLabel = gate?.label ?? DEFAULT_HEALTH_LABEL;
301
411
  // The id Porthole's health check answers with: keyed, so another deployment's answer fails.
@@ -318,8 +428,16 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
318
428
  "Redirect entry needs a naming that says which scope a label names (prefixedName)",
319
429
  );
320
430
  }
431
+ const displays = options.displays;
321
432
  configs =
322
- typeof options.configs === "function" ? options.configs(domain.source) : options.configs;
433
+ options.configs === undefined
434
+ ? (displays?.served(domain.source) ??
435
+ (() => {
436
+ throw new TypeError(displays?.problem(domain.source) ?? "No configs");
437
+ })())
438
+ : typeof options.configs === "function"
439
+ ? options.configs(domain.source)
440
+ : options.configs;
323
441
  server = createServer({
324
442
  content: serverDomain(domain, {
325
443
  ...(options.name === undefined ? {} : { name: options.name }),
@@ -335,7 +453,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
335
453
  ? {}
336
454
  : {
337
455
  entry: {
338
- authorizeUrl: options.entry.authorizeUrl,
456
+ authorizeUrl,
339
457
  // Whether a clean address names anything, before a browser is sent away (P070).
340
458
  named: async (label: string, path: string, request: Request) => {
341
459
  const scope = options.name?.scopeOf?.(label) ?? null;
@@ -375,6 +493,19 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
375
493
  }
376
494
 
377
495
  const served = (): boolean => server !== null && view.state === "healthy";
496
+ // onServedChange: once per flip of served(), the first decision included.
497
+ let toldServed: boolean | null = null;
498
+ const tellServed = () => {
499
+ const now = served();
500
+ if (now !== toldServed && view.state !== "checking") {
501
+ toldServed = now;
502
+ try {
503
+ gate?.onServedChange?.(now);
504
+ } catch {
505
+ // The app's listener failing changes nothing here.
506
+ }
507
+ }
508
+ };
378
509
 
379
510
  // The health gate: one check at a time, again after a minute while unhealthy, ten while healthy.
380
511
  let timer: ReturnType<typeof setTimeout> | null = null;
@@ -446,6 +577,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
446
577
  // The app's listener failing changes nothing here.
447
578
  }
448
579
  }
580
+ tellServed();
449
581
  running = null;
450
582
  schedule();
451
583
  return view;
@@ -498,7 +630,85 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
498
630
  return top !== "" && appReserved(top) ? null : { url, label };
499
631
  };
500
632
 
501
- return {
633
+ // The viewer handoff (P072): a key Porthole signs, naming the app's viewer until a time, in a
634
+ // cookie only the prefix's routes get. Never the app's own credential.
635
+ const handoffKey = hmacSha256(secret, utf8("porthole/handoff"));
636
+ const secureApp = (options.appOrigins[0] ?? "").startsWith("https:");
637
+ const handoffName = secureApp ? "__Secure-porthole-handoff" : "porthole-handoff";
638
+ const handoffCookie = (value: string, maxAge: number): string =>
639
+ [
640
+ `${handoffName}=${value}`,
641
+ `Path=${prefix}`,
642
+ "HttpOnly",
643
+ "SameSite=Lax",
644
+ `Max-Age=${maxAge}`,
645
+ ...(secureApp ? ["Secure"] : []),
646
+ ].join("; ");
647
+ const signHandoff = (id: string, until: number): string => {
648
+ const payload = base64url(utf8(JSON.stringify({ h: 1, v: id, x: until })));
649
+ return `${payload}.${base64url(hmacSha256(handoffKey, utf8(payload)))}`;
650
+ };
651
+ /** The viewer a request's handoff cookie names, if it is good. */
652
+ const handedOver = async (request: Request): Promise<V | null> => {
653
+ const handoff = options.entry?.handoff;
654
+ if (handoff === undefined) {
655
+ return null;
656
+ }
657
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
658
+ const at = part.indexOf("=");
659
+ if (at < 0 || part.slice(0, at).trim() !== handoffName) {
660
+ continue;
661
+ }
662
+ const [payload = "", mac = "", ...rest] = part
663
+ .slice(at + 1)
664
+ .trim()
665
+ .split(".");
666
+ const given = fromBase64url(mac);
667
+ if (
668
+ rest.length > 0 ||
669
+ given === null ||
670
+ !timingSafeEqual(given, hmacSha256(handoffKey, utf8(payload)))
671
+ ) {
672
+ continue;
673
+ }
674
+ const bytes = fromBase64url(payload);
675
+ let said: unknown = null;
676
+ try {
677
+ said = bytes === null ? null : JSON.parse(fromUtf8(bytes));
678
+ } catch {
679
+ said = null;
680
+ }
681
+ if (
682
+ isRecord(said) &&
683
+ said.h === 1 &&
684
+ typeof said.v === "string" &&
685
+ typeof said.x === "number" &&
686
+ said.x > Date.now()
687
+ ) {
688
+ return handoff.viewer(said.v, request);
689
+ }
690
+ }
691
+ return null;
692
+ };
693
+ /** The app's sign-in: its own `signIn`, or its single-page route with `next`. */
694
+ const signInWith = async (
695
+ entry: EntryOptions<V>,
696
+ request: Request,
697
+ context: EntryContext,
698
+ ): Promise<Response> => {
699
+ if (entry.signIn !== undefined) {
700
+ return entry.signIn(request.url, request, context);
701
+ }
702
+ const route = entry.spa?.route ?? "/";
703
+ const to = new URL(route, options.appOrigins[0]);
704
+ to.searchParams.set("next", request.url);
705
+ return new Response(null, {
706
+ status: 303,
707
+ headers: { location: to.href, "cache-control": "no-store", "referrer-policy": "no-referrer" },
708
+ });
709
+ };
710
+
711
+ const host: ContentHost<V> = {
502
712
  get domain() {
503
713
  return domain;
504
714
  },
@@ -511,7 +721,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
511
721
  : [
512
722
  ...embedderFrameSourcesOf(Object.values(configs)),
513
723
  // A frame on a clean address goes by the authorize route (only that path).
514
- ...(options.entry === undefined ? [] : [authorizeSource(options.entry.authorizeUrl)]),
724
+ ...(options.entry === undefined ? [] : [authorizeSource(authorizeUrl)]),
515
725
  ],
516
726
 
517
727
  owns: (request) => routeOf(request) !== null,
@@ -597,7 +807,15 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
597
807
  } catch (error) {
598
808
  return refusal(409, "refused", error instanceof Error ? error.message : String(error));
599
809
  }
600
- return json(201, location);
810
+ // The clean address, where the app says the instance's path (P072).
811
+ const path = options.entry?.pathOf?.(instance) ?? null;
812
+ let link: string | null = null;
813
+ try {
814
+ link = path === null ? null : server.urlOf(instance.scope, path);
815
+ } catch {
816
+ link = null;
817
+ }
818
+ return json(201, link === null ? location : { ...location, link });
601
819
  } catch {
602
820
  return refusal(500, "failed", "The app's policy failed");
603
821
  }
@@ -610,6 +828,103 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
610
828
  health: gate === undefined ? null : view,
611
829
  }),
612
830
 
831
+ prefix,
832
+
833
+ clientMeta: () => ({
834
+ served: served(),
835
+ contentSource: domain?.source ?? null,
836
+ frameSources: host.frameSources,
837
+ health:
838
+ gate === undefined
839
+ ? null
840
+ : { state: view.state, ...(view.reason === undefined ? {} : { reason: view.reason }) },
841
+ }),
842
+
843
+ routes(viewerOf) {
844
+ const issue = host.issue(viewerOf);
845
+ const authorize = host.authorize(viewerOf);
846
+ const handoff = host.handoff(viewerOf);
847
+ return async (request) => {
848
+ let pathname: string;
849
+ try {
850
+ pathname = new URL(request.url).pathname;
851
+ } catch {
852
+ return null;
853
+ }
854
+ if (!pathname.startsWith(`${prefix}/`)) {
855
+ return null;
856
+ }
857
+ const method = request.method.toUpperCase();
858
+ switch (pathname.slice(prefix.length)) {
859
+ case "/frames":
860
+ return issue(request);
861
+ case "/authorize":
862
+ return authorize(request);
863
+ case "/meta":
864
+ return method === "GET" || method === "HEAD"
865
+ ? json(200, host.clientMeta())
866
+ : refusal(405, "method", "GET here");
867
+ case "/handoff":
868
+ return handoff(request);
869
+ default:
870
+ return null;
871
+ }
872
+ };
873
+ },
874
+
875
+ handoff(viewerOf) {
876
+ return async (request) => {
877
+ const method = request.method.toUpperCase();
878
+ if (method !== "POST" && method !== "DELETE") {
879
+ return refusal(405, "method", "POST (or DELETE) here");
880
+ }
881
+ const handoff = options.entry?.handoff;
882
+ if (handoff === undefined) {
883
+ return refusal(404, "not-found", "This app has no viewer handoff (entry.handoff)");
884
+ }
885
+ // The app's own page only: a request from another site never sets or clears it.
886
+ const origin = request.headers.get("origin");
887
+ const site = request.headers.get("sec-fetch-site");
888
+ if (
889
+ (origin !== null && !options.appOrigins.includes(origin)) ||
890
+ (origin === null && site !== null && site !== "same-origin")
891
+ ) {
892
+ return refusal(403, "cross-site", "Only the app's own page hands its viewer over");
893
+ }
894
+ if (method === "DELETE") {
895
+ return new Response(null, {
896
+ status: 204,
897
+ headers: { "set-cookie": handoffCookie("", 0), "cache-control": "no-store" },
898
+ });
899
+ }
900
+ let viewer: V | null;
901
+ try {
902
+ viewer = await viewerOf(request);
903
+ } catch {
904
+ return refusal(500, "failed", "The app couldn't tell who is asking");
905
+ }
906
+ if (viewer === null) {
907
+ return refusal(401, "unauthenticated", "Sign in first: the handoff names a viewer");
908
+ }
909
+ const id = handoff.id(viewer);
910
+ if (typeof id !== "string" || id.length === 0 || id.length > 512) {
911
+ return refusal(500, "failed", "entry.handoff.id gave no id (1 to 512 characters)");
912
+ }
913
+ const key = signHandoff(id, Date.now() + HANDOFF_SECONDS * 1_000);
914
+ return new Response(null, {
915
+ status: 204,
916
+ headers: {
917
+ "set-cookie": handoffCookie(key, HANDOFF_SECONDS),
918
+ "cache-control": "no-store",
919
+ },
920
+ });
921
+ };
922
+ },
923
+
924
+ forget(filter = {}) {
925
+ server?.forget(filter);
926
+ },
927
+
613
928
  urlOf(scope, path = "/") {
614
929
  return server === null || !served() ? null : server.urlOf(scope, path);
615
930
  },
@@ -668,7 +983,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
668
983
  const scope = options.name?.scopeOf?.(state.label) ?? null;
669
984
  let viewer: V | null;
670
985
  try {
671
- viewer = await viewerOf(request);
986
+ viewer = (await viewerOf(request)) ?? (await handedOver(request));
672
987
  } catch {
673
988
  return appPage(
674
989
  500,
@@ -709,7 +1024,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
709
1024
  "sign-in",
710
1025
  method,
711
1026
  )
712
- : await entry.signIn(request.url, request, context);
1027
+ : await signInWith(entry, request, context);
713
1028
  }
714
1029
  const status = instance === null ? 404 : 403;
715
1030
  const own = framed ? null : await entry.refusal?.(status, request, context);
@@ -773,4 +1088,5 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
773
1088
  }
774
1089
  },
775
1090
  };
1091
+ return host;
776
1092
  }
@@ -40,6 +40,8 @@ export {
40
40
  type ContentHost,
41
41
  type ContentHostEvent,
42
42
  type ContentHostOptions,
43
+ type ContentClientMeta,
44
+ type ContentLogger,
43
45
  type EntryContext,
44
46
  type EntryOptions,
45
47
  type ContentMeta,
@@ -68,7 +70,15 @@ export { conformancePage } from "../conformance/page.ts";
68
70
  // The types an app's callbacks take and give (P070).
69
71
  export type { PortholeConfig } from "../config/schema.ts";
70
72
  export type { FrameLocation, InstanceRef, ServedDocument } from "../isolation/types.ts";
71
- export { proxyTo, type ProxyOptions } from "./proxy.ts";
73
+ export {
74
+ isPortholeCookie,
75
+ proxyTo,
76
+ upstreamHeaders,
77
+ withoutPortholeCookies,
78
+ type ProxyOptions,
79
+ } from "./proxy.ts";
80
+ export { statusPageOf as statusPage } from "./pages.ts";
81
+ export { contentHostFor, type ContentHostFor } from "./bootstrap.ts";
72
82
  export type {
73
83
  Access,
74
84
  ArtifactStore,
@@ -184,3 +184,31 @@ export function appStatusPage(
184
184
  },
185
185
  });
186
186
  }
187
+
188
+ /**
189
+ * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
190
+ * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
191
+ * its one script inline under its hash, so it works on any origin.
192
+ */
193
+ export function statusPageOf(options: {
194
+ readonly status: number;
195
+ readonly title: string;
196
+ readonly detail: string;
197
+ readonly reason?: FrameBlock;
198
+ readonly hostOrigins: readonly string[];
199
+ /** Who may frame it (`frame-ancestors`): default, the host origins. */
200
+ readonly frameAncestors?: string;
201
+ readonly link?: { readonly href: string; readonly text: string };
202
+ readonly method?: string;
203
+ }): Response {
204
+ return appStatusPage(
205
+ options.status,
206
+ options.title,
207
+ options.detail,
208
+ options.frameAncestors ?? options.hostOrigins.join(" "),
209
+ options.reason ?? "error",
210
+ options.hostOrigins,
211
+ options.link,
212
+ options.method,
213
+ );
214
+ }
@@ -131,3 +131,89 @@ export function proxyTo(options: ProxyOptions = {}): Upstream {
131
131
  });
132
132
  };
133
133
  }
134
+
135
+ type HeaderInput =
136
+ | Headers
137
+ | Iterable<readonly [string, string]>
138
+ | Readonly<Record<string, string | readonly string[] | undefined>>;
139
+
140
+ /** Headers from any of the shapes a relay has: fetch's, raw pairs, Node's. */
141
+ function headersOf(input: HeaderInput): Headers {
142
+ if (input instanceof Headers) {
143
+ return new Headers(input);
144
+ }
145
+ const out = new Headers();
146
+ const entries =
147
+ Symbol.iterator in input
148
+ ? (input as Iterable<readonly [string, string]>)
149
+ : Object.entries(input as Record<string, string | readonly string[] | undefined>).flatMap(
150
+ ([name, value]): [string, string][] =>
151
+ value === undefined
152
+ ? []
153
+ : typeof value === "string"
154
+ ? [[name, value]]
155
+ : value.map((each): [string, string] => [name, each]),
156
+ );
157
+ for (const [name, value] of entries) {
158
+ out.append(name, value);
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /** Whether a cookie is Porthole's own (sessions, entry nonces, the handoff). */
164
+ export const isPortholeCookie = (name: string): boolean =>
165
+ /^(?:__Host-|__Secure-)?porthole-/u.test(name);
166
+
167
+ /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
168
+ export function withoutPortholeCookies(cookie: string | null | undefined): string | null {
169
+ const kept = (cookie ?? "")
170
+ .split(";")
171
+ .map((part) => part.trim())
172
+ .filter((part) => part !== "" && !isPortholeCookie(part.split("=")[0]?.trim() ?? ""));
173
+ return kept.length === 0 ? null : kept.join("; ");
174
+ }
175
+
176
+ /**
177
+ * The header rewrite `proxyTo` makes, for a relay of its own (P072): a browser's request as the
178
+ * app at `target` gets it (Host, Origin, Referer naming the app; no forwarding headers, no
179
+ * Porthole cookies), and the app's answer as the browser on `origin` gets it (redirects and
180
+ * cookies kept on the content origin, Porthole's cookies never set). `websocket` keeps the
181
+ * upgrade's own headers. Pairs out, so a raw socket relay writes them as they are.
182
+ */
183
+ export const upstreamHeaders = {
184
+ request(
185
+ input: HeaderInput,
186
+ options: { readonly origin: string; readonly target: string; readonly websocket?: boolean },
187
+ ): [string, string][] {
188
+ const given = headersOf(input);
189
+ const out = upstreamRequestHeaders(given, options.origin, options.target);
190
+ const cookie = withoutPortholeCookies(given.get("cookie"));
191
+ if (cookie === null) {
192
+ out.delete("cookie");
193
+ } else {
194
+ out.set("cookie", cookie);
195
+ }
196
+ if (options.websocket === true) {
197
+ out.delete("accept-encoding");
198
+ for (const name of ["connection", "upgrade"]) {
199
+ const value = given.get(name);
200
+ if (value !== null) {
201
+ out.set(name, value);
202
+ }
203
+ }
204
+ out.set("host", new URL(options.target).host);
205
+ }
206
+ return [...out];
207
+ },
208
+ response(
209
+ input: HeaderInput,
210
+ options: { readonly origin: string; readonly target: string },
211
+ ): [string, string][] {
212
+ const answer = upstreamResponseHeaders(headersOf(input), options.origin, options.target);
213
+ const cookies = answer
214
+ .getSetCookie()
215
+ .filter((each) => !isPortholeCookie(each.split("=")[0]?.trim() ?? ""));
216
+ answer.delete("set-cookie");
217
+ return [...answer, ...cookies.map((each): [string, string] => ["set-cookie", each])];
218
+ },
219
+ };
@@ -251,7 +251,15 @@ export function createServer(options: ServerOptions): PortholeServer {
251
251
  if (!Number.isInteger(authorizeTtl) || authorizeTtl < 0 || authorizeTtl > 300) {
252
252
  throw new TypeError("authorize.ttlSeconds must be an integer from 0 to 300");
253
253
  }
254
- const answers = new Map<string, { readonly answer: AuthorizeAnswer; readonly until: number }>();
254
+ const answers = new Map<
255
+ string,
256
+ {
257
+ readonly answer: AuthorizeAnswer;
258
+ readonly until: number;
259
+ readonly scope: string;
260
+ readonly subject: string | null;
261
+ }
262
+ >();
255
263
 
256
264
  if (options.hostOrigins.length === 0) {
257
265
  throw new TypeError("hostOrigins must name the origins that embed content");
@@ -338,7 +346,12 @@ export function createServer(options: ServerOptions): PortholeServer {
338
346
  } catch {
339
347
  given = { allow: false };
340
348
  }
341
- answer = { answer: given, until: at + authorizeTtl * 1_000 };
349
+ answer = {
350
+ answer: given,
351
+ until: at + authorizeTtl * 1_000,
352
+ scope: access.instance.scope,
353
+ subject: access.subject ?? null,
354
+ };
342
355
  if (authorizeTtl > 0) {
343
356
  if (answers.size > 10_000) {
344
357
  answers.clear();
@@ -1047,6 +1060,17 @@ export function createServer(options: ServerOptions): PortholeServer {
1047
1060
  return { url: `${origin}${path}`, origin, reports: true };
1048
1061
  },
1049
1062
 
1063
+ forget(filter = {}) {
1064
+ for (const [key, each] of answers) {
1065
+ if (
1066
+ (filter.scope === undefined || each.scope === filter.scope) &&
1067
+ (filter.subject === undefined || each.subject === filter.subject)
1068
+ ) {
1069
+ answers.delete(key);
1070
+ }
1071
+ }
1072
+ },
1073
+
1050
1074
  urlOf(scope, path = "/") {
1051
1075
  if (!path.startsWith("/") || path.startsWith("//") || path.startsWith(PREFIX)) {
1052
1076
  throw new TypeError("A clean address's path starts with one / and isn't Porthole's own");