@botiverse/porthole 0.2.4 → 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.
- package/README.md +17 -11
- package/dist/check/check.d.ts +100 -0
- package/dist/check/check.js +247 -0
- package/dist/check/drivers.d.ts +43 -0
- package/dist/check/drivers.js +181 -0
- package/dist/check/index.d.ts +8 -0
- package/dist/check/index.js +8 -0
- package/dist/check/instrument.d.ts +71 -0
- package/dist/check/instrument.js +84 -0
- package/dist/check/lint.d.ts +21 -0
- package/dist/check/lint.js +131 -0
- package/dist/check/page-source.d.ts +2 -0
- package/dist/check/page-source.js +2 -0
- package/dist/check/page.d.ts +13 -0
- package/dist/check/page.js +170 -0
- package/dist/check/tools.d.ts +61 -0
- package/dist/check/tools.js +140 -0
- package/dist/conformance/host-kit.d.ts +26 -5
- package/dist/conformance/host-kit.js +46 -22
- package/dist/conformance/index.d.ts +1 -1
- package/dist/conformance/reporter.d.ts +14 -0
- package/dist/conformance/reporter.js +28 -0
- package/dist/displays/displays.d.ts +61 -0
- package/dist/displays/displays.js +113 -0
- package/dist/host/client.d.ts +110 -0
- package/dist/host/client.js +274 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +6 -0
- package/dist/node/index.d.ts +26 -1
- package/dist/node/index.js +91 -1
- package/dist/react/frame.d.ts +79 -3
- package/dist/react/frame.js +183 -42
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +1 -0
- package/dist/react/view.d.ts +54 -0
- package/dist/react/view.js +151 -0
- package/dist/server/bootstrap.d.ts +27 -0
- package/dist/server/bootstrap.js +63 -0
- package/dist/server/host.d.ts +77 -8
- package/dist/server/host.js +268 -11
- package/dist/server/index.d.ts +4 -2
- package/dist/server/index.js +3 -1
- package/dist/server/pages.d.ts +19 -0
- package/dist/server/pages.js +8 -0
- package/dist/server/proxy.d.ts +24 -0
- package/dist/server/proxy.js +67 -0
- package/dist/server/server.js +14 -1
- package/dist/server/types.d.ts +8 -0
- package/docs/ADOPTING.md +278 -108
- package/docs/DECISIONS.md +280 -0
- package/docs/DESIGN.md +84 -2
- package/examples/app.mjs +82 -78
- package/examples/conformance/page.spec.mjs +23 -0
- package/examples/conformance/playwright.config.mjs +3 -2
- package/examples/conformance/porthole.spec.mjs +6 -3
- package/examples/displays.mjs +21 -0
- package/examples/mcp/server.mjs +121 -0
- package/examples/node/server.mjs +16 -34
- package/examples/workers/worker.mjs +19 -7
- package/package.json +13 -1
- package/src/check/check.ts +386 -0
- package/src/check/drivers.ts +242 -0
- package/src/check/index.ts +22 -0
- package/src/check/instrument.ts +138 -0
- package/src/check/lint.ts +238 -0
- package/src/check/page-source.ts +19 -0
- package/src/check/page.ts +230 -0
- package/src/check/tools.ts +206 -0
- package/src/conformance/host-kit.ts +82 -27
- package/src/conformance/index.ts +1 -0
- package/src/conformance/reporter.ts +38 -0
- package/src/displays/displays.ts +191 -0
- package/src/host/client.ts +395 -0
- package/src/index.ts +25 -0
- package/src/node/index.ts +112 -2
- package/src/react/frame.tsx +271 -57
- package/src/react/index.ts +9 -0
- package/src/react/view.tsx +237 -0
- package/src/server/bootstrap.ts +97 -0
- package/src/server/host.ts +372 -18
- package/src/server/index.ts +11 -1
- package/src/server/pages.ts +28 -0
- package/src/server/proxy.ts +86 -0
- package/src/server/server.ts +26 -2
- package/src/server/types.ts +5 -0
package/src/server/host.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
/**
|
|
96
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
158
|
-
|
|
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
|
|
@@ -171,11 +201,38 @@ export interface EntryOptions<V> {
|
|
|
171
201
|
request: Request,
|
|
172
202
|
) => Awaitable<InstanceRef | null | undefined>;
|
|
173
203
|
/**
|
|
174
|
-
* The app's own sign-in, which comes back to `returnTo` (the authorize URL
|
|
204
|
+
* The app's own sign-in, which comes back to `returnTo` (the authorize URL, as `authorizeUrl`
|
|
205
|
+
* names the app, with the entry's state) once signed in.
|
|
175
206
|
* Only ever on a tab: in a frame, the person is asked to open a new tab instead. `entry` is the
|
|
176
207
|
* address being opened, decoded (P070).
|
|
177
208
|
*/
|
|
178
|
-
readonly signIn
|
|
209
|
+
readonly signIn?: (
|
|
210
|
+
returnTo: string,
|
|
211
|
+
request: Request,
|
|
212
|
+
entry: EntryContext,
|
|
213
|
+
) => Awaitable<Response>;
|
|
214
|
+
/**
|
|
215
|
+
* A single-page app's sign-in route (P072): the default `signIn` sends the person there with
|
|
216
|
+
* `?next=<authorize URL>`, and the app goes on to `next` once signed in (check it with
|
|
217
|
+
* `entryTarget`).
|
|
218
|
+
*/
|
|
219
|
+
readonly spa?: { readonly route: string };
|
|
220
|
+
/**
|
|
221
|
+
* The clean path of an instance (the reverse of `at`), or null: `issue` then answers its clean
|
|
222
|
+
* address as `link` (P072), for "open in a new tab" and "copy link". It may look it up (a
|
|
223
|
+
* promise, P074); where it fails, the frame comes without a link.
|
|
224
|
+
*/
|
|
225
|
+
readonly pathOf?: (instance: InstanceRef, request: Request) => Awaitable<string | null>;
|
|
226
|
+
/**
|
|
227
|
+
* A viewer handoff, for an app whose page authenticates with a token rather than a cookie
|
|
228
|
+
* (P072): `POST <prefix>/handoff`, made with the app's own credential, leaves a short-lived key
|
|
229
|
+
* for its viewer in a cookie only the authorize route gets. `id` says who the viewer is (at
|
|
230
|
+
* most 512 characters); `viewer` turns it back into the app's viewer, or null.
|
|
231
|
+
*/
|
|
232
|
+
readonly handoff?: {
|
|
233
|
+
readonly id: (viewer: V) => string;
|
|
234
|
+
readonly viewer: (id: string, request: Request) => Awaitable<V | null>;
|
|
235
|
+
};
|
|
179
236
|
/**
|
|
180
237
|
* The app's refusal page on a tab (a frame gets Porthole's plain one), for the address in
|
|
181
238
|
* `entry`. Nothing (null, undefined): Porthole's own (P070).
|
|
@@ -230,6 +287,24 @@ export interface ContentHost<V> {
|
|
|
230
287
|
* nothing is served. Opens through redirect entry (`entry`); frames take tickets (`issue`).
|
|
231
288
|
*/
|
|
232
289
|
urlOf(scope: string, path?: string): string | null;
|
|
290
|
+
/** Where `routes` answers (`/porthole`). */
|
|
291
|
+
readonly prefix: string;
|
|
292
|
+
/**
|
|
293
|
+
* The app's Porthole routes in one handler (P072): `POST <prefix>/frames` (`issue`), `GET
|
|
294
|
+
* <prefix>/authorize`, `GET <prefix>/meta` (`clientMeta`), `POST`/`DELETE <prefix>/handoff`.
|
|
295
|
+
* Null for any other request: the app's own routes.
|
|
296
|
+
*/
|
|
297
|
+
routes(
|
|
298
|
+
viewerOf: (request: Request) => Awaitable<V | null>,
|
|
299
|
+
): (request: Request) => Promise<Response | null>;
|
|
300
|
+
/** What `GET <prefix>/meta` answers the page. */
|
|
301
|
+
clientMeta(): ContentClientMeta;
|
|
302
|
+
/** The viewer handoff (`entry.handoff`), as a fetch handler: POST sets it, DELETE clears it. */
|
|
303
|
+
handoff(
|
|
304
|
+
viewerOf: (request: Request) => Awaitable<V | null>,
|
|
305
|
+
): (request: Request) => Promise<Response>;
|
|
306
|
+
/** Drops cached `authorize` answers (`authorizeTtlSeconds`): all, or a scope's, or a subject's. */
|
|
307
|
+
forget(filter?: { readonly scope?: string; readonly subject?: string }): void;
|
|
233
308
|
/** The app's authorize route for redirect entry (`entry.authorizeUrl`), as a fetch handler. */
|
|
234
309
|
authorize(
|
|
235
310
|
viewerOf: (request: Request) => Awaitable<V | null>,
|
|
@@ -276,6 +351,34 @@ const plain = (status: number, text: string): Response =>
|
|
|
276
351
|
|
|
277
352
|
type FrameBlockReason = Parameters<typeof appStatusPage>[4];
|
|
278
353
|
|
|
354
|
+
/** How long a viewer handoff holds (P072): the app's page refreshes it on load and focus. */
|
|
355
|
+
const HANDOFF_SECONDS = 600;
|
|
356
|
+
|
|
357
|
+
/** The kit's events to the app's `log`: its function, or its logger at each event's level. */
|
|
358
|
+
function logOf(given: ContentHostOptions<unknown>["log"]): (event: ContentHostEvent) => void {
|
|
359
|
+
if (given === undefined) {
|
|
360
|
+
return () => {};
|
|
361
|
+
}
|
|
362
|
+
if (typeof given === "function") {
|
|
363
|
+
return given;
|
|
364
|
+
}
|
|
365
|
+
return (event) => {
|
|
366
|
+
const message =
|
|
367
|
+
event.evt === "porthole.content.healthy"
|
|
368
|
+
? "Porthole: the content domain answers; frames are served"
|
|
369
|
+
: event.evt === "porthole.content.unhealthy"
|
|
370
|
+
? `Porthole: frames aren't served: ${event.reason}`
|
|
371
|
+
: `Porthole: the content domain can't be served (${event.code}): ${event.reason}`;
|
|
372
|
+
if (event.evt === "porthole.content.healthy") {
|
|
373
|
+
given.info?.(message, event);
|
|
374
|
+
} else if (event.evt === "porthole.content.unhealthy") {
|
|
375
|
+
given.warn?.(message, event);
|
|
376
|
+
} else {
|
|
377
|
+
given.error?.(message, event);
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
279
382
|
/** The CSP source for an authorize route: its origin and path, so nothing else there frames. */
|
|
280
383
|
const authorizeSource = (url: string): string => {
|
|
281
384
|
const parsed = new URL(url);
|
|
@@ -295,11 +398,29 @@ const fetchProbe: HealthProbe = async (url, timeoutMs) => {
|
|
|
295
398
|
|
|
296
399
|
export function createContentHost<V>(options: ContentHostOptions<V>): ContentHost<V> {
|
|
297
400
|
const gate = options.health;
|
|
298
|
-
const log = options.log
|
|
299
|
-
const
|
|
401
|
+
const log = logOf(options.log);
|
|
402
|
+
const prefix = (options.prefix ?? "/porthole").replace(/\/+$/u, "");
|
|
403
|
+
if (!/^\/[\w./-]*$/u.test(prefix)) {
|
|
404
|
+
throw new TypeError("A route prefix is a path: /porthole");
|
|
405
|
+
}
|
|
406
|
+
const authorizeUrl =
|
|
407
|
+
options.entry?.authorizeUrl ?? `${options.appOrigins[0] ?? ""}${prefix}/authorize`;
|
|
408
|
+
if (options.configs === undefined && options.displays === undefined) {
|
|
409
|
+
throw new TypeError("createContentHost needs configs or displays");
|
|
410
|
+
}
|
|
411
|
+
// The secret as given (an unset environment variable: none), checked with the domain below.
|
|
412
|
+
const secret: Uint8Array | null =
|
|
413
|
+
typeof options.secret === "string"
|
|
414
|
+
? utf8(options.secret.trim())
|
|
415
|
+
: options.secret instanceof Uint8Array
|
|
416
|
+
? options.secret
|
|
417
|
+
: null;
|
|
300
418
|
const healthLabel = gate?.label ?? DEFAULT_HEALTH_LABEL;
|
|
301
419
|
// The id Porthole's health check answers with: keyed, so another deployment's answer fails.
|
|
302
|
-
const healthId =
|
|
420
|
+
const healthId =
|
|
421
|
+
secret === null || secret.byteLength < 32
|
|
422
|
+
? ""
|
|
423
|
+
: base64url(hmacSha256(secret, utf8("porthole/health"))).slice(0, 22);
|
|
303
424
|
const appReserved = reservedLabels(options.reserved);
|
|
304
425
|
|
|
305
426
|
let domain: ContentDomainInfo | null = null;
|
|
@@ -313,13 +434,32 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
313
434
|
? options.domain
|
|
314
435
|
: contentDomain(options.domain, { appOrigins: options.appOrigins });
|
|
315
436
|
if (domain !== null) {
|
|
437
|
+
// Said plainly where it's missing, as where it's short (P074).
|
|
438
|
+
if (secret === null) {
|
|
439
|
+
throw new TypeError(
|
|
440
|
+
"createContentHost needs a secret: at least 32 random bytes (set PORTHOLE_SECRET; npx porthole secret makes one)",
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
if (secret.byteLength < 32) {
|
|
444
|
+
throw new TypeError(
|
|
445
|
+
"The secret must be at least 32 random bytes (set PORTHOLE_SECRET; npx porthole secret makes one)",
|
|
446
|
+
);
|
|
447
|
+
}
|
|
316
448
|
if (options.entry !== undefined && options.name?.scopeOf === undefined) {
|
|
317
449
|
throw new TypeError(
|
|
318
450
|
"Redirect entry needs a naming that says which scope a label names (prefixedName)",
|
|
319
451
|
);
|
|
320
452
|
}
|
|
453
|
+
const displays = options.displays;
|
|
321
454
|
configs =
|
|
322
|
-
|
|
455
|
+
options.configs === undefined
|
|
456
|
+
? (displays?.served(domain.source) ??
|
|
457
|
+
(() => {
|
|
458
|
+
throw new TypeError(displays?.problem(domain.source) ?? "No configs");
|
|
459
|
+
})())
|
|
460
|
+
: typeof options.configs === "function"
|
|
461
|
+
? options.configs(domain.source)
|
|
462
|
+
: options.configs;
|
|
323
463
|
server = createServer({
|
|
324
464
|
content: serverDomain(domain, {
|
|
325
465
|
...(options.name === undefined ? {} : { name: options.name }),
|
|
@@ -335,7 +475,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
335
475
|
? {}
|
|
336
476
|
: {
|
|
337
477
|
entry: {
|
|
338
|
-
authorizeUrl
|
|
478
|
+
authorizeUrl,
|
|
339
479
|
// Whether a clean address names anything, before a browser is sent away (P070).
|
|
340
480
|
named: async (label: string, path: string, request: Request) => {
|
|
341
481
|
const scope = options.name?.scopeOf?.(label) ?? null;
|
|
@@ -375,6 +515,19 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
375
515
|
}
|
|
376
516
|
|
|
377
517
|
const served = (): boolean => server !== null && view.state === "healthy";
|
|
518
|
+
// onServedChange: once per flip of served(), the first decision included.
|
|
519
|
+
let toldServed: boolean | null = null;
|
|
520
|
+
const tellServed = () => {
|
|
521
|
+
const now = served();
|
|
522
|
+
if (now !== toldServed && view.state !== "checking") {
|
|
523
|
+
toldServed = now;
|
|
524
|
+
try {
|
|
525
|
+
gate?.onServedChange?.(now);
|
|
526
|
+
} catch {
|
|
527
|
+
// The app's listener failing changes nothing here.
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
};
|
|
378
531
|
|
|
379
532
|
// The health gate: one check at a time, again after a minute while unhealthy, ten while healthy.
|
|
380
533
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
@@ -446,6 +599,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
446
599
|
// The app's listener failing changes nothing here.
|
|
447
600
|
}
|
|
448
601
|
}
|
|
602
|
+
tellServed();
|
|
449
603
|
running = null;
|
|
450
604
|
schedule();
|
|
451
605
|
return view;
|
|
@@ -498,7 +652,98 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
498
652
|
return top !== "" && appReserved(top) ? null : { url, label };
|
|
499
653
|
};
|
|
500
654
|
|
|
501
|
-
|
|
655
|
+
// The viewer handoff (P072): a key Porthole signs, naming the app's viewer until a time, in a
|
|
656
|
+
// cookie only the prefix's routes get. Never the app's own credential.
|
|
657
|
+
// None where the secret can't sign (then nothing is served, and no handoff made or taken).
|
|
658
|
+
const handoffKey =
|
|
659
|
+
secret === null || secret.byteLength < 32 ? null : hmacSha256(secret, utf8("porthole/handoff"));
|
|
660
|
+
const secureApp = (options.appOrigins[0] ?? "").startsWith("https:");
|
|
661
|
+
const handoffName = secureApp ? "__Secure-porthole-handoff" : "porthole-handoff";
|
|
662
|
+
const handoffCookie = (value: string, maxAge: number): string =>
|
|
663
|
+
[
|
|
664
|
+
`${handoffName}=${value}`,
|
|
665
|
+
`Path=${prefix}`,
|
|
666
|
+
"HttpOnly",
|
|
667
|
+
"SameSite=Lax",
|
|
668
|
+
`Max-Age=${maxAge}`,
|
|
669
|
+
...(secureApp ? ["Secure"] : []),
|
|
670
|
+
].join("; ");
|
|
671
|
+
const signHandoff = (key: Uint8Array, id: string, until: number): string => {
|
|
672
|
+
const payload = base64url(utf8(JSON.stringify({ h: 1, v: id, x: until })));
|
|
673
|
+
return `${payload}.${base64url(hmacSha256(key, utf8(payload)))}`;
|
|
674
|
+
};
|
|
675
|
+
/** The viewer a request's handoff cookie names, if it is good. */
|
|
676
|
+
const handedOver = async (request: Request): Promise<V | null> => {
|
|
677
|
+
const handoff = options.entry?.handoff;
|
|
678
|
+
if (handoff === undefined || handoffKey === null) {
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
682
|
+
const at = part.indexOf("=");
|
|
683
|
+
if (at < 0 || part.slice(0, at).trim() !== handoffName) {
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
const [payload = "", mac = "", ...rest] = part
|
|
687
|
+
.slice(at + 1)
|
|
688
|
+
.trim()
|
|
689
|
+
.split(".");
|
|
690
|
+
const given = fromBase64url(mac);
|
|
691
|
+
if (
|
|
692
|
+
rest.length > 0 ||
|
|
693
|
+
given === null ||
|
|
694
|
+
!timingSafeEqual(given, hmacSha256(handoffKey, utf8(payload)))
|
|
695
|
+
) {
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
const bytes = fromBase64url(payload);
|
|
699
|
+
let said: unknown = null;
|
|
700
|
+
try {
|
|
701
|
+
said = bytes === null ? null : JSON.parse(fromUtf8(bytes));
|
|
702
|
+
} catch {
|
|
703
|
+
said = null;
|
|
704
|
+
}
|
|
705
|
+
if (
|
|
706
|
+
isRecord(said) &&
|
|
707
|
+
said.h === 1 &&
|
|
708
|
+
typeof said.v === "string" &&
|
|
709
|
+
typeof said.x === "number" &&
|
|
710
|
+
said.x > Date.now()
|
|
711
|
+
) {
|
|
712
|
+
return handoff.viewer(said.v, request);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return null;
|
|
716
|
+
};
|
|
717
|
+
/**
|
|
718
|
+
* Where the person comes back after signing in: the authorize route as the app is reached
|
|
719
|
+
* (`authorizeUrl`'s origin and path), with this request's query (its state). Never the request's
|
|
720
|
+
* own URL, whose origin behind a TLS edge or a dev proxy isn't the app's (P074).
|
|
721
|
+
*/
|
|
722
|
+
const returnOf = (request: Request): string => {
|
|
723
|
+
const back = new URL(authorizeUrl);
|
|
724
|
+
back.search = new URL(request.url).search;
|
|
725
|
+
return back.href;
|
|
726
|
+
};
|
|
727
|
+
/** The app's sign-in: its own `signIn`, or its single-page route with `next`. */
|
|
728
|
+
const signInWith = async (
|
|
729
|
+
entry: EntryOptions<V>,
|
|
730
|
+
request: Request,
|
|
731
|
+
context: EntryContext,
|
|
732
|
+
): Promise<Response> => {
|
|
733
|
+
const returnTo = returnOf(request);
|
|
734
|
+
if (entry.signIn !== undefined) {
|
|
735
|
+
return entry.signIn(returnTo, request, context);
|
|
736
|
+
}
|
|
737
|
+
const route = entry.spa?.route ?? "/";
|
|
738
|
+
const to = new URL(route, new URL(authorizeUrl).origin);
|
|
739
|
+
to.searchParams.set("next", returnTo);
|
|
740
|
+
return new Response(null, {
|
|
741
|
+
status: 303,
|
|
742
|
+
headers: { location: to.href, "cache-control": "no-store", "referrer-policy": "no-referrer" },
|
|
743
|
+
});
|
|
744
|
+
};
|
|
745
|
+
|
|
746
|
+
const host: ContentHost<V> = {
|
|
502
747
|
get domain() {
|
|
503
748
|
return domain;
|
|
504
749
|
},
|
|
@@ -511,7 +756,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
511
756
|
: [
|
|
512
757
|
...embedderFrameSourcesOf(Object.values(configs)),
|
|
513
758
|
// A frame on a clean address goes by the authorize route (only that path).
|
|
514
|
-
...(options.entry === undefined ? [] : [authorizeSource(
|
|
759
|
+
...(options.entry === undefined ? [] : [authorizeSource(authorizeUrl)]),
|
|
515
760
|
],
|
|
516
761
|
|
|
517
762
|
owns: (request) => routeOf(request) !== null,
|
|
@@ -597,7 +842,15 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
597
842
|
} catch (error) {
|
|
598
843
|
return refusal(409, "refused", error instanceof Error ? error.message : String(error));
|
|
599
844
|
}
|
|
600
|
-
|
|
845
|
+
// The clean address, where the app says the instance's path (P072, P074).
|
|
846
|
+
let link: string | null = null;
|
|
847
|
+
try {
|
|
848
|
+
const path = (await options.entry?.pathOf?.(instance, request)) ?? null;
|
|
849
|
+
link = path === null ? null : server.urlOf(instance.scope, path);
|
|
850
|
+
} catch {
|
|
851
|
+
link = null;
|
|
852
|
+
}
|
|
853
|
+
return json(201, link === null ? location : { ...location, link });
|
|
601
854
|
} catch {
|
|
602
855
|
return refusal(500, "failed", "The app's policy failed");
|
|
603
856
|
}
|
|
@@ -610,6 +863,106 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
610
863
|
health: gate === undefined ? null : view,
|
|
611
864
|
}),
|
|
612
865
|
|
|
866
|
+
prefix,
|
|
867
|
+
|
|
868
|
+
clientMeta: () => ({
|
|
869
|
+
served: served(),
|
|
870
|
+
contentSource: domain?.source ?? null,
|
|
871
|
+
frameSources: host.frameSources,
|
|
872
|
+
health:
|
|
873
|
+
gate === undefined
|
|
874
|
+
? null
|
|
875
|
+
: { state: view.state, ...(view.reason === undefined ? {} : { reason: view.reason }) },
|
|
876
|
+
}),
|
|
877
|
+
|
|
878
|
+
routes(viewerOf) {
|
|
879
|
+
const issue = host.issue(viewerOf);
|
|
880
|
+
const authorize = host.authorize(viewerOf);
|
|
881
|
+
const handoff = host.handoff(viewerOf);
|
|
882
|
+
return async (request) => {
|
|
883
|
+
let pathname: string;
|
|
884
|
+
try {
|
|
885
|
+
pathname = new URL(request.url).pathname;
|
|
886
|
+
} catch {
|
|
887
|
+
return null;
|
|
888
|
+
}
|
|
889
|
+
if (!pathname.startsWith(`${prefix}/`)) {
|
|
890
|
+
return null;
|
|
891
|
+
}
|
|
892
|
+
const method = request.method.toUpperCase();
|
|
893
|
+
switch (pathname.slice(prefix.length)) {
|
|
894
|
+
case "/frames":
|
|
895
|
+
return issue(request);
|
|
896
|
+
case "/authorize":
|
|
897
|
+
return authorize(request);
|
|
898
|
+
case "/meta":
|
|
899
|
+
return method === "GET" || method === "HEAD"
|
|
900
|
+
? json(200, host.clientMeta())
|
|
901
|
+
: refusal(405, "method", "GET here");
|
|
902
|
+
case "/handoff":
|
|
903
|
+
return handoff(request);
|
|
904
|
+
default:
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
},
|
|
909
|
+
|
|
910
|
+
handoff(viewerOf) {
|
|
911
|
+
return async (request) => {
|
|
912
|
+
const method = request.method.toUpperCase();
|
|
913
|
+
if (method !== "POST" && method !== "DELETE") {
|
|
914
|
+
return refusal(405, "method", "POST (or DELETE) here");
|
|
915
|
+
}
|
|
916
|
+
const handoff = options.entry?.handoff;
|
|
917
|
+
if (handoff === undefined) {
|
|
918
|
+
return refusal(404, "not-found", "This app has no viewer handoff (entry.handoff)");
|
|
919
|
+
}
|
|
920
|
+
// The app's own page only: a request from another site never sets or clears it.
|
|
921
|
+
const origin = request.headers.get("origin");
|
|
922
|
+
const site = request.headers.get("sec-fetch-site");
|
|
923
|
+
if (
|
|
924
|
+
(origin !== null && !options.appOrigins.includes(origin)) ||
|
|
925
|
+
(origin === null && site !== null && site !== "same-origin")
|
|
926
|
+
) {
|
|
927
|
+
return refusal(403, "cross-site", "Only the app's own page hands its viewer over");
|
|
928
|
+
}
|
|
929
|
+
if (method === "DELETE") {
|
|
930
|
+
return new Response(null, {
|
|
931
|
+
status: 204,
|
|
932
|
+
headers: { "set-cookie": handoffCookie("", 0), "cache-control": "no-store" },
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
let viewer: V | null;
|
|
936
|
+
try {
|
|
937
|
+
viewer = await viewerOf(request);
|
|
938
|
+
} catch {
|
|
939
|
+
return refusal(500, "failed", "The app couldn't tell who is asking");
|
|
940
|
+
}
|
|
941
|
+
if (viewer === null) {
|
|
942
|
+
return refusal(401, "unauthenticated", "Sign in first: the handoff names a viewer");
|
|
943
|
+
}
|
|
944
|
+
const id = handoff.id(viewer);
|
|
945
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 512) {
|
|
946
|
+
return refusal(500, "failed", "entry.handoff.id gave no id (1 to 512 characters)");
|
|
947
|
+
}
|
|
948
|
+
if (handoffKey === null) {
|
|
949
|
+
return refusal(503, "unavailable", "The content domain isn't served");
|
|
950
|
+
}
|
|
951
|
+
const key = signHandoff(handoffKey, id, Date.now() + HANDOFF_SECONDS * 1_000);
|
|
952
|
+
return new Response(null, {
|
|
953
|
+
status: 204,
|
|
954
|
+
headers: {
|
|
955
|
+
"set-cookie": handoffCookie(key, HANDOFF_SECONDS),
|
|
956
|
+
"cache-control": "no-store",
|
|
957
|
+
},
|
|
958
|
+
});
|
|
959
|
+
};
|
|
960
|
+
},
|
|
961
|
+
|
|
962
|
+
forget(filter = {}) {
|
|
963
|
+
server?.forget(filter);
|
|
964
|
+
},
|
|
965
|
+
|
|
613
966
|
urlOf(scope, path = "/") {
|
|
614
967
|
return server === null || !served() ? null : server.urlOf(scope, path);
|
|
615
968
|
},
|
|
@@ -668,7 +1021,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
668
1021
|
const scope = options.name?.scopeOf?.(state.label) ?? null;
|
|
669
1022
|
let viewer: V | null;
|
|
670
1023
|
try {
|
|
671
|
-
viewer = await viewerOf(request);
|
|
1024
|
+
viewer = (await viewerOf(request)) ?? (await handedOver(request));
|
|
672
1025
|
} catch {
|
|
673
1026
|
return appPage(
|
|
674
1027
|
500,
|
|
@@ -709,7 +1062,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
709
1062
|
"sign-in",
|
|
710
1063
|
method,
|
|
711
1064
|
)
|
|
712
|
-
: await entry
|
|
1065
|
+
: await signInWith(entry, request, context);
|
|
713
1066
|
}
|
|
714
1067
|
const status = instance === null ? 404 : 403;
|
|
715
1068
|
const own = framed ? null : await entry.refusal?.(status, request, context);
|
|
@@ -773,4 +1126,5 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
|
|
|
773
1126
|
}
|
|
774
1127
|
},
|
|
775
1128
|
};
|
|
1129
|
+
return host;
|
|
776
1130
|
}
|
package/src/server/index.ts
CHANGED
|
@@ -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 {
|
|
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,
|
package/src/server/pages.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/server/proxy.ts
CHANGED
|
@@ -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
|
+
};
|