@mostra/runtime 0.13.0 → 0.14.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.
@@ -29,10 +29,17 @@ import {
29
29
  import { faultsFrom } from "../faults.ts";
30
30
  import {
31
31
  BASE_HEADERS,
32
+ defaultPages,
32
33
  documentHeaders,
33
34
  locateShell,
35
+ MADE_WITH_HREF,
36
+ refusalDocument,
34
37
  resetOnClose,
38
+ type ServerPages,
39
+ serverPages,
35
40
  shellAssetResponse,
41
+ THEME_BASE,
42
+ themePageCsp,
36
43
  } from "../gateway/index.ts";
37
44
  import { appendEvent } from "../interaction/index.ts";
38
45
  import type { Ledger, LedgerOwner } from "../ledger/index.ts";
@@ -50,6 +57,7 @@ import { createRemoteMcp, serverDocs } from "./mcp.ts";
50
57
  import { createMeter, heldLevels, type Meter } from "./metering.ts";
51
58
  import { createClients } from "./oauth-clients.ts";
52
59
  import { loadOperator, type Operator } from "./operator.ts";
60
+ import { APPEARANCE_PATH, createApiPages } from "./pages.ts";
53
61
  import { type BuiltInProvider, builtInProviders } from "./providers.ts";
54
62
  import { createRouting, type Destination, type Routing } from "./routing.ts";
55
63
 
@@ -93,8 +101,43 @@ function json(response: ServerResponse, status: number, body: unknown): void {
93
101
  response.end(text);
94
102
  }
95
103
 
96
- function refusal(response: ServerResponse, status: number, diagnostic: Diagnostic): void {
97
- json(response, status, diagnostic);
104
+ /** Whether a request is a person's navigation, answered with a page rather than JSON. */
105
+ function wantsPage(request: IncomingMessage | undefined): boolean {
106
+ if (!request) return false;
107
+ const dest = request.headers["sec-fetch-dest"];
108
+ if (typeof dest === "string") return dest === "document";
109
+ return (request.headers.accept ?? "").includes("text/html");
110
+ }
111
+
112
+ /**
113
+ * A refusal: a page in the server's theme for a person's navigation (an unknown host, a request
114
+ * the server couldn't answer), the diagnostic as JSON for anything else.
115
+ */
116
+ function refusal(
117
+ response: ServerResponse,
118
+ status: number,
119
+ diagnostic: Diagnostic,
120
+ pages: ServerPages = defaultPages(),
121
+ ): void {
122
+ const request = response.req as IncomingMessage | undefined;
123
+ if (!wantsPage(request)) {
124
+ json(response, status, diagnostic);
125
+ return;
126
+ }
127
+ const text = refusalDocument(pages.pages, {
128
+ title: diagnostic.message,
129
+ detail: diagnostic.hint,
130
+ code: diagnostic.code,
131
+ });
132
+ response.writeHead(status, {
133
+ ...BASE_HEADERS,
134
+ "content-type": "text/html; charset=utf-8",
135
+ "content-length": String(Buffer.byteLength(text)),
136
+ "cache-control": "no-store",
137
+ "content-security-policy": themePageCsp(pages.pages),
138
+ "x-frame-options": "DENY",
139
+ });
140
+ response.end(request?.method === "HEAD" ? undefined : text);
98
141
  }
99
142
 
100
143
  /** Splits `host:port`, with `[::1]:port` for IPv6. */
@@ -116,6 +159,8 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
116
159
  // The authorization server and the operator module are made once the directory is open; homes
117
160
  // open only after both.
118
161
  let auth: Authorization | undefined;
162
+ // The hosted hosts' own pages, once the configuration's are made (below); the defaults until then.
163
+ let pagesOfHosts: ServerPages = defaultPages();
119
164
  let operator: Operator | undefined;
120
165
  let meter: Meter | undefined;
121
166
  let routing: Routing;
@@ -177,6 +222,10 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
177
222
  },
178
223
  signInOffered: () =>
179
224
  (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false),
225
+ // On by default for every page, self-hosted included; an operator's `policy.link` turns it
226
+ // off for the pages it promises unbranded (D171 item 5).
227
+ madeWith: { href: MADE_WITH_HREF },
228
+ pages: () => pagesOfHosts,
180
229
  });
181
230
  const assembler: HomeAssembler<HostedHome> = {
182
231
  assemble: (home) =>
@@ -346,7 +395,26 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
346
395
  await data.close();
347
396
  throw error;
348
397
  }
