@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.
package/src/server/api.ts CHANGED
@@ -12,17 +12,20 @@ import { join } from "node:path";
12
12
  import type { Duplex } from "node:stream";
13
13
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
14
14
  import type { CredentialResource } from "@mostra/protocol/operator";
15
+ import { appearanceCookie } from "@mostra/themes";
15
16
  import { type WebSocket, WebSocketServer } from "ws";
17
+ import { type ServerPages, themePageCsp } from "../gateway/index.ts";
16
18
  import type { Log } from "../log.ts";
17
19
  import { BINDING_SUBPROTOCOL, MAX_FRAME_BYTES, serveWebSocket } from "../protocol-server/index.ts";
18
20
  import type { Authenticated, Authorization } from "./auth.ts";
19
- import type { Authorize } from "./authorize.ts";
21
+ import { type Authorize, pageRequest } from "./authorize.ts";
20
22
  import type { ClientAddresses, RateLimiter } from "./clients.ts";
21
23
  import type { RemoteServerConfig } from "./config.ts";
22
24
  import type { HostedHome } from "./hosted.ts";
23
25
  import type { RemoteMcp } from "./mcp.ts";
24
26
  import type { Clients } from "./oauth-clients.ts";
25
27
  import type { Operator } from "./operator.ts";
28
+ import { API_PAGE_WORDS, APPEARANCE_PATH, createApiPages } from "./pages.ts";
26
29
 
27
30
  /** How often an open binding's grant is checked again: a revocation closes it within 60 s. */
28
31
  const GRANT_RECHECK_MS = 30_000;
@@ -59,20 +62,6 @@ function send(
59
62
  response.end(text);
60
63
  }
61
64
 
62
- function page(response: ServerResponse, status: number, html: string): void {
63
- response.writeHead(status, {
64
- ...BASE_HEADERS,
65
- "content-type": "text/html; charset=utf-8",
66
- "content-security-policy":
67
- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
68
- "x-frame-options": "DENY",
69
- // The device page posts its own form, whose `Origin` the server checks: under `no-referrer`
70
- // browsers send `Origin: null` for a form's POST, so this page sends origins to itself only.
71
- "referrer-policy": "same-origin",
72
- });
73
- response.end(html);
74
- }
75
-
76
65
  async function readBody(request: IncomingMessage, limit: number): Promise<Buffer | undefined> {
77
66
  const chunks: Buffer[] = [];
78
67
  let size = 0;
@@ -84,13 +73,11 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Buffer
84
73
  return Buffer.concat(chunks);
85
74
  }
86
75
 
87
- function escapeHtml(text: string): string {
88
- return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
89
- }
90
-
91
76
  /** Options for {@link createApi}. */
