@niwa-labs/web 0.0.0-stage → 0.0.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.
package/src/index.ts ADDED
@@ -0,0 +1,737 @@
1
+ /**
2
+ * index.ts — the web surface: a thin client of the core.
3
+ *
4
+ * It keeps no list of its own: the feed is computed from the journal through the core's
5
+ * observation API, and the actions are the ones the core describes. The caller is the web
6
+ * connection: one core client, opened with the id "web", so the host sees that caller and
7
+ * no other — and that caller speaks for the owner only when the instance is configured with
8
+ * `speaksFor: "owner"`; then it holds the owner's token, and a request is let in only with the
9
+ * cookie that the login link gives. Without that cookie a
10
+ * request is refused with 401 and reaches nothing.
11
+ * It listens on the loopback only, under a host name of its own (`niwa-<random>.localhost`) so that its cookie is not shared with
12
+ * another instance or another service, and refuses a request that names another host or origin.
13
+ *
14
+ * What a page may call is not a list kept here: a call goes to the host as it is, and the grant of the connection decides
15
+ * it. A call the grant refuses is answered 403.
16
+ *
17
+ * The routes:
18
+ *
19
+ * - `GET /login?secret=` — the one-time link the server prints: it sets the cookie;
20
+ * - `GET /` — the cockpit app, when the surface is given one, else the page of the composition;
21
+ * - `GET /assets/…`, `GET /modules/<id>/<hash>/…` — the app's files, and the client modules of the plugins, built for the
22
+ * browser from the source the host lists; every other address of the app is the app's page, which routes it;
23
+ * - `GET /api/viewer` — who is looking: the principal and the actions its grant lets it call;
24
+ * - `GET /api/catalogue` — the client modules the host lists, with the addresses they are served at;
25
+ * - `GET /api/info` — the actions the viewer may call, the position of the journal, journal field names, the harnesses
26
+ * with an agent action and the input schema of `session.start`;
27
+ * - `GET /api/history?after=&query=` — up to 128 records after a journal position that answer the record query in
28
+ * `query` (JSON: `types`, `filter`, `stream`; every record when absent);
29
+ * - `GET /api/events?after=&query=` — the records that answer the same query over SSE from a position (the journal's
30
+ * end is `seq` of `/api/info`), resuming from `Last-Event-ID` when present;
31
+ * - `GET /api/source?seq=` — the verified script of a workflow start, for the owner;
32
+ * - `POST /api/call` — call an action with `{action, input}`;
33
+ *
34
+ * The feed and trace routes:
35
+ *
36
+ * - `GET /events` — the feed over SSE, so the page follows the journal;
37
+ * - `GET /feed` — the feed as JSON;
38
+ * - `GET /trace/:id` — the page of one record: what it depends on and what grew from it;
39
+ * - `GET /trace-data/:id` — the chain as JSON;
40
+ * - `POST /resolve` — answer a paused invocation;
41
+ * - `POST /answer` — answer an open request.
42
+ */
43
+
44
+ import { randomBytes } from "node:crypto";
45
+
46
+ import { z } from "zod";
47
+
48
+ import { actionName, RESOLVE_ACTION, RecordQuerySchema, recordId, seq } from "@niwa-labs/core";
49
+ import { readOwnerToken, connect, RECORDS_READ_ACTION } from "@niwa-labs/client";
50
+ import type { ActionName, Description, RecordQuery, SpeaksFor } from "@niwa-labs/core";
51
+ import type { NiwaApi } from "@niwa-labs/client";
52
+
53
+ import { ASSETS_PREFIX, assetFile, catalogueOf, MODULES_PREFIX, ModuleBuilds, pageOf, typeOf } from "./app.ts";
54
+ import type { WebApp } from "./app.ts";
55
+ import { followFeed, readFeed } from "./feed.ts";
56
+ import { isDenied } from "./denial.ts";
57
+ import { viewerOf } from "./viewer.ts";
58
+ import { LOGIN_PATH, WebLogin } from "./login.ts";
59
+ import { runSource } from "./source.ts";
60
+ import { chainOf } from "./trace.ts";
61
+ import type { Chain } from "./trace.ts";
62
+
63
+ export { feedOf } from "./feed.ts";
64
+ export type { WebApp } from "./app.ts";
65
+ export type { Chain, ChainRecord } from "./trace.ts";
66
+
67
+ /**
68
+ * The name the web surface gives itself. Whether it speaks for the owner is its token's matter:
69
+ * with `speaksFor` the page answers a request addressed to the owner.
70
+ */
71
+ export const WEB_CLIENT_ID = "web";
72
+
73
+ /** The action that answers an open request, when the requests module has declared it. */
74
+ const ANSWER_ACTION = "request.answer";
75
+
76
+ /** What the web surface needs. */
77
+ export interface WebOptions {
78
+ /** The home of the running host: where the journal is. */
79
+ readonly home: string;
80
+ /** The port to listen on; 0 asks the system for a free one. */
81
+ readonly port?: number;
82
+ /**
83
+ * Speak for the owner: the surface connects with the owner's token. Without it the surface is
84
+ * a plain client, even if the owner's token file is readable.
85
+ */
86
+ readonly speaksFor?: SpeaksFor;
87
+ /**
88
+ * Actions with a check of their own: an input the schema alone does not refuse, an answer that is shaped before it is
89
+ * read. The web surface knows none by name: the composition that serves it (the umbrella) says which pages it carries.
90
+ * Whether a page may call them is the grant's matter, as for every action.
91
+ */
92
+ readonly ownerActions?: readonly OwnerAction[];
93
+ /** The pages the surface serves. The web surface draws none itself: the composition that serves it brings them. */
94
+ readonly pages: WebPages;
95
+ /**
96
+ * The cockpit app: its built files and the modules its client modules share. With it `/` is the app and the addresses of
97
+ * the app are its page; without it the surface serves only the pages above and the API.
98
+ */
99
+ readonly app?: WebApp;
100
+ }
101
+
102
+ /** The two pages of the web surface: the feed at `/` and the trace of one record. */
103
+ export interface WebPages {
104
+ feed(): string;
105
+ trace(recordId: string, chain: Chain): string;
106
+ }
107
+
108
+ /** The part of an action reference the page needs: its name and its two schemas. */
109
+ export interface OwnerActionRef {
110
+ readonly name: ActionName;
111
+ readonly input: z.ZodType;
112
+ readonly output: z.ZodType;
113
+ }
114
+
115
+ /** An action of the owner's page: the reference, and what the page checks around the call. */
116
+ export interface OwnerAction {
117
+ readonly ref: OwnerActionRef;
118
+ /** Refuse an input the schema alone does not: the answer is the reason, undefined when the input stands. */
119
+ readonly refuse?: (input: Record<string, unknown>) => string | undefined;
120
+ /** Shape what the action answered, then check it against the output schema. */
121
+ readonly shape?: (answer: unknown) => Promise<unknown>;
122
+ }
123
+
124
+ /** How a page calls: the checks some actions carry, and the shape of the body. The grant decides the rest. */
125
+ interface Calls {
126
+ readonly hooks: ReadonlyMap<string, OwnerAction>;
127
+ readonly body: z.ZodType<{ action: string; input?: unknown }>;
128
+ }
129
+
130
+ /** What a route needs beyond the request: the host, the login, the open streams and what the surface serves. */
131
+ interface Context {
132
+ readonly api: NiwaApi;
133
+ readonly login: WebLogin;
134
+ readonly streams: Set<() => void>;
135
+ readonly calls: Calls;
136
+ readonly pages: WebPages;
137
+ readonly app: WebApp | undefined;
138
+ readonly builds: ModuleBuilds;
139
+ readonly speaksForOwner: boolean;
140
+ /** The only host name this instance answers to: the one its cookie is kept under. */
141
+ readonly hostname: string;
142
+ }
143
+
144
+ /** A running web surface. */
145
+ export interface WebServer {
146
+ readonly port: number;
147
+ readonly url: string;
148
+ /** The link that logs a browser in: it works once, and the server prints it when it starts. */
149
+ readonly loginUrl: string;
150
+ /** End every open stream, stop listening and close the core client. */
151
+ close(): Promise<void>;
152
+ }
153
+
154
+ /** Run the web surface of one home. The host must already be running. */
155
+ export async function serveWeb(options: WebOptions): Promise<WebServer> {
156
+ const token = options.speaksFor === undefined ? undefined : readOwnerToken(options.home);
157
+ if (options.speaksFor !== undefined && token === undefined) {
158
+ throw new Error(`the host of ${options.home} has not made the owner's token, so the web surface cannot speak for the owner`);
159
+ }
160
+ const api = await connect({ home: options.home, id: WEB_CLIENT_ID, ...(token === undefined ? {} : { token }) });
161
+ const context: Context = {
162
+ api,
163
+ login: new WebLogin(),
164
+ streams: new Set<() => void>(),
165
+ calls: callsOf(options.ownerActions ?? []),
166
+ pages: options.pages,
167
+ app: options.app,
168
+ builds: new ModuleBuilds(),
169
+ speaksForOwner: options.speaksFor === "owner",
170
+ hostname: instanceHostname(),
171
+ };
172
+ const { login, streams } = context;
173
+ const handle = async (request: Request, listener: Bun.Server<undefined>): Promise<Response> => {
174
+ try {
175
+ const response = await route(context, request);
176
+ if (response.headers.get("content-type") === SSE_TYPE) listener.timeout(request, 0);
177
+ return response;
178
+ } catch (error) {
179
+ // A refusal by the grant is a refusal wherever it surfaces; anything else is the surface's own failure.
180
+ return isDenied(error) ? text(403, errorText(error)) : text(500, `the web surface failed: ${errorText(error)}`);
181
+ }
182
+ };
183
+ let server: Bun.Server<undefined>;
184
+ try {
185
+ server = Bun.serve({ hostname: "127.0.0.1", port: options.port ?? 0, fetch: handle });
186
+ } catch (error) {
187
+ await api.close();
188
+ throw error;
189
+ }
190
+ const port = server.port ?? 0;
191
+ // A browser may reach the name of this instance by `::1` first: hold that address of the port too, where there is one,
192
+ // so no other process is the one that answers a browser that has this instance's cookie.
193
+ let other: Bun.Server<undefined> | undefined;
194
+ try {
195
+ other = Bun.serve({ hostname: "::1", port, fetch: handle });
196
+ } catch {
197
+ // No IPv6 loopback here, or the port is taken on it: the browser falls back to the address that is served.
198
+ }
199
+ let closing: Promise<void> | undefined;
200
+ return {
201
+ port,
202
+ url: `http://${context.hostname}:${port}`,
203
+ loginUrl: `http://${context.hostname}:${port}${LOGIN_PATH}?secret=${login.secret}`,
204
+ close(): Promise<void> {
205
+ closing ??= (async () => {
206
+ for (const end of [...streams]) end();
207
+ try {
208
+ await Promise.all([server.stop(true), other?.stop(true)]);
209
+ } finally {
210
+ await api.close();
211
+ }
212
+ })();
213
+ return closing;
214
+ },
215
+ };
216
+ }
217
+
218
+ /**
219
+ * The host name of one instance. A cookie is kept per host name and is not told apart by port, so instances that shared a name
220
+ * would replace one another's session and would hand it to any other service on that name. Each instance gets a name of its
221
+ * own under `.localhost`, which a browser resolves to the loopback, and answers to no other: the cookie it gives has no
222
+ * `Domain`, so it belongs to this name alone. A request that names another host is refused, which is also what keeps a
223
+ * rebound name away from the surface.
224
+ */
225
+ function instanceHostname(): string {
226
+ return `niwa-${randomBytes(8).toString("hex")}.localhost`;
227
+ }
228
+
229
+ /** The method each exact path takes. */
230
+ const METHODS: Readonly<Record<string, string>> = {
231
+ [LOGIN_PATH]: "GET",
232
+ "/": "GET",
233
+ "/events": "GET",
234
+ "/api/info": "GET",
235
+ "/api/viewer": "GET",
236
+ "/api/catalogue": "GET",
237
+ "/api/source": "GET",
238
+ "/api/history": "GET",
239
+ "/api/events": "GET",
240
+ "/api/call": "POST",
241
+ "/feed": "GET",
242
+ "/resolve": "POST",
243
+ "/answer": "POST",
244
+ };
245
+
246
+ /** The route of one request. */
247
+ async function route(context: Context, request: Request): Promise<Response> {
248
+ const { api, login, streams, calls, pages, app, speaksForOwner } = context;
249
+ const url = new URL(request.url);
250
+ const path = url.pathname;
251
+ if (url.hostname !== context.hostname) return text(403, "this host name is not served");
252
+ if (path !== LOGIN_PATH && !login.allows(request.headers.get("cookie"))) {
253
+ return text(401, "log in with the link the server printed when it started");
254
+ }
255
+ const origin = request.headers.get("origin");
256
+ if (origin !== null && origin !== url.origin) return text(403, "a request from another origin is refused");
257
+
258
+ const tracePrefix = ["/trace/", "/trace-data/"].find((prefix) => path.startsWith(prefix));
259
+ const allowed = tracePrefix === undefined ? METHODS[path] : "GET";
260
+ if (allowed === undefined) {
261
+ if (app === undefined || path.startsWith("/api/")) return text(404, "there is no such page");
262
+ // An address of the app: its files, the client modules, or a page the app routes itself.
263
+ if (request.method !== "GET") return methodNotAllowed("GET");
264
+ return appResponse(context, app, request);
265
+ }
266
+ if (request.method !== allowed) return methodNotAllowed(allowed);
267
+
268
+ if (tracePrefix !== undefined) return trace(api, pages, path.slice(tracePrefix.length), tracePrefix === "/trace/");
269
+ switch (path) {
270
+ case LOGIN_PATH: {
271
+ const cookie = login.exchange(url.searchParams.get("secret"));
272
+ if (cookie === undefined) return text(401, "this login link is not valid, or it was used already");
273
+ return new Response(null, { status: 302, headers: { location: "/", "set-cookie": cookie, ...SECURITY_HEADERS } });
274
+ }
275
+ case "/":
276
+ return app === undefined ? html(pages.feed()) : appPage(app);
277
+ case "/api/viewer":
278
+ return json(200, await viewerOf(api, WEB_CLIENT_ID));
279
+ case "/api/catalogue":
280
+ return json(200, app === undefined ? await catalogueOf(api) : { modules: await context.builds.catalogue(api, app) });
281
+ case "/api/info":
282
+ return cockpitInfo(api, url.searchParams.get("action"));
283
+ case "/api/source": {
284
+ if (!speaksForOwner) return text(403, "The source is available to the owner only");
285
+ const at = position(url.searchParams.get("seq") ?? "");
286
+ if (at === undefined || at < 1) return text(400, "invalid position");
287
+ const source = await runSource(api, at);
288
+ return source === undefined ? text(404, "The file for this version is unavailable") : text(200, source);
289
+ }
290
+ case "/api/call":
291
+ return post(request, calls.body, async ({ action, input }) => {
292
+ try {
293
+ const hooked = calls.hooks.get(action);
294
+ if (hooked !== undefined) {
295
+ const ref = hooked.ref;
296
+ const schema = ref.input;
297
+ if (!(schema instanceof z.ZodObject)) return text(502, "invalid cockpit action schema");
298
+ const parsed = schema.strict().safeParse(input);
299
+ if (!parsed.success) return text(400, "invalid cockpit action input");
300
+ const refusal = hooked.refuse?.(parsed.data);
301
+ if (refusal !== undefined) return text(400, refusal);
302
+ const called = await api.call(ref.name, parsed.data);
303
+ // What the host answered has passed the output schema there: it goes on as it is, not through the schema
304
+ // again. A shaped answer is the page's own, and is checked once.
305
+ if (hooked.shape === undefined) return json(200, called);
306
+ const result = ref.output.safeParse(await hooked.shape(called));
307
+ return result.success ? json(200, result.data) : text(502, "invalid cockpit action response");
308
+ }
309
+ return json(200, await api.call(actionName(action), input));
310
+ } catch (error) {
311
+ return refused(error, errorText(error));
312
+ }
313
+ });
314
+ case "/api/history":
315
+ case "/api/events": {
316
+ const lastEventId = path === "/api/events" ? request.headers.get("last-event-id") : null;
317
+ const after = position(lastEventId ?? url.searchParams.get("after") ?? "0");
318
+ if (after === undefined) return text(400, "invalid journal cursor");
319
+ const query = recordQuery(url.searchParams.get("query"));
320
+ if (query === undefined) return text(400, "invalid record query");
321
+ if (path === "/api/history") return json(200, await api.records.read({ ...query, from: after, limit: 128 }));
322
+ return journalEvents(api, { ...query, from: after }, streams);
323
+ }
324
+ case "/events":
325
+ return events(api, streams);
326
+ case "/feed":
327
+ return json(200, await readFeed(api));
328
+ case "/resolve":
329
+ return post(request, ResolveBody, async (body) => {
330
+ try {
331
+ await api.call(actionName(RESOLVE_ACTION), body);
332
+ return json(200, { resolved: true });
333
+ } catch (error) {
334
+ return refused(error, `the invocation was not answered: ${errorText(error)}`);
335
+ }
336
+ });
337
+ default:
338
+ return post(request, AnswerBody, async (body) => {
339
+ try {
340
+ // The page names the request it answers; the action wants the id of the request and the
341
+ // answer itself. The verdict of the action is what the page is told: an answer to a
342
+ // request that was over does not stand, and it says why.
343
+ const raw = await api.call(actionName(ANSWER_ACTION), {
344
+ id: body.request,
345
+ answer: body.answer,
346
+ });
347
+ const verdict = AnswerVerdict.safeParse(raw);
348
+ if (!verdict.success) {
349
+ return text(502, "the answer of the host is not a verdict of the answer");
350
+ }
351
+ return json(200, {
352
+ accepted: verdict.data.accepted,
353
+ ...(verdict.data.reason === undefined ? {} : { reason: verdict.data.reason }),
354
+ });
355
+ } catch (error) {
356
+ return refused(error, `the request was not answered: ${errorText(error)}`);
357
+ }
358
+ });
359
+ }
360
+ }
361
+
362
+ /**
363
+ * The query a page sends with its position: which records it wants, as JSON in `query`. The
364
+ * position is not part of it, it is `after`; undefined for a query that is not one.
365
+ */
366
+ function recordQuery(text: string | null): Omit<RecordQuery, "from"> | undefined {
367
+ if (text === null) return {};
368
+ let value: unknown;
369
+ try {
370
+ value = JSON.parse(text);
371
+ } catch {
372
+ return undefined;
373
+ }
374
+ const parsed = RecordQuerySchema.omit({ from: true }).safeParse(value);
375
+ return parsed.success ? (parsed.data as Omit<RecordQuery, "from">) : undefined;
376
+ }
377
+
378
+ function position(value: string): ReturnType<typeof seq> | undefined {
379
+ const number = Number(value);
380
+ return /^\d+$/.test(value) && Number.isSafeInteger(number) ? seq(number) : undefined;
381
+ }
382
+
383
+ /** The page of a record, or its chain as JSON; 400 for an id that is not one, 404 for no record. */
384
+ async function trace(api: NiwaApi, pages: WebPages, encoded: string, page: boolean): Promise<Response> {
385
+ let id: string;
386
+ try {
387
+ id = decodeURIComponent(encoded);
388
+ recordId(id);
389
+ } catch {
390
+ return text(400, "that is not a record id");
391
+ }
392
+ const chain = await chainOf(api, recordId(id));
393
+ if (chain.root === null) return text(404, "there is no such record");
394
+ return page ? html(pages.trace(id, chain)) : json(200, chain);
395
+ }
396
+
397
+ /**
398
+ * The feed over SSE: the whole list is sent as it stands, and again whenever it changes; the page keeps no state of
399
+ * its own. The list is read before the stream opens, so a journal the connection may not read is refused as any request
400
+ * is. The subscription ends with the stream, whoever ends it.
401
+ */
402
+ async function events(api: NiwaApi, streams: Set<() => void>): Promise<Response> {
403
+ const encoder = new TextEncoder();
404
+ let end = (_close = true): void => undefined;
405
+ let ended = false;
406
+ let send = (_entries: unknown): void => undefined;
407
+ const follower = await followFeed(
408
+ api,
409
+ (entries) => {
410
+ send(entries);
411
+ },
412
+ () => end(),
413
+ );
414
+ const body = new ReadableStream<Uint8Array>({
415
+ start(controller) {
416
+ send = (entries) => {
417
+ if (!ended) controller.enqueue(encoder.encode(`data: ${JSON.stringify(entries)}\n\n`));
418
+ };
419
+ end = (close = true) => {
420
+ if (ended) return;
421
+ ended = true;
422
+ streams.delete(end);
423
+ follower.stop();
424
+ if (close) controller.close();
425
+ };
426
+ streams.add(end);
427
+ send(follower.entries);
428
+ },
429
+ cancel() {
430
+ end(false);
431
+ },
432
+ });
433
+ return new Response(body, { headers: { "content-type": SSE_TYPE, ...SECURITY_HEADERS } });
434
+ }
435
+
436
+ /** What a page may call: whatever the grant of the connection lets through, with the checks the composition added. */
437
+ function callsOf(hooks: readonly OwnerAction[]): Calls {
438
+ return {
439
+ hooks: new Map(hooks.map((entry) => [String(entry.ref.name), entry] as const)),
440
+ body: z.object({
441
+ action: z.string().min(1).refine(isActionName, "that is not an action name"),
442
+ // Any JSON value: what shape an action takes is its schema's matter, and the host holds it to that.
443
+ input: z.unknown(),
444
+ }),
445
+ };
446
+ }
447
+
448
+ function isActionName(name: string): boolean {
449
+ try {
450
+ actionName(name);
451
+ return true;
452
+ } catch {
453
+ return false;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * What the page needs to know of the host: the actions the viewer may call, the position of the journal's end (where a feed
459
+ * that wants the latest records starts), and the facts of the host the pages read. The host may load a subset of the
460
+ * plugins this page supports.
461
+ */
462
+ async function cockpitInfo(api: NiwaApi, action: string | null): Promise<Response> {
463
+ const description = await api.describe();
464
+ const { actions } = await viewerOf(api, WEB_CLIENT_ID);
465
+ if (action !== null) {
466
+ if (!actions.includes(action)) return text(403, "this action is not available");
467
+ const definition = description.actions.find(item => String(item.name) === action);
468
+ if (!definition) return text(404, "unknown action");
469
+ return json(200, { actions: [action], action: { name: action, input: definition.input, description: definition.description, destructive: definition.destructive || definition.effect === "irreversible" } });
470
+ }
471
+ const recordFields = Object.fromEntries(
472
+ description.types.map(({ name, schema }) => [name, schemaFields(schema.properties)]),
473
+ );
474
+ const sessionStart = description.actions.find(({ name }) => name === "session.start")?.input;
475
+ return json(200, { actions, seq: await journalEnd(api), recordFields, harnesses: agentHarnesses(description), sessionStart });
476
+ }
477
+
478
+ /** The position of the last record the connection may read: 0 when it may read none. */
479
+ async function journalEnd(api: NiwaApi): Promise<number> {
480
+ try {
481
+ const read = await api.call(RECORDS_READ_ACTION, { tail: 1 });
482
+ const next = (read as { next?: unknown }).next;
483
+ return typeof next === "number" ? next : 0;
484
+ } catch (error) {
485
+ if (isDenied(error)) return 0;
486
+ throw error;
487
+ }
488
+ }
489
+
490
+ const AGENT_ACTION_PREFIX = "session.start.";
491
+
492
+ /** The harnesses the host serves an agent action for: the ids behind `session.start.<harness>`. */
493
+ function agentHarnesses(description: Description): string[] {
494
+ return description.actions
495
+ .map(({ name }) => String(name))
496
+ .filter((name) => name.startsWith(AGENT_ACTION_PREFIX))
497
+ .map((name) => name.slice(AGENT_ACTION_PREFIX.length))
498
+ .sort();
499
+ }
500
+
501
+ function schemaFields(properties: unknown): string[] {
502
+ return properties !== null && typeof properties === "object" && !Array.isArray(properties)
503
+ ? Object.keys(properties)
504
+ : [];
505
+ }
506
+
507
+ const SSE_TYPE = "text/event-stream; charset=utf-8";
508
+
509
+ /**
510
+ * Each SSE id is a committed journal position. Reconnecting resumes after it. The stream opens once the host has accepted
511
+ * the subscription, with or without a record to send: a connection the grant does not let read the journal is refused here,
512
+ * before the response is made, and is not told of a stream that is over.
513
+ */
514
+ async function journalEvents(api: NiwaApi, query: RecordQuery, streams: Set<() => void>): Promise<Response> {
515
+ const feed = api.records.since(query);
516
+ const iterator = feed[Symbol.asyncIterator]();
517
+ try {
518
+ await feed.ready;
519
+ } catch (error) {
520
+ void iterator.return?.().catch(() => undefined);
521
+ throw error;
522
+ }
523
+ const encoder = new TextEncoder();
524
+ let end = (_close = true): void => undefined;
525
+ let closed = false;
526
+ const body = new ReadableStream<Uint8Array>({
527
+ start(controller) {
528
+ end = (close = true) => {
529
+ if (closed) return;
530
+ closed = true;
531
+ streams.delete(end);
532
+ void iterator.return?.().catch(() => undefined);
533
+ if (close) controller.close();
534
+ };
535
+ streams.add(end);
536
+ controller.enqueue(encoder.encode(": connected\n\n"));
537
+ },
538
+ async pull(controller) {
539
+ try {
540
+ const next = await iterator.next();
541
+ if (closed) return;
542
+ if (next.done) return end();
543
+ const r = next.value;
544
+ controller.enqueue(encoder.encode(`id: ${r.seq}\ndata: ${JSON.stringify(r)}\n\n`));
545
+ } catch { end(); }
546
+ },
547
+ cancel() {
548
+ end(false);
549
+ },
550
+ });
551
+ return new Response(body, { headers: { "content-type": SSE_TYPE, ...SECURITY_HEADERS } });
552
+ }
553
+
554
+ const ResolveBody = z.object({
555
+ invocation: z.string().min(1),
556
+ choice: z.enum(["retry", "skip", "cancel"]),
557
+ key: z.string().optional(),
558
+ });
559
+
560
+ const AnswerBody = z.object({
561
+ request: z.string().min(1),
562
+ answer: z.unknown().refine((value) => value !== undefined, "an answer is needed"),
563
+ });
564
+
565
+ /**
566
+ * What the answer action answers with: whether the answer stands, and why it does not.
567
+ *
568
+ * The action is called by name, so its answer comes back untyped: it is checked here, and an
569
+ * answer that does not have this shape is refused rather than passed on.
570
+ */
571
+ const AnswerVerdict = z.object({
572
+ accepted: z.boolean(),
573
+ reason: z.enum(["cancelled", "expired"]).optional(),
574
+ });
575
+
576
+ /** The largest body a POST may have. */
577
+ const MAX_BODY_BYTES = 64 * 1024;
578
+
579
+ /** A POST: JSON, small, and shaped as `schema` says. The handler gets the parsed body. */
580
+ async function post<T>(
581
+ request: Request,
582
+ schema: z.ZodType<T>,
583
+ handle: (body: T) => Promise<Response>,
584
+ ): Promise<Response> {
585
+ if (request.headers.get("content-type")?.split(";")[0]?.trim() !== "application/json") {
586
+ return text(415, "the body must be application/json");
587
+ }
588
+ const raw = await readBody(request);
589
+ if (raw === undefined) return text(413, "the body is too large");
590
+ let value: unknown;
591
+ try {
592
+ value = JSON.parse(raw);
593
+ } catch {
594
+ return text(400, "the body is not JSON");
595
+ }
596
+ const parsed = schema.safeParse(value);
597
+ if (!parsed.success) {
598
+ return text(400, parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; "));
599
+ }
600
+ return handle(parsed.data);
601
+ }
602
+
603
+ async function readBody(request: Request): Promise<string | undefined> {
604
+ if (Number(request.headers.get("content-length")) > MAX_BODY_BYTES) return undefined;
605
+ if (request.body === null) return "";
606
+ const reader = request.body.getReader();
607
+ const decoder = new TextDecoder();
608
+ let bytes = 0;
609
+ let text = "";
610
+ try {
611
+ for (;;) {
612
+ const { done, value } = await reader.read();
613
+ if (done) return text + decoder.decode();
614
+ bytes += value.byteLength;
615
+ if (bytes > MAX_BODY_BYTES) {
616
+ void reader.cancel().catch(() => undefined);
617
+ return undefined;
618
+ }
619
+ text += decoder.decode(value, { stream: true });
620
+ }
621
+ } finally {
622
+ reader.releaseLock();
623
+ }
624
+ }
625
+
626
+ const BASE_HEADERS = {
627
+ "cache-control": "no-store",
628
+ "x-content-type-options": "nosniff",
629
+ "x-frame-options": "DENY",
630
+ "referrer-policy": "no-referrer",
631
+ } as const;
632
+
633
+ /**
634
+ * The policy of the app and of everything else the surface answers: scripts only from this origin (the app's own and the
635
+ * client modules, as modules), inline styles because components set style attributes, requests only to this origin.
636
+ */
637
+ function appPolicy(inlineScript?: string): string {
638
+ const scripts = inlineScript === undefined ? "'self'" : `'self' ${inlineScript}`;
639
+ return `default-src 'none'; script-src ${scripts}; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`;
640
+ }
641
+
642
+ /** Headers for every response: no storage, no sniffing, no framing, only this origin's requests. */
643
+ const SECURITY_HEADERS = { ...BASE_HEADERS, "content-security-policy": appPolicy() } as const;
644
+
645
+ /** The pages a composition brings carry their own inline script: they are the one thing that may. */
646
+ const PAGE_HEADERS = {
647
+ ...BASE_HEADERS,
648
+ "content-security-policy":
649
+ "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'",
650
+ } as const;
651
+
652
+ function html(body: string): Response {
653
+ return new Response(body, {
654
+ headers: { "content-type": "text/html; charset=utf-8", ...PAGE_HEADERS },
655
+ });
656
+ }
657
+
658
+ function methodNotAllowed(allowed: string): Response {
659
+ return new Response("the method is not allowed here", {
660
+ status: 405,
661
+ headers: { allow: allowed, "content-type": "text/plain; charset=utf-8", ...SECURITY_HEADERS },
662
+ });
663
+ }
664
+
665
+ /** The page of the app, with the import map the client modules share and the policy that lets that one script run. */
666
+ async function appPage(app: WebApp): Promise<Response> {
667
+ const page = await pageOf(app);
668
+ return new Response(page.html, {
669
+ headers: { "content-type": "text/html; charset=utf-8", ...BASE_HEADERS, "content-security-policy": appPolicy(page.hash) },
670
+ });
671
+ }
672
+
673
+ /** A file that never changes under its name: the name carries the hash of what it holds. */
674
+ const IMMUTABLE = "public, max-age=31536000, immutable";
675
+
676
+ /** `/modules/<id>/<hash>/index.js` and `/modules/<id>/<hash>/style-<n>-<hash>.css`. */
677
+ const MODULE_PATH = /^\/modules\/([^/]+)\/([0-9a-f]{64})\/(index\.js|style-(\d+)-([0-9a-f]{12})\.css)$/;
678
+
679
+ /** What the app serves at an address that is none of the API's: its files, the client modules, or the app's own page. */
680
+ async function appResponse(context: Context, app: WebApp, request: Request): Promise<Response> {
681
+ const { api } = context;
682
+ const path = new URL(request.url).pathname;
683
+ if (path.startsWith(ASSETS_PREFIX)) {
684
+ const file = await assetFile(app, path);
685
+ if (file === undefined) return text(404, "there is no such file");
686
+ return new Response(Bun.file(file), {
687
+ headers: { "content-type": typeOf(file), ...SECURITY_HEADERS, "cache-control": IMMUTABLE },
688
+ });
689
+ }
690
+ if (path.startsWith(MODULES_PREFIX)) {
691
+ const found = MODULE_PATH.exec(path);
692
+ if (found === null) return text(404, "there is no such module");
693
+ const [, id = "", hash = "", file = "", index, sheet] = found;
694
+ const answer = await context.builds.file(api, app, id, hash, file === "index.js" ? {} : { sheet: { index: Number(index), hash: sheet ?? "" } });
695
+ if (answer === undefined) return text(404, "the host lists no such module file");
696
+ if ("problem" in answer) return text(500, `the module could not be built: ${answer.problem}`);
697
+ const headers = { ...SECURITY_HEADERS, "cache-control": IMMUTABLE };
698
+ return "code" in answer
699
+ ? new Response(answer.code, { headers: { "content-type": typeOf("module.js"), ...headers } })
700
+ : new Response(answer.css, { headers: { "content-type": typeOf("style.css"), ...headers } });
701
+ }
702
+ // A browser that opens an address asks for a page, whatever the address ends with: `/reports/v1.2` is a page of the app. Any
703
+ // other request for an address with an extension names a file that is not there.
704
+ if (/\.[A-Za-z0-9]+$/.test(path) && !wantsPage(request)) return text(404, "there is no such file");
705
+ return appPage(app);
706
+ }
707
+
708
+ /** Whether the request is a browser opening an address, which accepts a page; a script or an image does not. */
709
+ function wantsPage(request: Request): boolean {
710
+ return (request.headers.get("accept") ?? "").includes("text/html");
711
+ }
712
+
713
+ function json(status: number, body: unknown): Response {
714
+ return new Response(JSON.stringify(body), {
715
+ status,
716
+ headers: { "content-type": "application/json; charset=utf-8", ...SECURITY_HEADERS },
717
+ });
718
+ }
719
+
720
+ function text(status: number, body: string): Response {
721
+ return new Response(body, {
722
+ status,
723
+ headers: { "content-type": "text/plain; charset=utf-8", ...SECURITY_HEADERS },
724
+ });
725
+ }
726
+
727
+ /**
728
+ * The answer to a call the host did not carry out: 403 when the grant of this connection refused it, so a page can tell a
729
+ * missing permission from a state that does not allow the call, which is 409.
730
+ */
731
+ function refused(error: unknown, message: string): Response {
732
+ return text(isDenied(error) ? 403 : 409, message);
733
+ }
734
+
735
+ function errorText(error: unknown): string {
736
+ return error instanceof Error ? error.message : String(error);
737
+ }