398
+ // The server's own pages (D171): the API origin's, with the appearance switch its own cookie
399
+ // keeps, and the hosted hosts', which keep no cookie (D165 item 8).
400
+ let apiPages: ServerPages;
401
+ let hostedPages: ServerPages;
402
+ try {
403
+ apiPages = serverPages(config.appearance, { appearanceAction: APPEARANCE_PATH });
404
+ hostedPages = serverPages(config.appearance);
405
+ } catch (error) {
406
+ operator?.stop();
407
+ await data.close();
408
+ throw new RpcError(
409
+ createDiagnostic("MOSTRA_REMOTE_CONFIG_INVALID", {
410
+ message: `The configuration key \`appearance.logo\` can't be used: ${(error as Error).message}`,
411
+ }),
412
+ );
413
+ }
414
+ pagesOfHosts = hostedPages;
349
415
  const authorize = createAuthorize({
416
+ server: apiPages,
417
+ pages: createApiPages(apiPages, apiPages.name),
350
418
  apiOrigin: config.apiOrigin,
351
419
  directory: data.directory,
352
420
  auth,
@@ -368,6 +436,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
368
436
  ensureHome: (accountId) => (auth as Authorization).ensureHome(accountId),
369
437
  });
370
438
  api = createApi({
439
+ server: apiPages,
371
440
  config,
372
441
  auth,
373
442
  mcp,
@@ -397,6 +466,16 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
397
466
  // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing. Only
398
467
  // the API origin's own sign-in pages read the cookies it set itself.
399
468
  if (host !== apiHost) delete request.headers.cookie;
469
+ // The files a server's own pages load (D171): the same public files on every host, so even
470
+ // the page for an unknown host is drawn in the server's theme.
471
+ if ((request.method === "GET" || request.method === "HEAD") && path.startsWith(THEME_BASE)) {
472
+ const file = pagesOfHosts.asset(path.slice(THEME_BASE.length));
473
+ if (file) {
474
+ response.writeHead(200, { ...BASE_HEADERS, ...file.headers });
475
+ response.end(request.method === "HEAD" ? undefined : file.body);
476
+ return;
477
+ }
478
+ }
400
479
  if (host === apiHost && request.method === "GET" && path === "/health") {
401
480
  json(response, 200, { status: "ok", homes: data.open().length });
402
481
  return;
@@ -437,6 +516,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
437
516
  createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", {
438
517
  message: "This server serves no pages at this host.",
439
518
  }),
519
+ pagesOfHosts,
440
520
  );
441
521
  // An empty or malformed Host gets nothing, and is never asked of an operator.
