@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,5 +1,5 @@
1
1
  import { embedderFrameSourcesOf } from "../compile/policy.js";
2
- import { base64url, hmacSha256, utf8 } from "./crypto.js";
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
5
  import { appStatusPage } from "./pages.js";
@@ -37,6 +37,33 @@ const plain = (status, text) => new Response(text, {
37
37
  "x-robots-tag": "noindex, nofollow",
38
38
  },
39
39
  });
40
+ /** How long a viewer handoff holds (P072): the app's page refreshes it on load and focus. */
41
+ const HANDOFF_SECONDS = 600;
42
+ /** The kit's events to the app's `log`: its function, or its logger at each event's level. */
43
+ function logOf(given) {
44
+ if (given === undefined) {
45
+ return () => { };
46
+ }
47
+ if (typeof given === "function") {
48
+ return given;
49
+ }
50
+ return (event) => {
51
+ const message = event.evt === "porthole.content.healthy"
52
+ ? "Porthole: the content domain answers; frames are served"
53
+ : event.evt === "porthole.content.unhealthy"
54
+ ? `Porthole: frames aren't served: ${event.reason}`
55
+ : `Porthole: the content domain can't be served (${event.code}): ${event.reason}`;
56
+ if (event.evt === "porthole.content.healthy") {
57
+ given.info?.(message, event);
58
+ }
59
+ else if (event.evt === "porthole.content.unhealthy") {
60
+ given.warn?.(message, event);
61
+ }
62
+ else {
63
+ given.error?.(message, event);
64
+ }
65
+ };
66
+ }
40
67
  /** The CSP source for an authorize route: its origin and path, so nothing else there frames. */
