@botiverse/porthole 0.3.0 → 0.3.1

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 (51) hide show
  1. package/README.md +3 -2
  2. package/dist/check/check.d.ts +18 -1
  3. package/dist/check/check.js +84 -6
  4. package/dist/check/drivers.d.ts +25 -6
  5. package/dist/check/drivers.js +99 -28
  6. package/dist/check/index.d.ts +2 -2
  7. package/dist/check/index.js +1 -1
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.d.ts +2 -40
  12. package/dist/check/page.js +63 -43
  13. package/dist/conformance/host-kit.d.ts +18 -5
  14. package/dist/conformance/host-kit.js +38 -21
  15. package/dist/conformance/index.d.ts +1 -1
  16. package/dist/conformance/reporter.d.ts +14 -0
  17. package/dist/conformance/reporter.js +28 -0
  18. package/dist/host/client.d.ts +33 -15
  19. package/dist/host/client.js +39 -24
  20. package/dist/node/index.d.ts +6 -2
  21. package/dist/node/index.js +53 -8
  22. package/dist/react/frame.d.ts +13 -5
  23. package/dist/react/frame.js +67 -27
  24. package/dist/react/index.d.ts +1 -1
  25. package/dist/react/view.js +6 -1
  26. package/dist/server/host.d.ts +5 -3
  27. package/dist/server/host.js +41 -12
  28. package/docs/ADOPTING.md +108 -25
  29. package/docs/DECISIONS.md +134 -0
  30. package/docs/DESIGN.md +36 -12
  31. package/examples/app.mjs +23 -17
  32. package/examples/conformance/playwright.config.mjs +2 -1
  33. package/examples/conformance/porthole.spec.mjs +2 -1
  34. package/examples/displays.mjs +2 -0
  35. package/examples/node/server.mjs +16 -34
  36. package/examples/workers/worker.mjs +19 -7
  37. package/package.json +5 -1
  38. package/src/check/check.ts +116 -8
  39. package/src/check/drivers.ts +137 -39
  40. package/src/check/index.ts +8 -1
  41. package/src/check/instrument.ts +138 -0
  42. package/src/check/page.ts +94 -68
  43. package/src/conformance/host-kit.ts +65 -19
  44. package/src/conformance/index.ts +1 -0
  45. package/src/conformance/reporter.ts +38 -0
  46. package/src/host/client.ts +65 -34
  47. package/src/node/index.ts +56 -10
  48. package/src/react/frame.tsx +89 -33
  49. package/src/react/index.ts +1 -0
  50. package/src/react/view.tsx +6 -1
  51. package/src/server/host.ts +53 -15