92
77
  export interface ApiOptions {
93
78
  readonly config: RemoteServerConfig;
79
+ /** The server's own pages on the API origin, in its operator's theme and name (D171). */
80
+ readonly server: ServerPages;
94
81
  readonly auth: Authorization;
95
82
  readonly log: Log;
96
83
  readonly filesDir: string;
@@ -141,63 +128,40 @@ function developmentProvider(
141
128
  return provider ? { id: provider.id, label: provider.label ?? "Development sign-in" } : undefined;
142
129
  }
143
130
 
144
- /** The device page: the code, the warning, and the development provider's sign-in. */
145
- function devicePage(options: {
146
- readonly code: string;
147
- readonly provider: { id: string; label: string } | undefined;
148
- readonly message?: string;
149
- readonly done?: boolean;
150
- }): string {
151
- const body = options.done
152
- ? `<p>${escapeHtml(options.message ?? "Done.")}</p><p>You can close this page.</p>`
153
- : `${options.message ? `<p role="alert">${escapeHtml(options.message)}</p>` : ""}
154
- <p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host
155
- pages under your account and receives their answers. Continue only if you started this sign-in
156
- yourself, on that machine.</p>
157
- ${
158
- options.provider
159
- ? `<form method="post" action="/device">
160
- <label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
161
- <p>${escapeHtml(options.provider.label)}: this server signs people in with a development provider,
162
- which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
163
- <label>Your name <input name="name" required maxlength="64"></label>
164
- <input type="hidden" name="provider" value="${escapeHtml(options.provider.id)}">
165
- <p><button name="decision" value="approve">Approve this machine</button>
166
- <button name="decision" value="deny">Refuse</button></p>
167
- </form>`
168
- : "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"
169
- }`;
170
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
171
- <meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
172
- <style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
173
- input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
174
- <body><h1>Link a machine to Mostra</h1>${body}</body></html>`;
175
- }
176
-
177
- /** The device page for a browser already signed in: approving links a machine (§18.5). */
178
- function deviceApproval(options: {
179
- readonly code: string;
180
- readonly name: string;
181
- readonly csrf: string;
182
- }): string {
183
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
184
- <meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
185
- <style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
186
- input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
187
- <body><h1>Link a machine to Mostra</h1>
188
- <p><strong>Approving links a machine to your account, ${escapeHtml(options.name)}.</strong> That machine's
189
- Mostra can then host pages under your account and receives their answers. Continue only if you started
190
- this sign-in yourself, on that machine.</p>
191
- <form method="post" action="/device"><input type="hidden" name="csrf" value="${escapeHtml(options.csrf)}">
192
- <label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
193
- <p><button name="session_decision" value="approve">Approve this machine</button>
194
- <button name="session_decision" value="deny">Refuse</button></p></form></body></html>`;
195
- }
196
-
197
131
  /** Creates the API origin. */
198
132
  export function createApi(options: ApiOptions): Api {
199
133
  const { config, auth, log } = options;
200
134
  const apiOrigin = config.apiOrigin;
135
+ const pages = createApiPages(options.server, options.server.name);
136
+ /** Sends one of the API origin's pages: themed, no script, its forms posting here only. */
137
+ const page = (response: ServerResponse, status: number, text: string): void => {
138
+ response.writeHead(status, {
139
+ ...BASE_HEADERS,
140
+ "content-type": "text/html; charset=utf-8",
141
+ "content-security-policy": themePageCsp(options.server.pages, "'none'", "'self'"),
142
+ "x-frame-options": "DENY",
143
+ // The device page posts its own form, whose `Origin` the server checks: under `no-referrer`
144
+ // browsers send `Origin: null` for a form's POST, so this page sends origins to itself only.
145
+ "referrer-policy": "same-origin",
146
+ });
147
+ response.end(text);
148
+ };
149
+ const devicePage = (
150
+ response: ServerResponse,
151
+ options: {
152
+ readonly code: string;
153
+ readonly provider: { id: string; label: string } | undefined;
154
+ readonly message?: string;
155
+ readonly done?: boolean;
156
+ },
157
+ ): string =>
158
+ options.done
159
+ ? pages.deviceDone(pageRequest(response), options.message ?? "")
160
+ : pages.deviceForm(pageRequest(response), {
161
+ code: options.code,
162
+ message: options.message,
163
+ development: options.provider,
164
+ });
201
165
  const sockets = new WebSocketServer({
202
166
  noServer: true,
203
167
  maxPayload: MAX_FRAME_BYTES,
@@ -328,11 +292,17 @@ export function createApi(options: ApiOptions): Api {
328
292
  authorization_response_iss_parameter_supported: true,
329
293
  });
330
294
 
331
- const sessionDevicePage = (code: string, signed: { accountId: string; hash: string }): string =>
332
- deviceApproval({
295
+ const sessionDevicePage = (
296
+ response: ServerResponse,
297
+ code: string,
298
+ signed: { accountId: string; hash: string },
299
+ ): string =>
300
+ pages.deviceForm(pageRequest(response), {
333
301
  code,
334
- name: auth.accountName(signed.accountId).name ?? "your account",
335
- csrf: options.authorize.csrf(signed.hash, "device"),
302
+ signedIn: {
303
+ name: auth.accountName(signed.accountId).name ?? API_PAGE_WORDS.yourAccount,
304
+ csrf: options.authorize.csrf(signed.hash, "device"),
305
+ },
336
306
  });
337
307
 
338
308
  const form = async (request: IncomingMessage): Promise<URLSearchParams | undefined> => {
@@ -577,13 +547,31 @@ export function createApi(options: ApiOptions): Api {
577
547
  send(response, 200, {});
578
548
  return;
579
549
  }
550
+ if (method === "POST" && path === APPEARANCE_PATH) {
551
+ // A person's light-or-dark choice (D171): kept in a cookie of this origin, from this
552
+ // origin's own pages only, then back to the page it was made on.
553
+ const body = request.headers.origin === apiOrigin ? await form(request) : undefined;
554
+ const chosen = body?.get("appearance");
555
+ const next = body?.get("next") ?? "/";
556
+ const back =
557
+ next.startsWith("/") && !next.startsWith("//") && !next.startsWith("/\\") ? next : "/";
558
+ response.writeHead(303, {
559
+ ...BASE_HEADERS,
560
+ location: back,
561
+ ...(chosen === "light" || chosen === "dark" || chosen === "system"
562
+ ? { "set-cookie": appearanceCookie(chosen, apiOrigin.startsWith("https:")) }
563
+ : {}),
564
+ });
565
+ response.end();
566
+ return;
567
+ }
580
568
  if (path === "/device") {
581
569
  const provider = developmentProvider(config);
582
570
  const signed = options.authorize.sessionAccount(request);
583
571
  if (method === "GET") {
584
572
  const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
585
573
  if (signed) {
586
- page(response, 200, sessionDevicePage(code, signed));
574
+ page(response, 200, sessionDevicePage(response, code, signed));
587
575
  return;
588
576
  }
589
577
  // Real providers sign the person in first; the development one asks on this page, when it
@@ -595,7 +583,7 @@ export function createApi(options: ApiOptions): Api {
595
583
  );
596
584
  return;
597
585
  }
598
- page(response, 200, devicePage({ code, provider }));
586
+ page(response, 200, devicePage(response, { code, provider }));
599
587
  return;
600
588
  }
601
589
  // The body is read once, for either form.
@@ -610,7 +598,7 @@ export function createApi(options: ApiOptions): Api {
610
598
  page(
611
599
  response,
612
600
  403,
613
- devicePage({
601
+ devicePage(response, {
614
602
  code: "",
615
603
  provider,
616
604
  message: "This form must be sent from this page.",
@@ -623,7 +611,7 @@ export function createApi(options: ApiOptions): Api {
623
611
  page(
624
612
  response,
625
613
  decided.ok ? 200 : 400,
626
- devicePage({
614
+ devicePage(response, {
627
615
  code,
628
616
  provider,
629
617
  ...(decided.ok
@@ -645,7 +633,11 @@ export function createApi(options: ApiOptions): Api {
645
633
  page(
646
634
  response,
647
635
  403,
648
- devicePage({ code: "", provider, message: "This form must be sent from this page." }),
636
+ devicePage(response, {
637
+ code: "",
638
+ provider,
639
+ message: "This form must be sent from this page.",
640
+ }),
649
641
  );
650
642
  return;
651
643
  }
@@ -664,7 +656,7 @@ export function createApi(options: ApiOptions): Api {
664
656
  page(
665
657
  response,
666
658
  400,
667
- devicePage({ code, provider, message: "Enter the code and your name." }),
659
+ devicePage(response, { code, provider, message: "Enter the code and your name." }),
668
660
  );
669
661
  return;
670
662
  }
@@ -673,7 +665,7 @@ export function createApi(options: ApiOptions): Api {
673
665
  // the operator nothing (second Fable review of WP-30, 5).
674
666
  const pending = auth.pendingCode(code);
675
667
  if (!pending.ok) {
676
- page(response, 400, devicePage({ code, provider, message: pending.reason }));
668
+ page(response, 400, devicePage(response, { code, provider, message: pending.reason }));
677
669
  return;
678
670
  }
679
671
  // The typed name is an identity like any provider's: the operator's `accounts.resolve`
@@ -695,20 +687,20 @@ export function createApi(options: ApiOptions): Api {
695
687
  page(
696
688
  response,
697
689
  account.kind === "unavailable" ? 503 : 403,
698
- devicePage({ code, provider, message: reason }),
690
+ devicePage(response, { code, provider, message: reason }),
699
691
  );
700
692
  return;
701
693
  }
702
694
  decided = auth.decideFor({ code, approve: true, accountId: account.accountId });
703
695
  }
704
696
  if (!decided.ok) {
705
- page(response, 400, devicePage({ code, provider, message: decided.reason }));
697
+ page(response, 400, devicePage(response, { code, provider, message: decided.reason }));
706
698
  return;
707
699
  }
708
700
  page(
709
701
  response,
710
702
  200,
711
- devicePage({
703
+ devicePage(response, {
712
704
  code,
713
705
  provider,
714
706
  done: true,
@@ -23,12 +23,15 @@ import {
23
23
  type SignInIdentity,
24
24
  SignInIdentity as SignInIdentitySchema,
25
25
  } from "@mostra/protocol/operator";
26
+ import { readAppearance } from "@mostra/themes";
27
+ import { type ServerPages, themePageCsp } from "../gateway/index.ts";
26
28
  import type { Ledger } from "../ledger/index.ts";
27
29
  import type { Log } from "../log.ts";
28
30
  import { type Authorization, canonicalResource, hashSecret } from "./auth.ts";
29
31
  import { verifierLabel } from "./config.ts";
30
32
  import { type Clients, type OAuthClient, redirectAllowed } from "./oauth-clients.ts";
31
33
  import type { Operator } from "./operator.ts";
34
+ import { API_PAGE_WORDS, type ApiPages, type PageRequest } from "./pages.ts";
32
35
 
33
36
  /** How long an authorization request, a provider sign-in or a step waits. */
34
37
  const PENDING_MS = 15 * 60_000;
@@ -70,9 +73,24 @@ export interface AuthorizeOptions {
70
73
  /** Names a hosted home's owner, for a page's sign-in ("Grace Hopper's page"). */
71
74
  readonly ownerName: (homeId: string) => string | undefined;
72
75
  readonly log: Log;
76
+ /** The server's own pages (its operator's theme and name, D171) and the API origin's on them. */
77
+ readonly server: ServerPages;
78
+ readonly pages: ApiPages;
73
79
  readonly now?: () => number;
74
80
  }
75
81
 
82
+ /**
83
+ * Where a page answers and what its reader chose (their appearance, D171), from the request a
84
+ * response answers.
85
+ */
86
+ export function pageRequest(response: ServerResponse): PageRequest {
87
+ const request = response.req as IncomingMessage | undefined;
88
+ const cookie = request?.headers.cookie;
89
+ // Without a choice of their own, a person gets the operator's default (the pages know it).
90
+ const chosen = cookie?.includes("mostra-appearance=") ? readAppearance(cookie) : undefined;
91
+ return { ...(chosen ? { appearance: chosen } : {}), path: request?.url ?? "/" };
92
+ }
93
+
76
94
  /** A page's sign-in in progress (INTERFACES §18.4), bound to its route and shell session. */
77
95
  export interface ViewerSignin {
78
96
  readonly homeId: string;
@@ -122,21 +140,10 @@ const BASE = {
122
140
  "x-frame-options": "DENY",
123
141
  } as const;
124
142
 
125
- function escapeHtml(text: string): string {
126
- return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
127
- }
128
-
129
- function shell(title: string, body: string): string {
130
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
131
- <meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
132
- <style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
133
- input{font:inherit;padding:.3rem}button,a.button{font:inherit;padding:.4rem .9rem;margin:.2rem .5rem .2rem 0;display:inline-block}
134
- .muted{color:#555}</style></head><body><h1>${escapeHtml(title)}</h1>${body}</body></html>`;
135
- }
136
-
137
143
  /** Builds the pages. */
138
144
  export function createAuthorize(options: AuthorizeOptions): Authorize {
139
- const { apiOrigin, directory, auth, clients, operator, log } = options;
145
+ const { apiOrigin, directory, auth, clients, operator, log, pages } = options;
146
+ const at = (response: ServerResponse): PageRequest => pageRequest(response);
140
147
  const now = options.now ?? (() => Date.now());
141
148
  const secure = apiOrigin.startsWith("https:");
142
149
  const sessionCookie = secure ? "__Host-mostra-signin" : "mostra-signin";
@@ -168,8 +175,13 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
168
175
  response.writeHead(status, {
169
176
  ...BASE,
170
177
  "content-type": "text/html; charset=utf-8",
171
- // A form posts here, and its answer may redirect to a client: those origins only.
172
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${formTargets.join(" ")}; frame-ancestors 'none'; base-uri 'none'`,
178
+ // The page loads its theme's files from this origin and runs nothing. A form posts here,
179
+ // and its answer may redirect to a client: those origins only.
180
+ "content-security-policy": themePageCsp(
181
+ options.server.pages,
182
+ "'none'",
183
+ ["'self'", ...formTargets].join(" "),
184
+ ),
173
185
  // A form's POST must carry this page's Origin (D166 item 10).
174
186
  "referrer-policy": "same-origin",
175
187
  ...extra,
@@ -185,11 +197,7 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
185
197
  response.end();
186
198
  };
187
199
  const problem = (response: ServerResponse, status: number, message: string): void =>
188
- send(
189
- response,
190
- status,
191
- shell("Sign-in can't continue", `<p role="alert">${escapeHtml(message)}</p>`),
192
- );
200
+ send(response, status, pages.problem(at(response), message));
193
201
 
194
202
  // ── in-progress records ─────────────────────────────────────────────────────────────────
195
203
 
@@ -298,18 +306,14 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
298
306
  message?: string,
299
307
  ): Promise<void> => {
300
308
  const list = await providers();
301
- const links = list
302
- .map(
303
- (provider) =>
304
- `<p><a class="button" href="/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}">Continue with ${escapeHtml(provider.label)}</a></p>`,
305
- )
306
- .join("");
307
309
  send(
308
310
  response,
309
311
  200,
310
- shell(
311
- "Sign in to Mostra",
312
- `${message ? `<p role="alert">${escapeHtml(message)}</p>` : ""}${links || "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"}`,
312
+ pages.signIn(
313
+ at(response),
314
+ list.map((provider) => ({ id: provider.id, label: provider.label })),
315
+ next,
316
+ message,
313
317
  ),
314
318
  );
315
319
  };
@@ -492,26 +496,24 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
492
496
  signed: { accountId: string; hash: string },
493
497
  homeId: string | undefined,
494
498
  ): void => {
495
- const who = auth.accountName(signed.accountId).name ?? "your account";
499
+ const who = auth.accountName(signed.accountId).name ?? API_PAGE_WORDS.yourAccount;
496
500
  const redirectHost = new URL(pending.redirectUri).host;
497
501
  const loopback = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/.test(redirectHost);
498
- const body =
499
- client.kind === "shell"
500
- ? `<p>Continue as <strong>${escapeHtml(who)}</strong> to answer <strong>${escapeHtml(
501
- (homeId !== undefined ? options.ownerName(homeId) : undefined) ?? "this person",
502
- )}</strong>'s page? They will see your name with your answers.</p>`
503
- : `<p><strong>${escapeHtml(client.name)}</strong>${client.unverified ? ' <span class="muted">(a name the app gives itself, not checked)</span>' : ""} asks to use Mostra as <strong>${escapeHtml(who)}</strong>: to read, create and change your hosted pages and their answers.</p>
504
- <p>It will send you back to <strong>${escapeHtml(redirectHost)}</strong>.${loopback ? " That is a program on your own computer: continue only if you started this there." : ""}</p>`;
502
+ const form = {
503
+ action: `/oauth/authorize/continue?authorize=${encodeURIComponent(handle)}`,
504
+ csrf: csrf(signed.hash, `consent ${handle}`),
505
+ };
505
506
  send(
506
507
  response,
507
508
  200,
508
- shell(
509
- client.kind === "shell" ? "Answer as yourself" : "Allow access",
510
- `${body}<form method="post" action="/oauth/authorize/continue?authorize=${encodeURIComponent(handle)}">
511
- <input type="hidden" name="csrf" value="${csrf(signed.hash, `consent ${handle}`)}">
512
- <button name="decision" value="approve">${client.kind === "shell" ? "Continue" : "Allow"}</button>
513
- <button name="decision" value="deny">Cancel</button></form>`,
514
- ),
509
+ client.kind === "shell"
510
+ ? pages.answerAs(
511
+ at(response),
512
+ form,
513
+ who,
514
+ homeId !== undefined ? options.ownerName(homeId) : undefined,
515
+ )
516
+ : pages.allow(at(response), form, client, who, redirectHost, loopback),
515
517
  {},
516
518
  [new URL(pending.redirectUri).origin],
517
519
  );
@@ -738,16 +740,7 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
738
740
  if (name && method === "GET") {
739
741
  // The development provider's page: a name, trusted as typed (D166 item 4).
740
742
  const state = url.searchParams.get("state") ?? "";
741
- send(
742
- response,
743
- 200,
744
- shell(
745
- "Development sign-in",
746
- `<p class="muted">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.</p>
747
- <form method="post" action="/signin/${escapeHtml(id)}/name"><input type="hidden" name="state" value="${escapeHtml(state)}">
748
- <label>Your name <input name="name" required maxlength="64"></label> <button>Continue</button></form>`,
749
- ),
750
- );
743
+ send(response, 200, pages.developmentName(at(response), id, state));
751
744
  return true;
752
745
  }
753
746
  let params: Record<string, string>;
@@ -6,7 +6,9 @@
6
6
  */
7
7
  import { readFileSync } from "node:fs";
8
8
  import { createDiagnostic, Duration, RpcError } from "@mostra/protocol";
9
+ import { safeHref } from "@mostra/themes";
9
10
  import * as z from "zod";
11
+ import type { AppearanceConfig } from "../gateway/index.ts";
10
12
  import type { Environment } from "../log.ts";
11
13
  import { validProxies } from "./clients.ts";
12
14
 
@@ -50,6 +52,18 @@ const Origin: z.ZodType<string> = z.string().refine(
50
52
  { message: "must be an https: origin (http: only on loopback), with no path" },
51
53
  );
52
54
 
55
+ /**
56
+ * A name or a short line a server's pages show (D171): 1 to 64 characters with no control,
57
+ * format or separator characters, as `verifierLabel` holds labels, so one can't read as another.
58
+ */
59
+ const PageName: z.ZodType<string> = z
60
+ .string()
61
+ .min(1)
62
+ .max(64)
63
+ .refine((value) => value.trim() !== "" && !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), {
64
+ message: "must be 1 to 64 characters with no control or format characters",
65
+ });
66
+
53
67
  /** A rate limit: `count` per `per`. */
54
68
  export interface Rate {
55
69
  readonly count: number;
@@ -126,6 +140,8 @@ export interface RemoteServerConfig {
126
140
  readonly framing?: { readonly frameAncestors: "'none'" } | undefined;
127
141
  readonly operator?: string | undefined;
128
142
  readonly chatHosts?: Record<string, unknown> | undefined;
143
+ /** How the server's own pages look and name themselves (D171). */
144
+ readonly appearance?: AppearanceConfig | undefined;
129
145
  }
130
146
 
131
147
  /** The schema of {@link RemoteServerConfig}. */
@@ -190,6 +206,35 @@ const Config: z.ZodType<RemoteServerConfig> & { readonly shape: Record<string, u
190
206
  framing: z.strictObject({ frameAncestors: z.literal("'none'") }).optional(),
191
207
  operator: z.string().optional(),
192
208
  chatHosts: z.record(z.string(), z.unknown()).optional(),
209
+ appearance: z
210
+ .strictObject({
211
+ theme: z.enum(["studio", "mostra"]).optional(),
212
+ name: PageName.nullable().optional(),
213
+ logo: z
214
+ .strictObject({
215
+ file: z.string().regex(/\.(svg|png|webp)$/i, {
216
+ message: "must be an .svg, .png or .webp file",
217
+ }),
218
+ alt: PageName,
219
+ width: z.int().min(1).max(400),
220
+ height: z.int().min(1).max(120),
221
+ })
222
+ .optional(),
223
+ stageLine: PageName.optional(),
224
+ default: z.enum(["system", "light", "dark"]).optional(),
225
+ footer: z
226
+ .array(
227
+ z.strictObject({
228
+ href: z.string().refine((href) => safeHref(href) !== undefined, {
229
+ message: "must be an https: address or a path of this server",
230
+ }),
231
+ text: PageName,
232
+ }),
233
+ )
234
+ .max(6)
235
+ .optional(),
236
+ })
237
+ .optional(),
193
238
  });
194
239
 
195
240
  /** The configuration keys, and the variable each also comes from. */
@@ -42,6 +42,7 @@ import {
42
42
  createGateway,
43
43
  type FaceSpec,
44
44
  type Gateway,
45
+ type ServerPages,
45
46
  } from "../gateway/index.ts";
46
47
  import { platformName } from "../home/index.ts";
47
48
  import { createEphemeralBus, createInteraction, type Interaction } from "../interaction/index.ts";
@@ -209,6 +210,8 @@ export interface HostedServices {
209
210
  readonly owner: (homeId: string) => HomeOwner;
210
211
  readonly signInOffered: () => boolean;
211
212
  readonly madeWith?: { readonly href?: string } | undefined;
213
+ /** The server's own pages, in its operator's theme and name (D171). */
214
+ readonly pages?: (() => ServerPages) | undefined;
212
215
  /** The server's routing by exact `Host`: operator hosts, their frames and link hosts (D167). */
213
216
  readonly routing: Routing;
214
217
  /** The server's meter: views here, submissions through the operator feed. */
@@ -497,7 +500,9 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
497
500
  );
498
501
  },
499
502
  };
503
+ const pages = options.services?.pages?.();
500
504
  const gateway: Gateway = createGateway({
505
+ ...(pages ? { pages } : {}),
501
506
  ledger,
502
507
  log,
503
508
  addressing,