41
68
  const authorizeSource = (url) => {
42
69
  const parsed = new URL(url);
@@ -54,7 +81,15 @@ const fetchProbe = async (url, timeoutMs) => {
54
81
  };
55
82
  export function createContentHost(options) {
56
83
  const gate = options.health;
57
- const log = options.log ?? (() => { });
84
+ const log = logOf(options.log);
85
+ const prefix = (options.prefix ?? "/porthole").replace(/\/+$/u, "");
86
+ if (!/^\/[\w./-]*$/u.test(prefix)) {
87
+ throw new TypeError("A route prefix is a path: /porthole");
88
+ }
89
+ const authorizeUrl = options.entry?.authorizeUrl ?? `${options.appOrigins[0] ?? ""}${prefix}/authorize`;
90
+ if (options.configs === undefined && options.displays === undefined) {
91
+ throw new TypeError("createContentHost needs configs or displays");
92
+ }
58
93
  const secret = typeof options.secret === "string" ? utf8(options.secret.trim()) : options.secret;
59
94
  const healthLabel = gate?.label ?? DEFAULT_HEALTH_LABEL;
60
95
  // The id Porthole's health check answers with: keyed, so another deployment's answer fails.
@@ -73,8 +108,16 @@ export function createContentHost(options) {
73
108
  if (options.entry !== undefined && options.name?.scopeOf === undefined) {
74
109
  throw new TypeError("Redirect entry needs a naming that says which scope a label names (prefixedName)");
75
110
  }
111
+ const displays = options.displays;
76
112
  configs =
77
- typeof options.configs === "function" ? options.configs(domain.source) : options.configs;
113
+ options.configs === undefined
114
+ ? (displays?.served(domain.source) ??
115
+ (() => {
116
+ throw new TypeError(displays?.problem(domain.source) ?? "No configs");
117
+ })())
118
+ : typeof options.configs === "function"
119
+ ? options.configs(domain.source)
120
+ : options.configs;
78
121
  server = createServer({
79
122
  content: serverDomain(domain, {
80
123
  ...(options.name === undefined ? {} : { name: options.name }),
@@ -90,7 +133,7 @@ export function createContentHost(options) {
90
133
  ? {}
91
134
  : {
92
135
  entry: {
93
- authorizeUrl: options.entry.authorizeUrl,
136
+ authorizeUrl,
94
137
  // Whether a clean address names anything, before a browser is sent away (P070).
95
138
  named: async (label, path, request) => {
96
139
  const scope = options.name?.scopeOf?.(label) ?? null;
@@ -128,6 +171,20 @@ export function createContentHost(options) {
128
171
  log({ evt: "porthole.content.misconfigured", code, reason });
129
172
  }
130
173
  const served = () => server !== null && view.state === "healthy";
174
+ // onServedChange: once per flip of served(), the first decision included.
175
+ let toldServed = null;
176
+ const tellServed = () => {
177
+ const now = served();
178
+ if (now !== toldServed && view.state !== "checking") {
179
+ toldServed = now;
180
+ try {
181
+ gate?.onServedChange?.(now);
182
+ }
183
+ catch {
184
+ // The app's listener failing changes nothing here.
185
+ }
186
+ }
187
+ };
131
188
  // The health gate: one check at a time, again after a minute while unhealthy, ten while healthy.
132
189
  let timer = null;
133
190
  let running = null;
@@ -193,6 +250,7 @@ export function createContentHost(options) {
193
250
  // The app's listener failing changes nothing here.
194
251
  }
195
252
  }
253
+ tellServed();
196
254
  running = null;
197
255
  schedule();
198
256
  return view;
@@ -242,7 +300,76 @@ export function createContentHost(options) {
242
300
  const top = label.split(".").at(-1) ?? "";
243
301
  return top !== "" && appReserved(top) ? null : { url, label };
244
302
  };
245
- return {
303
+ // The viewer handoff (P072): a key Porthole signs, naming the app's viewer until a time, in a
304
+ // cookie only the prefix's routes get. Never the app's own credential.
305
+ const handoffKey = hmacSha256(secret, utf8("porthole/handoff"));
306
+ const secureApp = (options.appOrigins[0] ?? "").startsWith("https:");
307
+ const handoffName = secureApp ? "__Secure-porthole-handoff" : "porthole-handoff";
308
+ const handoffCookie = (value, maxAge) => [
309
+ `${handoffName}=${value}`,
310
+ `Path=${prefix}`,
311
+ "HttpOnly",
312
+ "SameSite=Lax",
313
+ `Max-Age=${maxAge}`,
314
+ ...(secureApp ? ["Secure"] : []),
315
+ ].join("; ");
316
+ const signHandoff = (id, until) => {
317
+ const payload = base64url(utf8(JSON.stringify({ h: 1, v: id, x: until })));
318
+ return `${payload}.${base64url(hmacSha256(handoffKey, utf8(payload)))}`;
319
+ };
320
+ /** The viewer a request's handoff cookie names, if it is good. */
321
+ const handedOver = async (request) => {
322
+ const handoff = options.entry?.handoff;
323
+ if (handoff === undefined) {
324
+ return null;
325
+ }
326
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
327
+ const at = part.indexOf("=");
328
+ if (at < 0 || part.slice(0, at).trim() !== handoffName) {
329
+ continue;
330
+ }
331
+ const [payload = "", mac = "", ...rest] = part
332
+ .slice(at + 1)
333
+ .trim()
334
+ .split(".");
335
+ const given = fromBase64url(mac);
336
+ if (rest.length > 0 ||
337
+ given === null ||
338
+ !timingSafeEqual(given, hmacSha256(handoffKey, utf8(payload)))) {
339
+ continue;
340
+ }
341
+ const bytes = fromBase64url(payload);
342
+ let said = null;
343
+ try {
344
+ said = bytes === null ? null : JSON.parse(fromUtf8(bytes));
345
+ }
346
+ catch {
347
+ said = null;
348
+ }
349
+ if (isRecord(said) &&
350
+ said.h === 1 &&
351
+ typeof said.v === "string" &&
352
+ typeof said.x === "number" &&
353
+ said.x > Date.now()) {
354
+ return handoff.viewer(said.v, request);
355
+ }
356
+ }
357
+ return null;
358
+ };
359
+ /** The app's sign-in: its own `signIn`, or its single-page route with `next`. */
360
+ const signInWith = async (entry, request, context) => {
361
+ if (entry.signIn !== undefined) {
362
+ return entry.signIn(request.url, request, context);
363
+ }
364
+ const route = entry.spa?.route ?? "/";
365
+ const to = new URL(route, options.appOrigins[0]);
366
+ to.searchParams.set("next", request.url);
367
+ return new Response(null, {
368
+ status: 303,
369
+ headers: { location: to.href, "cache-control": "no-store", "referrer-policy": "no-referrer" },
370
+ });
371
+ };
372
+ const host = {
246
373
  get domain() {
247
374
  return domain;
248
375
  },
@@ -254,7 +381,7 @@ export function createContentHost(options) {
254
381
  : [
255
382
  ...embedderFrameSourcesOf(Object.values(configs)),
256
383
  // A frame on a clean address goes by the authorize route (only that path).
257
- ...(options.entry === undefined ? [] : [authorizeSource(options.entry.authorizeUrl)]),
384
+ ...(options.entry === undefined ? [] : [authorizeSource(authorizeUrl)]),
258
385
  ],
259
386
  owns: (request) => routeOf(request) !== null,
260
387
  async fetch(request) {
@@ -329,7 +456,16 @@ export function createContentHost(options) {
329
456
  catch (error) {
330
457
  return refusal(409, "refused", error instanceof Error ? error.message : String(error));
331
458
  }
332
- return json(201, location);
459
+ // The clean address, where the app says the instance's path (P072).
460
+ const path = options.entry?.pathOf?.(instance) ?? null;
461
+ let link = null;
462
+ try {
463
+ link = path === null ? null : server.urlOf(instance.scope, path);
464
+ }
465
+ catch {
466
+ link = null;
467
+ }
468
+ return json(201, link === null ? location : { ...location, link });
333
469
  }
334
470
  catch {
335
471
  return refusal(500, "failed", "The app's policy failed");
@@ -341,6 +477,97 @@ export function createContentHost(options) {
341
477
  contentSource: domain?.source ?? null,
342
478
  health: gate === undefined ? null : view,
343
479
  }),
480
+ prefix,
481
+ clientMeta: () => ({
482
+ served: served(),
483
+ contentSource: domain?.source ?? null,
484
+ frameSources: host.frameSources,
485
+ health: gate === undefined
486
+ ? null
487
+ : { state: view.state, ...(view.reason === undefined ? {} : { reason: view.reason }) },
488
+ }),
489
+ routes(viewerOf) {
490
+ const issue = host.issue(viewerOf);
491
+ const authorize = host.authorize(viewerOf);
492
+ const handoff = host.handoff(viewerOf);
493
+ return async (request) => {
494
+ let pathname;
495
+ try {
496
+ pathname = new URL(request.url).pathname;
497
+ }
498
+ catch {
499
+ return null;
500
+ }
501
+ if (!pathname.startsWith(`${prefix}/`)) {
502
+ return null;
503
+ }
504
+ const method = request.method.toUpperCase();
505
+ switch (pathname.slice(prefix.length)) {
506
+ case "/frames":
507
+ return issue(request);
508
+ case "/authorize":
509
+ return authorize(request);
510
+ case "/meta":
511
+ return method === "GET" || method === "HEAD"
512
+ ? json(200, host.clientMeta())
513
+ : refusal(405, "method", "GET here");
514
+ case "/handoff":
515
+ return handoff(request);
516
+ default:
517
+ return null;
518
+ }
519
+ };
520
+ },
521
+ handoff(viewerOf) {
522
+ return async (request) => {
523
+ const method = request.method.toUpperCase();
524
+ if (method !== "POST" && method !== "DELETE") {
525
+ return refusal(405, "method", "POST (or DELETE) here");
526
+ }
527
+ const handoff = options.entry?.handoff;
528
+ if (handoff === undefined) {
529
+ return refusal(404, "not-found", "This app has no viewer handoff (entry.handoff)");
530
+ }
531
+ // The app's own page only: a request from another site never sets or clears it.
532
+ const origin = request.headers.get("origin");
533
+ const site = request.headers.get("sec-fetch-site");
534
+ if ((origin !== null && !options.appOrigins.includes(origin)) ||
535
+ (origin === null && site !== null && site !== "same-origin")) {
536
+ return refusal(403, "cross-site", "Only the app's own page hands its viewer over");
537
+ }
538
+ if (method === "DELETE") {
539
+ return new Response(null, {
540
+ status: 204,
541
+ headers: { "set-cookie": handoffCookie("", 0), "cache-control": "no-store" },
542
+ });
543
+ }
544
+ let viewer;
545
+ try {
546
+ viewer = await viewerOf(request);
547
+ }
548
+ catch {
549
+ return refusal(500, "failed", "The app couldn't tell who is asking");
550
+ }
551
+ if (viewer === null) {
552
+ return refusal(401, "unauthenticated", "Sign in first: the handoff names a viewer");
553
+ }
554
+ const id = handoff.id(viewer);
555
+ if (typeof id !== "string" || id.length === 0 || id.length > 512) {
556
+ return refusal(500, "failed", "entry.handoff.id gave no id (1 to 512 characters)");
557
+ }
558
+ const key = signHandoff(id, Date.now() + HANDOFF_SECONDS * 1_000);
559
+ return new Response(null, {
560
+ status: 204,
561
+ headers: {
562
+ "set-cookie": handoffCookie(key, HANDOFF_SECONDS),
563
+ "cache-control": "no-store",
564
+ },
565
+ });
566
+ };
567
+ },
568
+ forget(filter = {}) {
569
+ server?.forget(filter);
570
+ },
344
571
  urlOf(scope, path = "/") {
345
572
  return server === null || !served() ? null : server.urlOf(scope, path);
346
573
  },
@@ -368,7 +595,7 @@ export function createContentHost(options) {
368
595
  const scope = options.name?.scopeOf?.(state.label) ?? null;
369
596
  let viewer;
370
597
  try {
371
- viewer = await viewerOf(request);
598
+ viewer = (await viewerOf(request)) ?? (await handedOver(request));
372
599
  }
373
600
  catch {
374
601
  return appPage(500, "Something went wrong", "The app couldn't tell who is asking.", "error", method);
@@ -392,7 +619,7 @@ export function createContentHost(options) {
392
619
  // The app's sign-in never shows in a frame: the person opens a tab for it.
393
620
  return framed
394
621
  ? appPage(401, "Open this in a new tab to sign in", "Signing in doesn't work inside a frame.", "sign-in", method)
395
- : await entry.signIn(request.url, request, context);
622
+ : await signInWith(entry, request, context);
396
623
  }
397
624
  const status = instance === null ? 404 : 403;
398
625
  const own = framed ? null : await entry.refusal?.(status, request, context);
@@ -443,4 +670,5 @@ export function createContentHost(options) {
443
670
  }
444
671
  },
445
672
  };
673
+ return host;
446
674
  }
@@ -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 EntryContext, type EntryOptions, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
36
+ export { createContentHost, HEALTH_PATH, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, 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";
@@ -41,5 +41,7 @@ export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
41
41
  export { conformancePage } from "../conformance/page.ts";
42
42
  export type { PortholeConfig } from "../config/schema.ts";
43
43
  export type { FrameLocation, InstanceRef, ServedDocument } from "../isolation/types.ts";
44
- export { proxyTo, type ProxyOptions } from "./proxy.ts";
44
+ export { isPortholeCookie, proxyTo, upstreamHeaders, withoutPortholeCookies, type ProxyOptions, } from "./proxy.ts";
45
+ export { statusPageOf as statusPage } from "./pages.ts";
46
+ export { contentHostFor, type ContentHostFor } from "./bootstrap.ts";
45
47
  export type { Access, ArtifactStore, AuthorizeAnswer, AuthorizeRequest, Authorizer, ContentDomain, EntryState, Grant, PortholeServer, ServerOptions, TicketRecord, TicketStore, Upstream, } from "./types.ts";
@@ -40,4 +40,6 @@ export { FRAME_STATUS_METHOD } from "../isolation/types.js";
40
40
  export { isHostLabel, prefixedName } from "./naming.js";
41
41
  // The page an app serves in conformance test mode (P071).
42
42
  export { conformancePage } from "../conformance/page.js";
43
- export { proxyTo } from "./proxy.js";
43
+ export { isPortholeCookie, proxyTo, upstreamHeaders, withoutPortholeCookies, } from "./proxy.js";
44
+ export { statusPageOf as statusPage } from "./pages.js";
45
+ export { contentHostFor } from "./bootstrap.js";
@@ -18,3 +18,22 @@ export declare function appStatusPage(status: number, title: string, detail: str
18
18
  readonly href: string;
19
19
  readonly text: string;
20
20
  }, method?: string): Response;
21
+ /**
22
+ * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
23
+ * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
24
+ * its one script inline under its hash, so it works on any origin.
25
+ */
26
+ export declare function statusPageOf(options: {
27
+ readonly status: number;
28
+ readonly title: string;
29
+ readonly detail: string;
30
+ readonly reason?: FrameBlock;
31
+ readonly hostOrigins: readonly string[];
32
+ /** Who may frame it (`frame-ancestors`): default, the host origins. */
33
+ readonly frameAncestors?: string;
34
+ readonly link?: {
35
+ readonly href: string;
36
+ readonly text: string;
37
+ };
38
+ readonly method?: string;
39
+ }): Response;
@@ -140,3 +140,11 @@ export function appStatusPage(status, title, detail, frameAncestors, reason, hos
140
140
  },
141
141
  });
142
142
  }
143
+ /**
144
+ * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
145
+ * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
146
+ * its one script inline under its hash, so it works on any origin.
147
+ */
148
+ export function statusPageOf(options) {
149
+ return appStatusPage(options.status, options.title, options.detail, options.frameAncestors ?? options.hostOrigins.join(" "), options.reason ?? "error", options.hostOrigins, options.link, options.method);
150
+ }
@@ -19,3 +19,27 @@ export declare function upstreamRequestHeaders(headers: Headers, origin: string,
19
19
  export declare function upstreamResponseHeaders(headers: Headers, origin: string, target: string): Headers;
20
20
  /** An `Upstream` that relays to the app by HTTP. */
21
21
  export declare function proxyTo(options?: ProxyOptions): Upstream;
22
+ type HeaderInput = Headers | Iterable<readonly [string, string]> | Readonly<Record<string, string | readonly string[] | undefined>>;
23
+ /** Whether a cookie is Porthole's own (sessions, entry nonces, the handoff). */
24
+ export declare const isPortholeCookie: (name: string) => boolean;
25
+ /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
26
+ export declare function withoutPortholeCookies(cookie: string | null | undefined): string | null;
27
+ /**
28
+ * The header rewrite `proxyTo` makes, for a relay of its own (P072): a browser's request as the
29
+ * app at `target` gets it (Host, Origin, Referer naming the app; no forwarding headers, no
30
+ * Porthole cookies), and the app's answer as the browser on `origin` gets it (redirects and
31
+ * cookies kept on the content origin, Porthole's cookies never set). `websocket` keeps the
32
+ * upgrade's own headers. Pairs out, so a raw socket relay writes them as they are.
33
+ */
34
+ export declare const upstreamHeaders: {
35
+ request(input: HeaderInput, options: {
36
+ readonly origin: string;
37
+ readonly target: string;
38
+ readonly websocket?: boolean;
39
+ }): [string, string][];
40
+ response(input: HeaderInput, options: {
41
+ readonly origin: string;
42
+ readonly target: string;
43
+ }): [string, string][];
44
+ };
45
+ export {};
@@ -107,3 +107,70 @@ export function proxyTo(options = {}) {
107
107
  });
108
108
  };
109
109
  }
110
+ /** Headers from any of the shapes a relay has: fetch's, raw pairs, Node's. */
111
+ function headersOf(input) {
112
+ if (input instanceof Headers) {
113
+ return new Headers(input);
114
+ }
115
+ const out = new Headers();
116
+ const entries = Symbol.iterator in input
117
+ ? input
118
+ : Object.entries(input).flatMap(([name, value]) => value === undefined
119
+ ? []
120
+ : typeof value === "string"
121
+ ? [[name, value]]
122
+ : value.map((each) => [name, each]));
123
+ for (const [name, value] of entries) {
124
+ out.append(name, value);
125
+ }
126
+ return out;
127
+ }
128
+ /** Whether a cookie is Porthole's own (sessions, entry nonces, the handoff). */
129
+ export const isPortholeCookie = (name) => /^(?:__Host-|__Secure-)?porthole-/u.test(name);
130
+ /** The cookie header without Porthole's own cookies, or null when nothing else is left. */
131
+ export function withoutPortholeCookies(cookie) {
132
+ const kept = (cookie ?? "")
133
+ .split(";")
134
+ .map((part) => part.trim())
135
+ .filter((part) => part !== "" && !isPortholeCookie(part.split("=")[0]?.trim() ?? ""));
136
+ return kept.length === 0 ? null : kept.join("; ");
137
+ }
138
+ /**
139
+ * The header rewrite `proxyTo` makes, for a relay of its own (P072): a browser's request as the
140
+ * app at `target` gets it (Host, Origin, Referer naming the app; no forwarding headers, no
141
+ * Porthole cookies), and the app's answer as the browser on `origin` gets it (redirects and
142
+ * cookies kept on the content origin, Porthole's cookies never set). `websocket` keeps the
143
+ * upgrade's own headers. Pairs out, so a raw socket relay writes them as they are.
144
+ */
145
+ export const upstreamHeaders = {
146
+ request(input, options) {
147
+ const given = headersOf(input);
148
+ const out = upstreamRequestHeaders(given, options.origin, options.target);
149
+ const cookie = withoutPortholeCookies(given.get("cookie"));
150
+ if (cookie === null) {
151
+ out.delete("cookie");
152
+ }
153
+ else {
154
+ out.set("cookie", cookie);
155
+ }
156
+ if (options.websocket === true) {
157
+ out.delete("accept-encoding");
158
+ for (const name of ["connection", "upgrade"]) {
159
+ const value = given.get(name);
160
+ if (value !== null) {
161
+ out.set(name, value);
162
+ }
163
+ }
164
+ out.set("host", new URL(options.target).host);
165
+ }
166
+ return [...out];
167
+ },
168
+ response(input, options) {
169
+ const answer = upstreamResponseHeaders(headersOf(input), options.origin, options.target);
170
+ const cookies = answer
171
+ .getSetCookie()
172
+ .filter((each) => !isPortholeCookie(each.split("=")[0]?.trim() ?? ""));
173
+ answer.delete("set-cookie");
174
+ return [...answer, ...cookies.map((each) => ["set-cookie", each])];
175
+ },
176
+ };
@@ -270,7 +270,12 @@ export function createServer(options) {
270
270
  catch {
271
271
  given = { allow: false };
272
272
  }
273
- answer = { answer: given, until: at + authorizeTtl * 1_000 };
273
+ answer = {
274
+ answer: given,
275
+ until: at + authorizeTtl * 1_000,
276
+ scope: access.instance.scope,
277
+ subject: access.subject ?? null,
278
+ };
274
279
  if (authorizeTtl > 0) {
275
280
  if (answers.size > 10_000) {
276
281
  answers.clear();
@@ -855,6 +860,14 @@ export function createServer(options) {
855
860
  : `${PREFIX}d/${key}?ticket=${ticket}`;
856
861
  return { url: `${origin}${path}`, origin, reports: true };
857
862
  },
863
+ forget(filter = {}) {
864
+ for (const [key, each] of answers) {
865
+ if ((filter.scope === undefined || each.scope === filter.scope) &&
866
+ (filter.subject === undefined || each.subject === filter.subject)) {
867
+ answers.delete(key);
868
+ }
869
+ }
870
+ },
858
871
  urlOf(scope, path = "/") {
859
872
  if (!path.startsWith("/") || path.startsWith("//") || path.startsWith(PREFIX)) {
860
873
  throw new TypeError("A clean address's path starts with one / and isn't Porthole's own");
@@ -205,6 +205,14 @@ export interface PortholeServer {
205
205
  access(request: Request): Promise<Access | null>;
206
206
  /** The frame source every content origin matches (`https://*.example-usercontent.com`). */
207
207
  readonly contentSource: string;
208
+ /**
209
+ * Drops cached `authorize.check` answers (`ttlSeconds`): all, or a scope's, or a subject's, so a
210
+ * revocation holds at once (P072).
211
+ */
212
+ forget(filter?: {
213
+ readonly scope?: string;
214
+ readonly subject?: string;
215
+ }): void;
208
216
  /** A clean address on a scope's origin (P068): what a tab, a link, a bookmark opens. */
209
217
  urlOf(scope: string, path?: string): string;
210
218
  /** A redirect entry's state, signature checked; null for one this server didn't make. */