@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.
@@ -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). */
@@ -556,6 +574,35 @@ interface FaceEntry {
556
574
 
557
575
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
558
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
+ };
559
606
  const { addressing, capabilities, artifacts, log, interaction } = options;
560
607
  // Respondents and presence for pages (D168): in memory, over the pages' ephemeral bus.
561
608
  const team = options.bus
@@ -683,7 +730,7 @@ export function createGateway(options: GatewayOptions): Gateway {
683
730
  message: `${number === undefined ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.`,
684
731
  }),
685
732
  },
686
- { document, frameAncestors },
733
+ { document, frameAncestors, pages: pagesOf() },
687
734
  );
688
735
 
689
736
  const link = (token: MintedToken): CapabilityLink => ({
@@ -735,6 +782,7 @@ export function createGateway(options: GatewayOptions): Gateway {
735
782
  const listener = createListener({
736
783
  policy: () => ({ origin: entry?.origin ?? "", hosts: way().hosts() }),
737
784
  log,
785
+ pages: pagesOf,
738
786
  frameAncestors: () =>
739
787
  spec.listener === "shell" ? "'none'" : (shellOf(way(), spec.group)?.origin() ?? "'none'"),
740
788
  configure: (app) => {
@@ -1044,6 +1092,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1044
1092
  cookieName: () => `mostra-${way().port()}`,
1045
1093
  // A hosted shell's session travels in a header, never a cookie (D165 item 8).
1046
1094
  mode: () => (way().by === "hosted" ? "header" : "cookie"),
1095
+ pages: pagesOf,
1047
1096
  frameAncestors: () => "'none'",
1048
1097
  artifactOf: (params) => {
1049
1098
  const id = params["artifactId"];
@@ -1499,6 +1548,13 @@ export function createGateway(options: GatewayOptions): Gateway {
1499
1548
  auth: "none",
1500
1549
  handler: shellAsset,
1501
1550
  },
1551
+ {
1552
+ method: "GET",
1553
+ path: `${THEME_BASE}*`,
1554
+ intent: "read",
1555
+ auth: "none",
1556
+ handler: themeAsset(checks),
1557
+ },
1502
1558
  {
1503
1559
  method: "POST",
1504
1560
  path: "/a/:artifactId/_mostra/session",
@@ -1594,6 +1650,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1594
1650
  capabilities,
1595
1651
  log,
1596
1652
  cookieName: () => `mostra-${wayOf().port()}`,
1653
+ pages: pagesOf,
1597
1654
  frameAncestors: () => {
1598
1655
  const way = wayOf();
1599
1656
  if (way.by === "hosted" && hosted?.frameAncestors) {
@@ -1946,6 +2003,13 @@ export function createGateway(options: GatewayOptions): Gateway {
1946
2003
 
1947
2004
  return [
1948
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
+ },
1949
2013
  {
1950
2014
  method: "POST",
1951
2015
  path: "/_mostra/enter",
@@ -2026,6 +2090,7 @@ export function createGateway(options: GatewayOptions): Gateway {
2026
2090
  const listener = createListener({
2027
2091
  policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),
2028
2092
  log,
2093
+ pages: pagesOf,
2029
2094
  frameAncestors: () => shellOrigin(),
2030
2095
  configure: (app) =>
2031
2096
  mount(
@@ -2114,6 +2179,7 @@ export function createGateway(options: GatewayOptions): Gateway {
2114
2179
  shellListener = createListener({
2115
2180
  policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
2116
2181
  log,
2182
+ pages: pagesOf,
2117
2183
  frameAncestors: () => "'none'",
2118
2184
  configure: (app) =>
2119
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
+ }