442
522
  if (!/^[a-z0-9.-]{1,253}(:\d{1,5})?$/.test(host)) {
@@ -0,0 +1,242 @@
1
+ /**
2
+ * The API origin's own pages (INTERFACES §18.5, D171): sign-in with its providers, the development
3
+ * provider's name page, linking a machine (the device grant), consent for a chat app, a page's
4
+ * "Answer as yourself", and every "Sign-in can't continue". They are `@mostra/themes`' pages in the
5
+ * operator's theme and name, with no script; every word they say is in `API_PAGE_WORDS`, and every
6
+ * name a provider, a client or a person supplies lands as text.
7
+ */
8
+ import type { Appearance } from "@mostra/themes";
9
+ import {
10
+ actions,
11
+ alert,
12
+ button,
13
+ field,
14
+ fine,
15
+ html,
16
+ linkButton,
17
+ type SafeHtml,
18
+ } from "@mostra/themes";
19
+ import type { ServerPages } from "../gateway/index.ts";
20
+
21
+ /** Where a person's appearance switch posts on the API origin (D171). */
22
+ export const APPEARANCE_PATH = "/_mostra/appearance";
23
+
24
+ /** Every word the API origin's pages say (D149: Mirza reviews them). */
25
+ export const API_PAGE_WORDS = {
26
+ signInTitle: (name: string | null): string => (name ? `Sign in to ${name}` : "Sign in"),
27
+ signInLede: "Choose how to sign in.",
28
+ continueWith: (label: string): string => `Continue with ${label}`,
29
+ noProviders: "This server has no sign-in set up yet, so nobody can sign in.",
30
+ neverPassword: "You sign in with your provider. This server never sees your password.",
31
+ devTitle: "Development sign-in",
32
+ devNote:
33
+ "This server signs people in with a development provider, which trusts the name you type. Use it only on a server you run for yourself or for tests.",
34
+ yourName: "Your name",
35
+ continue: "Continue",
36
+ cantContinue: "Sign-in can't continue",
37
+ deviceTitle: "Link this machine",
38
+ deviceSignedInAs: (name: string): SafeHtml => html`Signed in as <strong>${name}</strong>.`,
39
+ deviceWarning:
40
+ "Approving links a machine to your account. That machine's Mostra can then host pages under your account and receives their answers. Continue only if you started this sign-in yourself, on that machine.",
41
+ deviceCode: "The code that machine shows",
42
+ approveMachine: "Approve this machine",
43
+ refuse: "Refuse",
44
+ deviceLinked: "The machine is linked to your account.",
45
+ deviceRefused: "The sign-in was refused.",
46
+ deviceClose: "You can close this page.",
47
+ answerTitle: "Answer as yourself",
48
+ answerAs: (who: string, owner: string): string => `Continue as ${who} to answer ${owner}'s page?`,
49
+ answerDetail: "They will see your name with your answers.",
50
+ thisPerson: "this person",
51
+ allowTitle: (client: string): string => `Allow ${client}?`,
52
+ asksToUse: (client: SafeHtml, who: string): SafeHtml =>
53
+ html`${client} asks to use Mostra as <strong>${who}</strong>.`,
54
+ unverifiedName: "a name the app gives itself, not checked",
55
+ grants: ["Read, create and change your hosted pages", "Read their answers"],
56
+ sendsBackTo: (host: string): SafeHtml => html`It will send you back to <strong>${host}</strong>.`,
57
+ loopback: "That is a program on your own computer: continue only if you started this there.",
58
+ allow: "Allow",
59
+ cancel: "Cancel",
60
+ yourAccount: "your account",
61
+ } as const;
62
+
63
+ /** The marks of providers a person recognises, by provider ID. Others show their label alone. */
64
+ const PROVIDER_ICONS: Readonly<Record<string, SafeHtml>> = {
65
+ github: html`<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>`,
66
+ google: html`<svg viewBox="0 0 18 18" aria-hidden="true"><path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92a8.78 8.78 0 0 0 2.68-6.62z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.33-1.58-5.04-3.7H.96v2.33A9 9 0 0 0 9 18z"/><path fill="#FBBC05" d="M3.96 10.72A5.4 5.4 0 0 1 3.68 9c0-.6.1-1.18.28-1.72V4.95H.96A9 9 0 0 0 0 9c0 1.45.35 2.83.96 4.05l3-2.33z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A8.97 8.97 0 0 0 9 0 9 9 0 0 0 .96 4.95l3 2.33C4.67 5.16 6.66 3.58 9 3.58z"/></svg>`,
67
+ };
68
+
69
+ /** Where a page is and what the person chose, for its appearance switch. */
70
+ export interface PageRequest {
71
+ /** The person's own choice; without one, the operator's default. */
72
+ readonly appearance?: Appearance;
73
+ /** This page's own path and query: where the appearance switch returns. */
74
+ readonly path: string;
75
+ }
76
+
77
+ /** The API origin's pages, as HTML. */
78
+ export interface ApiPages {
79
+ readonly name: string | null;
80
+ signIn(
81
+ request: PageRequest,
82
+ providers: readonly { readonly id: string; readonly label: string }[],
83
+ next: string,
84
+ message?: string,
85
+ ): string;
86
+ developmentName(request: PageRequest, providerId: string, state: string): string;
87
+ problem(request: PageRequest, message: string): string;
88
+ answerAs(request: PageRequest, form: ConsentForm, who: string, owner: string | undefined): string;
89
+ allow(
90
+ request: PageRequest,
91
+ form: ConsentForm,
92
+ client: { readonly name: string; readonly unverified: boolean },
93
+ who: string,
94
+ redirectHost: string,
95
+ loopback: boolean,
96
+ ): string;
97
+ deviceForm(
98
+ request: PageRequest,
99
+ options: {
100
+ readonly code: string;
101
+ readonly message?: string | undefined;
102
+ readonly development?: { readonly id: string; readonly label: string } | undefined;
103
+ readonly signedIn?: { readonly name: string; readonly csrf: string } | undefined;
104
+ },
105
+ ): string;
106
+ deviceDone(request: PageRequest, message: string): string;
107
+ }
108
+
109
+ /** The consent form's target and its CSRF token. */
110
+ export interface ConsentForm {
111
+ readonly action: string;
112
+ readonly csrf: string;
113
+ }
114
+
115
+ /** Makes the API origin's pages from the server's own pages (its theme and name). */
116
+ export function createApiPages(server: ServerPages, name: string | null): ApiPages {
117
+ const W = API_PAGE_WORDS;
118
+ const { pages } = server;
119
+ const consentButtons = (approve: string) =>
120
+ actions(
121
+ button(approve, { name: "decision", value: "approve", primary: true }),
122
+ button(W.cancel, { name: "decision", value: "deny" }),
123
+ );
124
+ return {
125
+ name,
126
+ signIn(request, providers, next, message) {
127
+ const list = providers.map((provider, index) =>
128
+ linkButton(
129
+ `/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}`,
130
+ W.continueWith(provider.label),
131
+ {
132
+ primary: index === 0,
133
+ ...(PROVIDER_ICONS[provider.id]
134
+ ? { icon: PROVIDER_ICONS[provider.id] as SafeHtml }
135
+ : {}),
136
+ },
137
+ ),
138
+ );
139
+ return pages.render({
140
+ kind: "task",
141
+ title: W.signInTitle(name),
142
+ lede: W.signInLede,
143
+ body: html`${message ? alert(message) : ""}${
144
+ list.length > 0
145
+ ? html`<div class="m-list">${list}</div>${fine(W.neverPassword)}`
146
+ : alert(W.noProviders, "note")
147
+ }`,
148
+ ...request,
149
+ });
150
+ },
151
+ developmentName(request, providerId, state) {
152
+ return pages.render({
153
+ kind: "task",
154
+ title: W.devTitle,
155
+ body: html`${alert(W.devNote, "note")}<form method="post" action="/signin/${providerId}/name"><input type="hidden" name="state" value="${state}">${field(
156
+ { label: W.yourName, name: "name", required: true, maxLength: 64, autocomplete: "name" },
157
+ )}${actions(button(W.continue, { primary: true }))}</form>`,
158
+ ...request,
159
+ });
160
+ },
161
+ problem(request, message) {
162
+ return pages.render({
163
+ kind: "notice",
164
+ tone: "problem",
165
+ title: W.cantContinue,
166
+ body: html`<p>${message}</p>`,
167
+ ...request,
168
+ });
169
+ },
170
+ answerAs(request, form, who, owner) {
171
+ return pages.render({
172
+ kind: "task",
173
+ title: W.answerTitle,
174
+ lede: W.answerAs(who, owner ?? W.thisPerson),
175
+ body: html`<p>${W.answerDetail}</p><form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.continue)}</form>`,
176
+ ...request,
177
+ });
178
+ },
179
+ allow(request, form, client, who, redirectHost, loopback) {
180
+ const clientName = client.unverified
181
+ ? html`<strong>${client.name}</strong> <span class="m-hint">(${W.unverifiedName})</span>`
182
+ : html`<strong>${client.name}</strong>`;
183
+ return pages.render({
184
+ kind: "task",
185
+ title: W.allowTitle(client.name),
186
+ lede: W.asksToUse(clientName, who),
187
+ body: html`<ul class="m-grants">${W.grants.map((grant) => html`<li>${grant}</li>`)}</ul><p>${W.sendsBackTo(redirectHost)}</p>${loopback ? alert(W.loopback) : ""}<form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.allow)}</form>`,
188
+ ...request,
189
+ });
190
+ },
191
+ deviceForm(request, options) {
192
+ const signedIn = options.signedIn;
193
+ const development = options.development;
194
+ const form = signedIn
195
+ ? html`<form method="post" action="/device"><input type="hidden" name="csrf" value="${signedIn.csrf}">${field(
196
+ {
197
+ label: W.deviceCode,
198
+ name: "user_code",
199
+ value: options.code,
200
+ required: true,
201
+ code: true,
202
+ },
203
+ )}${actions(
204
+ button(W.approveMachine, { name: "session_decision", value: "approve", primary: true }),
205
+ button(W.refuse, { name: "session_decision", value: "deny" }),
206
+ )}</form>`
207
+ : development
208
+ ? html`<form method="post" action="/device">${field({
209
+ label: W.deviceCode,
210
+ name: "user_code",
211
+ value: options.code,
212
+ required: true,
213
+ code: true,
214
+ })}${alert(W.devNote, "note")}${field({
215
+ label: W.yourName,
216
+ name: "name",
217
+ required: true,
218
+ maxLength: 64,
219
+ autocomplete: "name",
220
+ })}<input type="hidden" name="provider" value="${development.id}">${actions(
221
+ button(W.approveMachine, { name: "decision", value: "approve", primary: true }),
222
+ button(W.refuse, { name: "decision", value: "deny" }),
223
+ )}</form>`
224
+ : alert(W.noProviders, "note");
225
+ return pages.render({
226
+ kind: "task",
227
+ title: W.deviceTitle,
228
+ ...(signedIn ? { lede: W.deviceSignedInAs(signedIn.name) } : {}),
229
+ body: html`${options.message ? alert(options.message) : ""}${alert(W.deviceWarning, "note")}${form}`,
230
+ ...request,
231
+ });
232
+ },
233
+ deviceDone(request, message) {
234
+ return pages.render({
235
+ kind: "notice",
236
+ title: message,
237
+ body: html`<p>${W.deviceClose}</p>`,
238
+ ...request,
239
+ });
240
+ },
241
+ };
242
+ }