@mostra/runtime 0.12.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.
Files changed (37) hide show
  1. package/dist/bin.js +2912 -2318
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{instance-CBUlOmzG.js → instance-CFTw3g-c.js} +227 -25
  5. package/dist/instance-CFTw3g-c.js.map +1 -0
  6. package/dist/reference/diagnostics.json +2 -2
  7. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +2 -2
  8. package/dist/reference/self-hosting.md +2 -1
  9. package/dist/skill/SKILL.md +2 -2
  10. package/dist/skill/assets/examples/dashboard/styles.css +27 -9
  11. package/dist/skill/assets/examples/decision/styles.css +27 -9
  12. package/dist/skill/assets/examples/inbox/styles.css +27 -9
  13. package/dist/skill/assets/studio.css +27 -9
  14. package/dist/skill/references/mcp.md +2 -2
  15. package/package.json +7 -6
  16. package/src/actions/index.ts +5 -2
  17. package/src/gateway/actions.ts +6 -1
  18. package/src/gateway/capabilities.ts +5 -1
  19. package/src/gateway/http.ts +15 -19
  20. package/src/gateway/index.ts +70 -1
  21. package/src/gateway/listener.ts +10 -5
  22. package/src/gateway/routes.ts +6 -1
  23. package/src/gateway/theme.ts +238 -0
  24. package/src/ledger/migrations.ts +9 -0
  25. package/src/server/api.ts +79 -87
  26. package/src/server/auth.ts +83 -16
  27. package/src/server/authorize.ts +74 -58
  28. package/src/server/config.ts +98 -0
  29. package/src/server/directory.ts +51 -0
  30. package/src/server/hosted-pages.ts +19 -6
  31. package/src/server/hosted.ts +59 -27
  32. package/src/server/index.ts +144 -17
  33. package/src/server/metering.ts +117 -12
  34. package/src/server/pages.ts +242 -0
  35. package/src/server/providers.ts +61 -9
  36. package/src/server/relay.ts +258 -107
  37. package/dist/instance-CBUlOmzG.js.map +0 -1
@@ -266,6 +266,8 @@ export interface CapabilitiesOptions {
266
266
  * links, so its operator's `revokeLink` finds a link's home, WP-30).
267
267
  */
268
268
  readonly onMinted?: (token: { readonly tokenId: string; readonly artifactId: string }) => void;
269
+ /** How often a session's `last_seen_at` is written at most; an hour unless a test shortens it. */
270
+ readonly touchIntervalMs?: number;
269
271
  }
270
272
 
271
273
  /** What a stream ticket opens (D158 item 5). */