@@ -252,14 +252,59 @@ export function nodeServer(options) {
252
252
  if (request === undefined) {
253
253
  throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
254
254
  }
255
- const porthole = nodeHost(options.content, {
256
- request,
257
- ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
258
- ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
255
+ const adapters = new WeakMap();
256
+ const started = new WeakSet();
257
+ let listening = false;
258
+ const given = options.content;
259
+ /** The host now (made once, adapted once), started once the server listens. */
260
+ const current = () => {
261
+ const host = typeof given === "function" ? given() : given;
262
+ if (host === null) {
263
+ return null;
264
+ }
265
+ let adapter = adapters.get(host);
266
+ if (adapter === undefined) {
267
+ adapter = nodeHost(host, {
268
+ request,
269
+ ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
270
+ ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
271
+ });
272
+ adapters.set(host, adapter);
273
+ }
274
+ if (listening && !started.has(host)) {
275
+ started.add(host);
276
+ host.start();
277
+ }
278
+ return adapter;
279
+ };
280
+ const server = createHttpServer((incoming, response) => {
281
+ const adapter = current();
282
+ if (adapter === null) {
283
+ request(incoming, response);
284
+ }
285
+ else {
286
+ adapter.request(incoming, response);
287
+ }
288
+ });
289
+ server.on("upgrade", (incoming, socket, head) => {
290
+ const adapter = current();
291
+ if (adapter !== null) {
292
+ adapter.upgrade(incoming, socket, head);
293
+ }
294
+ else if (options.upgrade !== undefined) {
295
+ options.upgrade(incoming, socket, head);
296
+ }
297
+ else {
298
+ refuseSocket(socket);
299
+ }
300
+ });
301
+ server.on("listening", () => {
302
+ listening = true;
303
+ current();
304
+ });
305
+ server.on("close", () => {
306
+ const host = typeof given === "function" ? given() : given;
307
+ host?.close();
259
308
  });
260
- const server = createHttpServer(porthole.request);
261
- server.on("upgrade", porthole.upgrade);
262
- server.on("listening", () => options.content.start());
263
- server.on("close", () => options.content.close());
264
309
  return server;
265
310
  }
@@ -67,12 +67,11 @@ export interface PortholeProviderProps {
67
67
  /**
68
68
  * Draws the confirmation in the app's own dialog, for the request at the head of the queue:
69
69
  * Porthole keeps the queue (one question at a time), runs `accept` inside the click, and counts
70
- * declines. Omitted: Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
70
+ * declines. `redirect`: the person took it elsewhere (edited a prompt first, P074): the call
71
+ * doesn't go, and it neither counts toward muting the display nor resets the count. Omitted:
72
+ * Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
71
73
  */
72
- readonly renderConfirm?: (request: ConfirmRequest, answer: {
73
- readonly accept: () => void;
74
- readonly decline: () => void;
75
- }) => ReactNode;
74
+ readonly renderConfirm?: (request: ConfirmRequest, answer: ConfirmActions) => ReactNode;
76
75
  /**
77
76
  * Who confirms gated calls for every frame below. Omitted: the default dialog (`ConfirmDialog`).
78
77
  * Pass your own function to replace it.
@@ -97,6 +96,15 @@ export interface PortholeProviderProps {
97
96
  readonly nonce?: string;
98
97
  readonly children?: ReactNode;
99
98
  }
99
+ /** What an app's own confirmation dialog answers with (`renderConfirm`). */
100
+ export interface ConfirmActions {
101
+ /** Yes: the call goes, run inside this click. */
102
+ readonly accept: () => void;
103
+ /** No: the call doesn't go, and it counts toward muting the display. */
104
+ readonly decline: () => void;
105
+ /** Elsewhere (the person edits the prompt first): the call doesn't go, and doesn't count. */
106
+ readonly redirect: () => void;
107
+ }
100
108
  export declare function PortholeProvider(props: PortholeProviderProps): ReactElement;
101
109
  /** What a placeholder shows: a display not yet running, loading, or stopped for others. */
102
110
  export interface PlaceholderProps {
@@ -147,6 +147,10 @@ export function PortholeProvider(props) {
147
147
  current.resolve("declined");
148
148
  setQueue((waiting) => waiting.slice(1));
149
149
  },
150
+ redirect: () => {
151
+ current.resolve("redirected");
152
+ setQueue((waiting) => waiting.slice(1));
153
+ },
150
154
  })
151
155
  : null, props.confirm === undefined && props.renderConfirm === undefined ? (_jsx(ConfirmDialog, { request: current?.request ?? null, ...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName }), onAnswer: (accepted) => {
152
156
  // A yes runs the effect inside this very click (a window it opens is the person's).
@@ -186,10 +190,13 @@ function rememberedHeight(heights, displayId, aliases) {
186
190
  }
187
191
  export function PortholeFrame(props) {
188
192
  const page = useContext(Page);
193
+ // The provider's registry and heights: stable, unlike the context value, which a scheme flip
194
+ // or a new themeKey renews (an effect keyed on it would let the frame go and make it again, #9).
195
+ const { live, heights } = page;
189
196
  const key = useId();
190
197
  const box = useRef(null);
191
198
  const max = props.config.limits.maxLiveFrames;
192
- const state = useSyncExternalStore((listener) => page.live.subscribe(listener), () => page.live.state(key), () => "waiting");
199
+ const state = useSyncExternalStore((listener) => live.subscribe(listener), () => live.state(key), () => "waiting");
193
200
  const { eager } = props;
194
201
  useEffect(() => {
195
202
  const element = box.current;
@@ -197,38 +204,38 @@ export function PortholeFrame(props) {
197
204
  return;
198
205
  }
199
206
  if (eager === true || typeof IntersectionObserver !== "function") {
200
- page.live.near(key, true);
201
- page.live.admit(key, max);
202
- return () => page.live.release(key);
207
+ live.near(key, true);
208
+ live.admit(key, max);
209
+ return () => live.release(key);
203
210
  }
204
211
  const observer = new IntersectionObserver((entries) => {
205
212
  const entry = entries.at(-1);
206
213
  if (entry === undefined) {
207
214
  return;
208
215
  }
209
- page.live.near(key, entry.isIntersecting);
216
+ live.near(key, entry.isIntersecting);
210
217
  if (entry.isIntersecting) {
211
- page.live.admit(key, max);
218
+ live.admit(key, max);
212
219
  }
213
220
  }, { rootMargin: NEAR_SCREEN });
214
221
  observer.observe(element);
215
222
  return () => {
216
223
  observer.disconnect();
217
- page.live.release(key);
224
+ live.release(key);
218
225
  };
219
- }, [page, key, max, eager]);
220
- const height = rememberedHeight(page.heights, props.displayId, props.aliases);
226
+ }, [live, key, max, eager]);
227
+ const height = rememberedHeight(heights, props.displayId, props.aliases);
221
228
  // A display renamed while it runs (its id settled) keeps its height under its new id.
222
229
  const previousId = useRef(props.displayId);
223
230
  useLayoutEffect(() => {
224
231
  const before = previousId.current;
225
232
  previousId.current = props.displayId;
226
- const kept = page.heights.get(before);
227
- if (before !== props.displayId && kept !== undefined && !page.heights.has(props.displayId)) {
228
- page.heights.set(props.displayId, kept);
233
+ const kept = heights.get(before);
234
+ if (before !== props.displayId && kept !== undefined && !heights.has(props.displayId)) {
235
+ heights.set(props.displayId, kept);
229
236
  }
230
- }, [page, props.displayId]);
231
- const run = () => page.live.admit(key, max);
237
+ }, [heights, props.displayId]);
238
+ const run = () => live.admit(key, max);
232
239
  const placeholder = props.renderPlaceholder ?? DefaultPlaceholder;
233
240
  return (_jsx("div", { ref: box, className: props.className, "data-porthole-display": props.displayId, "data-porthole-state": state, style: {
234
241
  position: "relative",
@@ -260,6 +267,11 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
260
267
  const fills = config.mode === "url" || frame.fill === true || config.layout.kind === "fill";
261
268
  // The latest props, read when the display calls back (never during render).
262
269
  const latest = useEffectEvent(() => frame);
270
+ // The provider's scheme and theme, read when used: a flip or a new themeKey (a new context
271
+ // value) re-themes the running display, never makes it again (#9, P074). What a display is
272
+ // made with comes from the provider's stable parts below.
273
+ const latestPage = useEffectEvent(() => page);
274
+ const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, hostInfo, locate, nonce, } = page;
263
275
  const notify = useEffectEvent((event, detail) => {
264
276
  switch (event) {
265
277
  case "initialized":
@@ -326,36 +338,36 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
326
338
  const declared = new Set(Object.keys(config.capabilities));
327
339
  for (const name of new Set([
328
340
  ...Object.keys(first.handlers ?? {}),
329
- ...Object.keys(page.handlers?.() ?? {}).filter((each) => declared.has(each)),
341
+ ...Object.keys(pageHandlers?.() ?? {}).filter((each) => declared.has(each)),
330
342
  ])) {
331
343
  handlers[name] = (args, context) => (latest().handlers?.[name] ??
332
- page.handlers?.()?.[name])?.(args, named(context));
344
+ pageHandlers?.()?.[name])?.(args, named(context));
333
345
  }
334
346
  // Copy buttons without a handler of the host's: the provider's, which shows a toast.
335
347
  if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
336
- const fallback = page.copyText;
348
+ const fallback = pageCopyText;
337
349
  if (fallback !== undefined) {
338
350
  handlers.copyText = (args, context) => fallback(args, named(context));
339
351
  }
340
352
  }
341
- const asks = first.confirm !== undefined || page.confirm !== undefined;
353
+ const asks = first.confirm !== undefined || pageConfirm !== undefined;
342
354
  let display;
343
355
  try {
344
356
  display = createHost(config, {
345
357
  handlers,
346
358
  ...(asks
347
359
  ? {
348
- confirm: (request, proceed) => (latest().confirm ?? page.confirm ?? (() => Promise.resolve(false)))({ ...request, display: { id: latest().displayId, title: latest().title } }, proceed),
360
+ confirm: (request, proceed) => (latest().confirm ?? pageConfirm ?? (() => Promise.resolve(false)))({ ...request, display: { id: latest().displayId, title: latest().title } }, proceed),
349
361
  }
350
362
  : {}),
351
- theme: (each) => (latest().theme ?? page.theme)?.(each) ?? {},
352
- ...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
353
- ...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
354
- ...(page.nonce === undefined ? {} : { nonce: page.nonce }),
363
+ theme: (each) => (latest().theme ?? latestPage().theme)?.(each) ?? {},
364
+ ...(hostInfo === undefined ? {} : { hostInfo }),
365
+ ...(locate === undefined ? {} : { locator: { locate } }),
366
+ ...(nonce === undefined ? {} : { nonce }),
355
367
  }).mount(container, {
356
368
  displayId: first.displayId,
357
369
  title: first.title,
358
- scheme: first.scheme ?? page.scheme ?? "light",
370
+ scheme: first.scheme ?? latestPage().scheme ?? "light",
359
371
  initialHeightPx: startHeight,
360
372
  ...(view === undefined ? {} : { document: view }),
361
373
  ...(instance === undefined ? {} : { instance }),
@@ -392,9 +404,22 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
392
404
  display.destroy();
393
405
  handle.current = null;
394
406
  };
395
- // A new display only for a new config, document, instance or page (or generation, by key);
396
- // content, theme, handlers, id and title are fed to the running one.
397
- }, [config, view, instance, page, startHeight, fills]);
407
+ // A new display only for a new config, document or instance, or what the provider makes
408
+ // displays with (its nonce, hostInfo by value, whether it locates or confirms; generation, by
409
+ // key). Content, scheme, theme, handlers, id and title are fed to the running one.
410
+ }, [
411
+ config,
412
+ view,
413
+ instance,
414
+ startHeight,
415
+ fills,
416
+ pageHandlers,
417
+ pageCopyText,
418
+ pageConfirm,
419
+ hostInfo,
420
+ locate,
421
+ nonce,
422
+ ]);
398
423
  useEffect(() => {
399
424
  if (content !== undefined) {
400
425
  handle.current?.setContent(content, { partial: partial === true });
@@ -453,6 +478,21 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
453
478
  handle.current?.refreshTheme();
454
479
  }
455
480
  }, [themeKey, mountThemeKey]);
481
+ // A new theme function (tokens a host passes inline): its values reach the running display
482
+ // where they changed for the scheme it shows (a flip re-reads them itself), P074.
483
+ const themeOf = frame.theme ?? page.theme;
484
+ const themed = useRef(null);
485
+ useEffect(() => {
486
+ if (themeOf === undefined) {
487
+ return;
488
+ }
489
+ const now = `${scheme}\n${JSON.stringify(themeOf(scheme))}`;
490
+ const before = themed.current;
491
+ themed.current = now;
492
+ if (before !== null && before !== now && before.startsWith(`${scheme}\n`)) {
493
+ handle.current?.refreshTheme();
494
+ }
495
+ }, [themeOf, scheme]);
456
496
  return (_jsxs("div", { "data-porthole-ready": String(ready), style: {
457
497
  position: "relative",
458
498
  // A url-mode app fills the frame's box (give PortholeFrame a height); the rest size to content.
@@ -8,7 +8,7 @@
8
8
  * theme={tokensFor} onError={report} />
9
9
  * </PortholeProvider>
10
10
  */
11
- export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type PortholeProviderProps, } from "./frame.tsx";
11
+ export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type ConfirmActions, type PortholeProviderProps, } from "./frame.tsx";
12
12
  export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
13
13
  export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, type PortholeFallbackProps, type PortholeViewProps, } from "./view.tsx";
14
14
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, type CopyNotice, type CopyToastProps, } from "./toast.tsx";
@@ -10,8 +10,13 @@ function useClient() {
10
10
  return client;
11
11
  }
12
12
  /** The client's meta, as a React value (re-renders when frames start or stop being served). */
13
+ /**
14
+ * The client's meta. On the server too (P074): a client made with the meta it will start with
15
+ * (`portholeClient({ meta })`) renders the frame's placeholder or the fallback there, and the
16
+ * page hydrates from the same.
17
+ */
13
18
  function useMeta(client) {
14
- return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => null);
19
+ return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => client.meta());
15
20
  }
16
21
  function DefaultFallback({ title, message, link }) {
17
22
  return (_jsxs("div", { "data-porthole-fallback": "", role: "status", style: { padding: 16 }, children: [_jsx("strong", { children: title }), " ", _jsx("span", { children: message }), " ", link === null ? null : (_jsx("a", { href: link, target: "_blank", rel: "noopener", children: "Open in a new tab" }))] }));
@@ -154,7 +154,8 @@ export interface EntryOptions<V> {
154
154
  */
155
155
  readonly at: (scope: string, path: string, viewer: V | null, request: Request) => Awaitable<InstanceRef | null | undefined>;
156
156
  /**
157
- * The app's own sign-in, which comes back to `returnTo` (the authorize URL) once signed in.
157
+ * The app's own sign-in, which comes back to `returnTo` (the authorize URL, as `authorizeUrl`
158
+ * names the app, with the entry's state) once signed in.
158
159
  * Only ever on a tab: in a frame, the person is asked to open a new tab instead. `entry` is the
159
160
  * address being opened, decoded (P070).
160
161
  */
@@ -169,9 +170,10 @@ export interface EntryOptions<V> {
169
170
  };
170
171
  /**
171
172
  * The clean path of an instance (the reverse of `at`), or null: `issue` then answers its clean
172
- * address as `link` (P072), for "open in a new tab" and "copy link".
173
+ * address as `link` (P072), for "open in a new tab" and "copy link". It may look it up (a
174
+ * promise, P074); where it fails, the frame comes without a link.
173
175
  */
174
- readonly pathOf?: (instance: InstanceRef) => string | null;
176
+ readonly pathOf?: (instance: InstanceRef, request: Request) => Awaitable<string | null>;
175
177
  /**
176
178
  * A viewer handoff, for an app whose page authenticates with a token rather than a cookie
177
179
  * (P072): `POST <prefix>/handoff`, made with the app's own credential, leaves a short-lived key
@@ -90,10 +90,17 @@ export function createContentHost(options) {
90
90
  if (options.configs === undefined && options.displays === undefined) {
91
91
  throw new TypeError("createContentHost needs configs or displays");
92
92
  }
93
- const secret = typeof options.secret === "string" ? utf8(options.secret.trim()) : options.secret;
93
+ // The secret as given (an unset environment variable: none), checked with the domain below.
94
+ const secret = typeof options.secret === "string"
95
+ ? utf8(options.secret.trim())
96
+ : options.secret instanceof Uint8Array
97
+ ? options.secret
98
+ : null;
94
99
  const healthLabel = gate?.label ?? DEFAULT_HEALTH_LABEL;
95
100
  // The id Porthole's health check answers with: keyed, so another deployment's answer fails.
96
- const healthId = base64url(hmacSha256(secret, utf8("porthole/health"))).slice(0, 22);
101
+ const healthId = secret === null || secret.byteLength < 32
102
+ ? ""
103
+ : base64url(hmacSha256(secret, utf8("porthole/health"))).slice(0, 22);
97
104
  const appReserved = reservedLabels(options.reserved);
98
105
  let domain = null;
99
106
  let server = null;
@@ -105,6 +112,13 @@ export function createContentHost(options) {
105
112
  ? options.domain
106
113
  : contentDomain(options.domain, { appOrigins: options.appOrigins });
107
114
  if (domain !== null) {
115
+ // Said plainly where it's missing, as where it's short (P074).
116
+ if (secret === null) {
117
+ throw new TypeError("createContentHost needs a secret: at least 32 random bytes (set PORTHOLE_SECRET; npx porthole secret makes one)");
118
+ }
119
+ if (secret.byteLength < 32) {
120
+ throw new TypeError("The secret must be at least 32 random bytes (set PORTHOLE_SECRET; npx porthole secret makes one)");
121
+ }
108
122
  if (options.entry !== undefined && options.name?.scopeOf === undefined) {
109
123
  throw new TypeError("Redirect entry needs a naming that says which scope a label names (prefixedName)");
110
124
  }
@@ -302,7 +316,8 @@ export function createContentHost(options) {
302
316
  };
303
317
  // The viewer handoff (P072): a key Porthole signs, naming the app's viewer until a time, in a
304
318
  // cookie only the prefix's routes get. Never the app's own credential.
305
- const handoffKey = hmacSha256(secret, utf8("porthole/handoff"));
319
+ // None where the secret can't sign (then nothing is served, and no handoff made or taken).
320
+ const handoffKey = secret === null || secret.byteLength < 32 ? null : hmacSha256(secret, utf8("porthole/handoff"));
306
321
  const secureApp = (options.appOrigins[0] ?? "").startsWith("https:");
307
322
  const handoffName = secureApp ? "__Secure-porthole-handoff" : "porthole-handoff";
308
323
  const handoffCookie = (value, maxAge) => [
@@ -313,14 +328,14 @@ export function createContentHost(options) {
313
328
  `Max-Age=${maxAge}`,
314
329
  ...(secureApp ? ["Secure"] : []),
315
330
  ].join("; ");
316
- const signHandoff = (id, until) => {
331
+ const signHandoff = (key, id, until) => {
317
332
  const payload = base64url(utf8(JSON.stringify({ h: 1, v: id, x: until })));
318
- return `${payload}.${base64url(hmacSha256(handoffKey, utf8(payload)))}`;
333
+ return `${payload}.${base64url(hmacSha256(key, utf8(payload)))}`;
319
334
  };
320
335
  /** The viewer a request's handoff cookie names, if it is good. */
321
336
  const handedOver = async (request) => {
322
337
  const handoff = options.entry?.handoff;
323
- if (handoff === undefined) {
338
+ if (handoff === undefined || handoffKey === null) {
324
339
  return null;
325
340
  }
326
341
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
@@ -356,14 +371,25 @@ export function createContentHost(options) {
356
371
  }
357
372
  return null;
358
373
  };
374
+ /**
375
+ * Where the person comes back after signing in: the authorize route as the app is reached
376
+ * (`authorizeUrl`'s origin and path), with this request's query (its state). Never the request's
377
+ * own URL, whose origin behind a TLS edge or a dev proxy isn't the app's (P074).
378
+ */
379
+ const returnOf = (request) => {
380
+ const back = new URL(authorizeUrl);
381
+ back.search = new URL(request.url).search;
382
+ return back.href;
383
+ };
359
384
  /** The app's sign-in: its own `signIn`, or its single-page route with `next`. */
360
385
  const signInWith = async (entry, request, context) => {
386
+ const returnTo = returnOf(request);
361
387
  if (entry.signIn !== undefined) {
362
- return entry.signIn(request.url, request, context);
388
+ return entry.signIn(returnTo, request, context);
363
389
  }
364
390
  const route = entry.spa?.route ?? "/";
365
- const to = new URL(route, options.appOrigins[0]);
366
- to.searchParams.set("next", request.url);
391
+ const to = new URL(route, new URL(authorizeUrl).origin);
392
+ to.searchParams.set("next", returnTo);
367
393
  return new Response(null, {
368
394
  status: 303,
369
395
  headers: { location: to.href, "cache-control": "no-store", "referrer-policy": "no-referrer" },
@@ -456,10 +482,10 @@ export function createContentHost(options) {
456
482
  catch (error) {
457
483
  return refusal(409, "refused", error instanceof Error ? error.message : String(error));
458
484
  }
459
- // The clean address, where the app says the instance's path (P072).
460
- const path = options.entry?.pathOf?.(instance) ?? null;
485
+ // The clean address, where the app says the instance's path (P072, P074).
461
486
  let link = null;
462
487
  try {
488
+ const path = (await options.entry?.pathOf?.(instance, request)) ?? null;
463
489
  link = path === null ? null : server.urlOf(instance.scope, path);
464
490
  }
465
491
  catch {
@@ -555,7 +581,10 @@ export function createContentHost(options) {
555
581
  if (typeof id !== "string" || id.length === 0 || id.length > 512) {
556
582
  return refusal(500, "failed", "entry.handoff.id gave no id (1 to 512 characters)");
557
583
  }
558
- const key = signHandoff(id, Date.now() + HANDOFF_SECONDS * 1_000);
584
+ if (handoffKey === null) {
585
+ return refusal(503, "unavailable", "The content domain isn't served");
586
+ }
587
+ const key = signHandoff(handoffKey, id, Date.now() + HANDOFF_SECONDS * 1_000);
559
588
  return new Response(null, {
560
589
  status: 204,
561
590
  headers: {