@@ -302,6 +304,7 @@ export class Capabilities {
302
304
  /** Failure times per artifact (`""` for tokens of no artifact in this home). */
303
305
  readonly #failures = new Map<string, number[]>();
304
306
  readonly #touched = new Map<string, number>();
307
+ readonly #touchIntervalMs: number;
305
308
 
306
309
  constructor(options: CapabilitiesOptions) {
307
310
  this.#ledger = options.ledger;
@@ -311,6 +314,7 @@ export class Capabilities {
311
314
  this.#shellOrigin = options.shellOrigin;
312
315
  this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());
313
316
  this.#onMinted = options.onMinted;
317
+ this.#touchIntervalMs = options.touchIntervalMs ?? TOUCH_INTERVAL_MS;
314
318
  }
315
319
 
316
320
  /** Runs `fn` in the caller's transaction, or in a new one. */
@@ -731,7 +735,7 @@ export class Capabilities {
731
735
  /** Writes `last_seen_at` at most hourly, so serving files doesn't write the ledger per request. */
732
736
  #touch(sessionId: string): void {
733
737
  const now = this.#now();
734
- if (now - (this.#touched.get(sessionId) ?? 0) < TOUCH_INTERVAL_MS) return;
738
+ if (now - (this.#touched.get(sessionId) ?? 0) < this.#touchIntervalMs) return;
735
739
  this.#touched.set(sessionId, now);
736
740
  this.#ledger.write((db) =>
737
741
  db.run("UPDATE session SET last_seen_at = ? WHERE id = ?", this.#iso(now), sessionId),
@@ -6,8 +6,10 @@
6
6
  */
7
7
  import type { IncomingMessage } from "node:http";
8
8
  import type { HttpBindings } from "@hono/node-server";
9
- import type { Diagnostic, Refusal } from "@mostra/protocol";
9
+ import type { Refusal } from "@mostra/protocol";
10
10
  import { refusal } from "@mostra/protocol";
11
+ import type { Pages } from "@mostra/themes";
12
+ import { defaultPages, refusalDocument, themePageCsp } from "./theme.ts";
11
13
 
12
14
  /** The Hono environment of a listener: Node's request and response objects. */
13
15
  export type HttpEnv = { Bindings: HttpBindings };
@@ -97,16 +99,6 @@ export function wantsDocument(headers: Headers): boolean {
97
99
  return (headers.get("accept") ?? "").includes("text/html");
98
100
  }
99
101
 
100
- /** Escapes text for HTML. */
101
- function escapeHtml(text: string): string {
102
- return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
103
- }
104
-
105
- /** A plain page for a refused navigation: no scripts, no external resources. */
106
- function refusalPage(diagnostic: Diagnostic): string {
107
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Mostra</title><style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:.25rem;padding:2rem;text-align:center;color-scheme:light dark}h1{font-size:1.25rem;margin:0}p{margin:0;opacity:.8}code{opacity:.5;font-size:.75rem;margin-top:1rem}</style></head><body><h1>${escapeHtml(diagnostic.message)}</h1>${diagnostic.hint ? `<p>${escapeHtml(diagnostic.hint)}</p>` : ""}<code>${escapeHtml(diagnostic.code)}</code></body></html>`;
108
- }
109
-
110
102
  /** The response for a refusal: the diagnostic as JSON, or a plain page for a navigation. */
111
103
  export function refusalResponse(
112
104
  refused: Refusal & { readonly retryAfter?: number },
@@ -114,6 +106,8 @@ export function refusalResponse(
114
106
  readonly document: boolean;
115
107
  readonly method?: string;
116
108
  readonly frameAncestors?: string;
109
+ /** The server's own pages, in its operator's theme; Studio, named Mostra, by default. */
110
+ readonly pages?: Pages;
117
111
  },
118
112
  ): Response {
119
113
  const headers: Record<string, string> = { ...BASE_HEADERS, "cache-control": "no-store" };
@@ -122,14 +116,16 @@ export function refusalResponse(
122
116
  const head = options.method === "HEAD";
123
117
  if (options.document) {
124
118
  headers["content-type"] = "text/html; charset=utf-8";
125
- // The page has an inline style and nothing else; only the shell may frame it (on artifacts).
126
- headers["content-security-policy"] = [
127
- "default-src 'none'",
128
- "style-src 'unsafe-inline'",
129
- `frame-ancestors ${options.frameAncestors ?? "'none'"}`,
130
- "base-uri 'none'",
131
- ].join("; ");
132
- return new Response(head ? null : refusalPage(refused.diagnostic), {
119
+ // The page loads its theme's files from its own origin and runs nothing; only the shell may
120
+ // frame it (on artifacts).
121
+ const pages = options.pages ?? defaultPages().pages;
122
+ headers["content-security-policy"] = themePageCsp(pages, options.frameAncestors ?? "'none'");
123
+ const page = refusalDocument(pages, {
124
+ title: refused.diagnostic.message,
125
+ detail: refused.diagnostic.hint,
126
+ code: refused.diagnostic.code,
127
+ });
128
+ return new Response(head ? null : page, {
133
129
  status: refused.status,
134
130
  headers,
135
131
  });
@@ -60,6 +60,7 @@ import {
60
60
  viewRotateMethod,
61
61
  viewUrlMethod,
62
62
  } from "@mostra/protocol";
63
+ import type { Pages } from "@mostra/themes";
63
64
  import type { Actions } from "../actions/index.ts";
64
65
  import { type Addressing, type FrameMode, hostOf } from "../addressing/index.ts";
65
66
  import { runtimeRoot } from "../deps/index.ts";
@@ -104,6 +105,7 @@ export { resetOnClose } from "./listener.ts";
104
105
  import { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from "./routes.ts";
105
106
  import { fileResponse, findFile } from "./serve.ts";
106
107
  import { rosterMethods } from "./team.ts";
108
+ import { defaultPages, type ServerPages, THEME_BASE } from "./theme.ts";
107
109
  import { BOOTSTRAP_PAGE, SERVICE_WORKER_PATH, SERVICE_WORKER_SOURCE } from "./worker.ts";
108
110
 
109
111
  export { Capabilities, capabilityKey } from "./capabilities.ts";
@@ -112,6 +114,17 @@ export type { DevUpstream } from "./dev.ts";
112
114
  export { BASE_HEADERS, documentHeaders, isRefusal, jsonResponse, readJsonObject } from "./http.ts";
113
115
  export { IDENTITY_TIMEOUT_MS, resolveIdentity } from "./identity.ts";
114
116
  export type { RouteContext, RouteSpec } from "./routes.ts";
117
+ export {
118
+ type AppearanceConfig,
119
+ defaultPages,
120
+ MADE_WITH_HREF,
121
+ PAGE_REFUSALS,
122
+ refusalDocument,
123
+ type ServerPages,
124
+ serverPages,
125
+ THEME_BASE,
126
+ themePageCsp,
127
+ } from "./theme.ts";
115
128
 
116
129
  /** What the gateway reads about artifacts and versions. */
117
130
  export interface GatewayArtifacts {
@@ -256,6 +269,11 @@ export interface GatewayOptions {
256
269
  * header, and its frames on the route's label, always in worker mode.
257
270
  */
258
271
  readonly hosted?: HostedAddressing;
272
+ /**
273
+ * The pages this gateway draws itself (a refused navigation), in its operator's theme and name
274
+ * (D171); Studio, named Mostra, when absent.
275
+ */
276
+ readonly pages?: ServerPages;
259
277
  }
260
278
 
261
279
  /** Where a hosted home's pages live (INTERFACES §18.4). */
@@ -295,6 +313,8 @@ export interface HostedAddressing {
295
313
  readonly artifactId: string;
296
314
  readonly versionId: string;
297
315
  readonly tokenId: string;
316
+ /** The shell session asking for the ticket: its own activity is this visit's (MT-03). */
317
+ readonly sessionId: string;
298
318
  readonly client: string | undefined;
299
319
  }) => Promise<(Refusal & { readonly retryAfter?: number }) | undefined>;
300
320
  /** A version whose files are withheld now (a quarantine): refused even to an open frame. */
@@ -554,6 +574,35 @@ interface FaceEntry {
554
574
 
555
575
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
556
576
  export function createGateway(options: GatewayOptions): Gateway {
577
+ const serverPages = options.pages ?? defaultPages();
578
+ const pagesOf = (): Pages => serverPages.pages;
579
+ /**
580
+ * `GET /_mostra/theme/*`: the files the gateway's own pages load (D171), on every listener, with
581
+ * no session: they are the same public files for everyone and carry nothing of an artifact.
582
+ */
583
+ const themeAsset =
584
+ (checks: Pick<ListenerChecks, "log" | "policy" | "frameAncestors" | "pages">) =>
585
+ (context: RouteContext): Response => {
586
+ const url = new URL(context.request.url);
587
+ const file = serverPages.asset(url.pathname.slice(THEME_BASE.length));
588
+ if (!file) {
589
+ return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No theme file at this path."), {
590
+ method: context.request.method,
591
+ path: url.pathname,
592
+ document: false,
593
+ });
594
+ }
595
+ return new Response(
596
+ context.request.method === "HEAD"
597
+ ? null
598
+ : typeof file.body === "string"
599
+ ? file.body
600
+ : new Uint8Array(file.body),
601
+ {
602
+ headers: { ...BASE_HEADERS, ...file.headers },
603
+ },
604
+ );
605
+ };
557
606
  const { addressing, capabilities, artifacts, log, interaction } = options;
558
607
  // Respondents and presence for pages (D168): in memory, over the pages' ephemeral bus.
559
608
  const team = options.bus
@@ -681,7 +730,7 @@ export function createGateway(options: GatewayOptions): Gateway {
681
730
  message: `${number === undefined ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.`,
682
731
  }),
683
732
  },
684
- { document, frameAncestors },
733
+ { document, frameAncestors, pages: pagesOf() },
685
734
  );
686
735
 
687
736
  const link = (token: MintedToken): CapabilityLink => ({
@@ -733,6 +782,7 @@ export function createGateway(options: GatewayOptions): Gateway {
733
782
  const listener = createListener({
734
783
  policy: () => ({ origin: entry?.origin ?? "", hosts: way().hosts() }),
735
784
  log,
785
+ pages: pagesOf,
736
786
  frameAncestors: () =>
737
787
  spec.listener === "shell" ? "'none'" : (shellOf(way(), spec.group)?.origin() ?? "'none'"),
738
788
  configure: (app) => {
@@ -1042,6 +1092,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1042
1092
  cookieName: () => `mostra-${way().port()}`,
1043
1093
  // A hosted shell's session travels in a header, never a cookie (D165 item 8).
1044
1094
  mode: () => (way().by === "hosted" ? "header" : "cookie"),
1095
+ pages: pagesOf,
1045
1096
  frameAncestors: () => "'none'",
1046
1097
  artifactOf: (params) => {
1047
1098
  const id = params["artifactId"];
@@ -1405,6 +1456,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1405
1456
  artifactId,
1406
1457
  versionId: version.id,
1407
1458
  tokenId: session.grant.tokenId,
1459
+ sessionId: session.id,
1408
1460
  client: context.client,
1409
1461
  });
1410
1462
  if (refused) return refuse(checks, refused, meta);
@@ -1496,6 +1548,13 @@ export function createGateway(options: GatewayOptions): Gateway {
1496
1548
  auth: "none",
1497
1549
  handler: shellAsset,
1498
1550
  },
1551
+ {
1552
+ method: "GET",
1553
+ path: `${THEME_BASE}*`,
1554
+ intent: "read",
1555
+ auth: "none",
1556
+ handler: themeAsset(checks),
1557
+ },
1499
1558
  {
1500
1559
  method: "POST",
1501
1560
  path: "/a/:artifactId/_mostra/session",
@@ -1591,6 +1650,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1591
1650
  capabilities,
1592
1651
  log,
1593
1652
  cookieName: () => `mostra-${wayOf().port()}`,
1653
+ pages: pagesOf,
1594
1654
  frameAncestors: () => {
1595
1655
  const way = wayOf();
1596
1656
  if (way.by === "hosted" && hosted?.frameAncestors) {
@@ -1943,6 +2003,13 @@ export function createGateway(options: GatewayOptions): Gateway {
1943
2003
 
1944
2004
  return [
1945
2005
  { method: "GET", path: "/_mostra/enter", intent: "read", auth: "none", handler: enter },
2006
+ {
2007
+ method: "GET",
2008
+ path: `${THEME_BASE}*`,
2009
+ intent: "read",
2010
+ auth: "none",
2011
+ handler: themeAsset(checks),
2012
+ },
1946
2013
  {
1947
2014
  method: "POST",
1948
2015
  path: "/_mostra/enter",
@@ -2023,6 +2090,7 @@ export function createGateway(options: GatewayOptions): Gateway {
2023
2090
  const listener = createListener({
2024
2091
  policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),
2025
2092
  log,
2093
+ pages: pagesOf,
2026
2094
  frameAncestors: () => shellOrigin(),
2027
2095
  configure: (app) =>
2028
2096
  mount(
@@ -2111,6 +2179,7 @@ export function createGateway(options: GatewayOptions): Gateway {
2111
2179
  shellListener = createListener({
2112
2180
  policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
2113
2181
  log,
2182
+ pages: pagesOf,
2114
2183
  frameAncestors: () => "'none'",
2115
2184
  configure: (app) =>
2116
2185
  mount(
@@ -16,10 +16,12 @@ import {
16
16
  type RequestPolicy,
17
17
  refusal,
18
18
  } from "@mostra/protocol";
19
+ import type { Pages } from "@mostra/themes";
19
20
  import { Hono } from "hono";
20
21
  import type { Log } from "../log.ts";
21
22
  import { BASE_HEADERS, type HttpEnv, headerPairs, refusalResponse } from "./http.ts";
22
23
  import { refuse } from "./routes.ts";
24
+ import { defaultPages, refusalDocument, themePageCsp } from "./theme.ts";
23
25
 
24
26
  /**
25
27
  * Node's limit on request headers for gateway listeners. Every port of the loopback host shares one
@@ -143,13 +145,15 @@ function headersTooLarge(socket: Duplex): void {
143
145
  "MOSTRA_HYGIENE_HEADERS_TOO_LARGE",
144
146
  "This browser sent more cookies than any page here sets.",
145
147
  );
146
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Mostra</title><style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:.25rem;padding:2rem;text-align:center;color-scheme:light dark}h1{font-size:1.25rem;margin:0}p{margin:0;opacity:.8}code{opacity:.5;font-size:.75rem;margin-top:1rem}</style></head><body><h1>This browser sent more cookies than Mostra accepts</h1><p>A page on this machine filled them. They have been cleared: open your link again.</p><code>MOSTRA_HYGIENE_HEADERS_TOO_LARGE</code></body></html>`;
148
+ const pages = defaultPages().pages;
149
+ const html = refusalDocument(pages, {
150
+ title: "This browser sent more cookies than Mostra accepts",
151
+ detail: "A page on this machine filled them. They have been cleared: open your link again.",
152
+ code: "MOSTRA_HYGIENE_HEADERS_TOO_LARGE",
153
+ });
147
154
  writeRaw(socket, refused, {
148
155
  html,
149
- headers: [
150
- 'clear-site-data: "cookies"',
151
- "content-security-policy: default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'",
152
- ],
156
+ headers: ['clear-site-data: "cookies"', `content-security-policy: ${themePageCsp(pages)}`],
153
157
  });
154
158
  }
155
159
 
@@ -205,6 +209,7 @@ export function createListener(options: {
205
209
  readonly policy: () => RequestPolicy;
206
210
  readonly log: Log;
207
211
  readonly frameAncestors: () => string;
212
+ readonly pages?: () => Pages;
208
213
  readonly configure: (app: Hono<HttpEnv>) => void;
209
214
  /**
210
215
  * Takes an upgrade whose Host, target and Origin passed the checks (a dev sandbox's HMR
@@ -27,6 +27,7 @@ import {
27
27
  SHELL_SESSION_HEADER,
28
28
  scopeAllows,
29
29
  } from "@mostra/protocol";
30
+ import type { Pages } from "@mostra/themes";
30
31
  import type { Context, Hono } from "hono";
31
32
  import type { Log } from "../log.ts";
32
33
  import type { Capabilities, ResolvedSession, SessionMode } from "./capabilities.ts";
@@ -103,11 +104,13 @@ export interface ListenerChecks {
103
104
  readonly streams?: () => boolean;
104
105
  /** The client's address of a request (a remote server's trusted proxies); default its peer. */
105
106
  readonly client?: (incoming: import("node:http").IncomingMessage) => string | undefined;
107
+ /** The server's own pages, in its operator's theme (D171); Studio, named Mostra, by default. */
108
+ readonly pages?: () => Pages;
106
109
  }
107
110
 
108
111
  /** Logs a refusal without any of the request's capability material, and answers it. */
109
112
  export function refuse(
110
- checks: Pick<ListenerChecks, "log" | "policy" | "frameAncestors">,
113
+ checks: Pick<ListenerChecks, "log" | "policy" | "frameAncestors" | "pages">,
111
114
  refused: Refusal & { readonly retryAfter?: number },
112
115
  request: { readonly method: string; readonly path: string; readonly document: boolean },
113
116
  ): Response {
@@ -120,10 +123,12 @@ export function refuse(
120
123
  path: request.path,
121
124
  origin: checks.policy().origin,
122
125
  });
126
+ const pages = checks.pages?.();
123
127
  return refusalResponse(refused, {
124
128
  document: request.document,
125
129
  method: request.method,
126
130
  frameAncestors: checks.frameAncestors(),
131
+ ...(pages ? { pages } : {}),
127
132
  });
128
133
  }
129
134
 
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The look of the pages the gateway and the remote server draw themselves (D171): a refusal a
3
+ * person's navigation meets, and on a remote server its API origin's sign-in, device and consent
4
+ * pages. They are `@mostra/themes`' pages, in the theme and under the name the server's operator
5
+ * configured, with their stylesheet, faces and marks served by the page's own origin under
6
+ * `/_mostra/theme/`, so no page needs a script, an inline style or a third party.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import {
10
+ type Appearance,
11
+ createPages,
12
+ type FooterLink,
13
+ html,
14
+ mostra,
15
+ type PageAsset,
16
+ type Pages,
17
+ studio,
18
+ } from "@mostra/themes";
19
+
20
+ /** Where a page's theme files are served, on every origin that draws one. */
21
+ export const THEME_BASE = "/_mostra/theme/";
22
+
23
+ /** Where "Make pages like this" goes from a page that runs on Mostra. */
24
+ export const MADE_WITH_HREF = "https://mostradev.com";
25
+
26
+ /**
27
+ * How a server's own pages look and name themselves (INTERFACES §18.1 `appearance`): Studio and
28
+ * the name Mostra unless the operator says otherwise.
29
+ */
30
+ export interface AppearanceConfig {
31
+ /** `studio` (the default), or `mostra`, Mostra's own brand. */
32
+ readonly theme?: "studio" | "mostra" | undefined;
33
+ /** The name pages speak of: `Mostra` by default, another name, or `null` for none. */
34
+ readonly name?: string | null | undefined;
35
+ /** An image the server serves as its mark: a file it reads at start. */
36
+ readonly logo?: LogoConfig | undefined;
37
+ /** A line on the `mostra` theme's stage. */
38
+ readonly stageLine?: string | undefined;
39
+ /** The appearance a person who never chose gets. */
40
+ readonly default?: Appearance | undefined;
41
+ /** Links in every page's footer: terms, privacy, help. */
42
+ readonly footer?: readonly FooterLink[] | undefined;
43
+ }
44
+
45
+ /** An operator's mark: an SVG, PNG or WebP file of at most 256 KiB, and the size it shows at. */
46
+ export interface LogoConfig {
47
+ readonly file: string;
48
+ readonly alt: string;
49
+ readonly width: number;
50
+ readonly height: number;
51
+ }
52
+
53
+ /** The kinds of image a logo may be, by extension. */
54
+ export const LOGO_TYPES: Readonly<Record<string, string>> = {
55
+ ".svg": "image/svg+xml",
56
+ ".png": "image/png",
57
+ ".webp": "image/webp",
58
+ };
59
+
60
+ /** A server's own pages, and the bytes of every file they load. */
61
+ export interface ServerPages {
62
+ readonly pages: Pages;
63
+ /** The theme the operator dressed its pages in. */
64
+ readonly theme: "studio" | "mostra";
65
+ /** The name its pages speak of, or `null` for none. */
66
+ readonly name: string | null;
67
+ /** The appearance a person who never chose gets. */
68
+ readonly defaultAppearance: Appearance;
69
+ /** The answer for a theme file (`path` after `THEME_BASE`), or `undefined` for none. */
70
+ asset(path: string): ThemeFile | undefined;
71
+ }
72
+
73
+ /** One file a page loads: its headers and its bytes. */
74
+ export interface ThemeFile {
75
+ readonly headers: Readonly<Record<string, string>>;
76
+ readonly body: Uint8Array | string;
77
+ }
78
+
79
+ const extensionOf = (file: string): string => file.slice(file.lastIndexOf(".")).toLowerCase();
80
+
81
+ /**
82
+ * Makes a server's pages. A logo is read now, so a missing or unusable one stops the server at its
83
+ * start (the caller reports `MOSTRA_REMOTE_CONFIG_INVALID`) rather than at a person's page.
84
+ */
85
+ export function serverPages(
86
+ config: AppearanceConfig = {},
87
+ options: { readonly appearanceAction?: string } = {},
88
+ ): ServerPages {
89
+ const logo = config.logo;
90
+ let logoAsset: PageAsset | undefined;
91
+ let logoBytes: Uint8Array | undefined;
92
+ if (logo) {
93
+ const type = LOGO_TYPES[extensionOf(logo.file)];
94
+ if (!type) throw new Error(`The logo ${logo.file} isn't an SVG, PNG or WebP file.`);
95
+ logoBytes = readFileSync(logo.file);
96
+ if (logoBytes.length > 256 * 1024) throw new Error(`The logo ${logo.file} is over 256 KiB.`);
97
+ logoAsset = {
98
+ path: `logo${extensionOf(logo.file)}`,
99
+ contentType: type,
100
+ body: { text: "" },
101
+ immutable: false,
102
+ };
103
+ }
104
+ const pages = createPages({
105
+ theme: config.theme === "mostra" ? mostra : studio,
106
+ identity: {
107
+ name: config.name === undefined ? "Mostra" : config.name,
108
+ ...(logo && logoAsset
109
+ ? {
110
+ logo: {
111
+ src: `${THEME_BASE}${logoAsset.path}`,
112
+ alt: logo.alt,
113
+ width: logo.width,
114
+ height: logo.height,
115
+ },
116
+ }
117
+ : {}),
118
+ ...(config.stageLine !== undefined ? { stageLine: config.stageLine } : {}),
119
+ },
120
+ assetBase: THEME_BASE,
121
+ madeWithHref: MADE_WITH_HREF,
122
+ ...(config.footer ? { footer: config.footer } : {}),
123
+ ...(options.appearanceAction ? { appearanceAction: options.appearanceAction } : {}),
124
+ ...(config.default ? { defaultAppearance: config.default } : {}),
125
+ });
126
+ const files = new Map<string, ThemeFile>();
127
+ for (const asset of pages.assets) {
128
+ const body = "text" in asset.body ? asset.body.text : readFileSync(new URL(asset.body.fileUrl));
129
+ files.set(asset.path, {
130
+ headers: {
131
+ "content-type": asset.contentType,
132
+ "cache-control": asset.immutable
133
+ ? "public, max-age=31536000, immutable"
134
+ : "public, max-age=3600",
135
+ // An image served alone (an SVG mark opened as its own page) runs nothing.
136
+ ...(asset.contentType === "image/svg+xml"
137
+ ? { "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" }
138
+ : {}),
139
+ },
140
+ body,
141
+ });
142
+ }
143
+ if (logoAsset && logoBytes) {
144
+ files.set(logoAsset.path, {
145
+ headers: {
146
+ "content-type": logoAsset.contentType,
147
+ "cache-control": "public, max-age=3600",
148
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
149
+ },
150
+ body: logoBytes,
151
+ });
152
+ }
153
+ return {
154
+ pages,
155
+ theme: config.theme ?? "studio",
156
+ name: config.name === undefined ? "Mostra" : config.name,
157
+ defaultAppearance: config.default ?? "system",
158
+ asset: (path) => files.get(path),
159
+ };
160
+ }
161
+
162
+ let standard: ServerPages | undefined;
163
+
164
+ /** The pages of a server that configured nothing: Studio, named Mostra. Made once. */
165
+ export function defaultPages(): ServerPages {
166
+ standard ??= serverPages();
167
+ return standard;
168
+ }
169
+
170
+ /** What a refused navigation says: its message, the way on if there is one, and its code. */
171
+ export interface RefusalWords {
172
+ readonly title: string;
173
+ readonly detail?: string | undefined;
174
+ readonly code: string;
175
+ }
176
+
177
+ /**
178
+ * A page for a refused navigation, in the server's theme: no script, nothing of the artifact, and
179
+ * the diagnostic's code in small print, for whoever the person asks for help.
180
+ */
181
+ export function refusalDocument(pages: Pages, words: RefusalWords): string {
182
+ // A person who meets one of these at a link reads the page's own words, as the shell would say
183
+ // them; anything else keeps the diagnostic's message and hint.
184
+ const said = PAGE_REFUSALS[words.code] ?? words;
185
+ return pages.render({
186
+ kind: "notice",
187
+ tone: "problem",
188
+ title: said.title,
189
+ body: html`${said.detail ? html`<p>${said.detail}</p>` : ""}<p class="m-fine"><code translate="no">${words.code}</code></p>`,
190
+ });
191
+ }
192
+
193
+ /**
194
+ * What a refused navigation says to a person who opened a link (UX-01: the same words the shell
195
+ * uses for these refusals, `packages/shell/src/messages.ts`, kept equal by a test). Neutral, naming
196
+ * nobody (FAILURE_MODEL §11.3).
197
+ */
198
+ export const PAGE_REFUSALS: Readonly<
199
+ Record<string, { readonly title: string; readonly detail: string }>
200
+ > = {
201
+ MOSTRA_HYGIENE_TOKEN_REVOKED: {
202
+ title: "This link was revoked or has expired",
203
+ detail: "Ask whoever shared it for a new link.",
204
+ },
205
+ MOSTRA_HYGIENE_SESSION_MISSING: {
206
+ title: "Open the full link to view this artifact",
207
+ detail: "This page needs the link you were given, including everything after the #.",
208
+ },
209
+ MOSTRA_HYGIENE_TOKEN_INVALID: {
210
+ title: "This link doesn't work",
211
+ detail: "It may be incomplete or belong to another artifact. Copy the whole link again.",
212
+ },
213
+ MOSTRA_REMOTE_UNDER_REVIEW: {
214
+ title: "This page is under review",
215
+ detail: "The people who run this server are looking at it. Try again later.",
216
+ },
217
+ MOSTRA_REMOTE_HOME_SUSPENDED: {
218
+ title: "This page isn't available",
219
+ detail: "The account that shared it is suspended on this server.",
220
+ },
221
+ MOSTRA_REMOTE_HOME_MOVING: { title: "This page is moving", detail: "Try again in a minute." },
222
+ MOSTRA_REMOTE_LIMIT_REACHED: {
223
+ title: "This page isn't available right now",
224
+ detail: "Try again later.",
225
+ },
226
+ MOSTRA_HYGIENE_HOST_REFUSED: {
227
+ title: "There's no page here",
228
+ detail: "Check the link you were given: this address doesn't serve one.",
229
+ },
230
+ };
231
+
232
+ /** The `Content-Security-Policy` of a theme page that `frameAncestors` may frame. */
233
+ export function themePageCsp(pages: Pages, frameAncestors = "'none'", formAction?: string): string {
234
+ return [
235
+ pages.csp.replace("frame-ancestors 'none'", `frame-ancestors ${frameAncestors}`),
236
+ ...(formAction ? [`form-action ${formAction}`] : ["form-action 'none'"]),
237
+ ].join("; ");
238
+ }
@@ -923,4 +923,13 @@ export const MIGRATIONS: readonly Migration[] = [
923
923
  `);
924
924
  },
925
925
  },
926
+ {
927
+ version: 17,
928
+ name: "a link's views",
929
+ up(db) {
930
+ // A hosted link's idle expiry is judged by its last view (`LinkPolicy.idleExpiry`, MT-03),
931
+ // read at every frame ticket a hosted page asks for: the link's views by its token.
932
+ db.exec("CREATE INDEX view_token ON view (token_id, opened_at)");
933
+ },
934
+ },
926
935
  ];