@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/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as startInstance, t as runtimeVersion } from "./instance-D5gh-sMM.js";
1
+ import { n as startInstance, t as runtimeVersion } from "./instance-CFTw3g-c.js";
2
2
  import { t as connectToSupervisor } from "./child-BmNZ4a70.js";
3
3
  export { connectToSupervisor, runtimeVersion, startInstance };
@@ -17,6 +17,7 @@ import * as z from "zod";
17
17
  import { parse as parse$1, parseDocument } from "yaml";
18
18
  import { pipeline } from "node:stream/promises";
19
19
  import { createZstdCompress, zstdCompressSync, zstdDecompressSync } from "node:zlib";
20
+ import { createPages, html, mostra, studio } from "@mostra/themes";
20
21
  import { createServer as createServer$1, request } from "node:http";
21
22
  import { getRequestListener } from "@hono/node-server";
22
23
  import { Hono } from "hono";
@@ -9952,6 +9953,154 @@ function contractRegressions(baseline, candidate, savedAnswers) {
9952
9953
  };
9953
9954
  }
9954
9955
  //#endregion
9956
+ //#region src/gateway/theme.ts
9957
+ /**
9958
+ * The look of the pages the gateway and the remote server draw themselves (D171): a refusal a
9959
+ * person's navigation meets, and on a remote server its API origin's sign-in, device and consent
9960
+ * pages. They are `@mostra/themes`' pages, in the theme and under the name the server's operator
9961
+ * configured, with their stylesheet, faces and marks served by the page's own origin under
9962
+ * `/_mostra/theme/`, so no page needs a script, an inline style or a third party.
9963
+ */
9964
+ /** Where a page's theme files are served, on every origin that draws one. */
9965
+ const THEME_BASE = "/_mostra/theme/";
9966
+ /** Where "Make pages like this" goes from a page that runs on Mostra. */
9967
+ const MADE_WITH_HREF = "https://mostradev.com";
9968
+ /** The kinds of image a logo may be, by extension. */
9969
+ const LOGO_TYPES = {
9970
+ ".svg": "image/svg+xml",
9971
+ ".png": "image/png",
9972
+ ".webp": "image/webp"
9973
+ };
9974
+ const extensionOf = (file) => file.slice(file.lastIndexOf(".")).toLowerCase();
9975
+ /**
9976
+ * Makes a server's pages. A logo is read now, so a missing or unusable one stops the server at its
9977
+ * start (the caller reports `MOSTRA_REMOTE_CONFIG_INVALID`) rather than at a person's page.
9978
+ */
9979
+ function serverPages(config = {}, options = {}) {
9980
+ const logo = config.logo;
9981
+ let logoAsset;
9982
+ let logoBytes;
9983
+ if (logo) {
9984
+ const type = LOGO_TYPES[extensionOf(logo.file)];
9985
+ if (!type) throw new Error(`The logo ${logo.file} isn't an SVG, PNG or WebP file.`);
9986
+ logoBytes = readFileSync(logo.file);
9987
+ if (logoBytes.length > 262144) throw new Error(`The logo ${logo.file} is over 256 KiB.`);
9988
+ logoAsset = {
9989
+ path: `logo${extensionOf(logo.file)}`,
9990
+ contentType: type,
9991
+ body: { text: "" },
9992
+ immutable: false
9993
+ };
9994
+ }
9995
+ const pages = createPages({
9996
+ theme: config.theme === "mostra" ? mostra : studio,
9997
+ identity: {
9998
+ name: config.name === void 0 ? "Mostra" : config.name,
9999
+ ...logo && logoAsset ? { logo: {
10000
+ src: `${THEME_BASE}${logoAsset.path}`,
10001
+ alt: logo.alt,
10002
+ width: logo.width,
10003
+ height: logo.height
10004
+ } } : {},
10005
+ ...config.stageLine !== void 0 ? { stageLine: config.stageLine } : {}
10006
+ },
10007
+ assetBase: THEME_BASE,
10008
+ madeWithHref: MADE_WITH_HREF,
10009
+ ...config.footer ? { footer: config.footer } : {},
10010
+ ...options.appearanceAction ? { appearanceAction: options.appearanceAction } : {},
10011
+ ...config.default ? { defaultAppearance: config.default } : {}
10012
+ });
10013
+ const files = /* @__PURE__ */ new Map();
10014
+ for (const asset of pages.assets) {
10015
+ const body = "text" in asset.body ? asset.body.text : readFileSync(new URL(asset.body.fileUrl));
10016
+ files.set(asset.path, {
10017
+ headers: {
10018
+ "content-type": asset.contentType,
10019
+ "cache-control": asset.immutable ? "public, max-age=31536000, immutable" : "public, max-age=3600",
10020
+ ...asset.contentType === "image/svg+xml" ? { "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" } : {}
10021
+ },
10022
+ body
10023
+ });
10024
+ }
10025
+ if (logoAsset && logoBytes) files.set(logoAsset.path, {
10026
+ headers: {
10027
+ "content-type": logoAsset.contentType,
10028
+ "cache-control": "public, max-age=3600",
10029
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox"
10030
+ },
10031
+ body: logoBytes
10032
+ });
10033
+ return {
10034
+ pages,
10035
+ theme: config.theme ?? "studio",
10036
+ name: config.name === void 0 ? "Mostra" : config.name,
10037
+ defaultAppearance: config.default ?? "system",
10038
+ asset: (path) => files.get(path)
10039
+ };
10040
+ }
10041
+ let standard;
10042
+ /** The pages of a server that configured nothing: Studio, named Mostra. Made once. */
10043
+ function defaultPages() {
10044
+ standard ??= serverPages();
10045
+ return standard;
10046
+ }
10047
+ /**
10048
+ * A page for a refused navigation, in the server's theme: no script, nothing of the artifact, and
10049
+ * the diagnostic's code in small print, for whoever the person asks for help.
10050
+ */
10051
+ function refusalDocument(pages, words) {
10052
+ const said = PAGE_REFUSALS[words.code] ?? words;
10053
+ return pages.render({
10054
+ kind: "notice",
10055
+ tone: "problem",
10056
+ title: said.title,
10057
+ body: html`${said.detail ? html`<p>${said.detail}</p>` : ""}<p class="m-fine"><code translate="no">${words.code}</code></p>`
10058
+ });
10059
+ }
10060
+ /**
10061
+ * What a refused navigation says to a person who opened a link (UX-01: the same words the shell
10062
+ * uses for these refusals, `packages/shell/src/messages.ts`, kept equal by a test). Neutral, naming
10063
+ * nobody (FAILURE_MODEL §11.3).
10064
+ */
10065
+ const PAGE_REFUSALS = {
10066
+ MOSTRA_HYGIENE_TOKEN_REVOKED: {
10067
+ title: "This link was revoked or has expired",
10068
+ detail: "Ask whoever shared it for a new link."
10069
+ },
10070
+ MOSTRA_HYGIENE_SESSION_MISSING: {
10071
+ title: "Open the full link to view this artifact",
10072
+ detail: "This page needs the link you were given, including everything after the #."
10073
+ },
10074
+ MOSTRA_HYGIENE_TOKEN_INVALID: {
10075
+ title: "This link doesn't work",
10076
+ detail: "It may be incomplete or belong to another artifact. Copy the whole link again."
10077
+ },
10078
+ MOSTRA_REMOTE_UNDER_REVIEW: {
10079
+ title: "This page is under review",
10080
+ detail: "The people who run this server are looking at it. Try again later."
10081
+ },
10082
+ MOSTRA_REMOTE_HOME_SUSPENDED: {
10083
+ title: "This page isn't available",
10084
+ detail: "The account that shared it is suspended on this server."
10085
+ },
10086
+ MOSTRA_REMOTE_HOME_MOVING: {
10087
+ title: "This page is moving",
10088
+ detail: "Try again in a minute."
10089
+ },
10090
+ MOSTRA_REMOTE_LIMIT_REACHED: {
10091
+ title: "This page isn't available right now",
10092
+ detail: "Try again later."
10093
+ },
10094
+ MOSTRA_HYGIENE_HOST_REFUSED: {
10095
+ title: "There's no page here",
10096
+ detail: "Check the link you were given: this address doesn't serve one."
10097
+ }
10098
+ };
10099
+ /** The `Content-Security-Policy` of a theme page that `frameAncestors` may frame. */
10100
+ function themePageCsp(pages, frameAncestors = "'none'", formAction) {
10101
+ return [pages.csp.replace("frame-ancestors 'none'", `frame-ancestors ${frameAncestors}`), ...formAction ? [`form-action ${formAction}`] : ["form-action 'none'"]].join("; ");
10102
+ }
10103
+ //#endregion
9955
10104
  //#region src/gateway/http.ts
9956
10105
  /** The longest JSON body a gateway endpoint reads. */
9957
10106
  const MAX_JSON_BODY = 65536;
@@ -10001,14 +10150,6 @@ function wantsDocument(headers) {
10001
10150
  if (dest !== null) return dest === "document" || dest === "iframe" || dest === "frame";
10002
10151
  return (headers.get("accept") ?? "").includes("text/html");
10003
10152
  }
10004
- /** Escapes text for HTML. */
10005
- function escapeHtml(text) {
10006
- return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
10007
- }
10008
- /** A plain page for a refused navigation: no scripts, no external resources. */
10009
- function refusalPage(diagnostic) {
10010
- 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>`;
10011
- }
10012
10153
  /** The response for a refusal: the diagnostic as JSON, or a plain page for a navigation. */
10013
10154
  function refusalResponse(refused, options) {
10014
10155
  const headers = {
@@ -10020,13 +10161,14 @@ function refusalResponse(refused, options) {
10020
10161
  const head = options.method === "HEAD";
10021
10162
  if (options.document) {
10022
10163
  headers["content-type"] = "text/html; charset=utf-8";
10023
- headers["content-security-policy"] = [
10024
- "default-src 'none'",
10025
- "style-src 'unsafe-inline'",
10026
- `frame-ancestors ${options.frameAncestors ?? "'none'"}`,
10027
- "base-uri 'none'"
10028
- ].join("; ");
10029
- return new Response(head ? null : refusalPage(refused.diagnostic), {
10164
+ const pages = options.pages ?? defaultPages().pages;
10165
+ headers["content-security-policy"] = themePageCsp(pages, options.frameAncestors ?? "'none'");
10166
+ const page = refusalDocument(pages, {
10167
+ title: refused.diagnostic.message,
10168
+ detail: refused.diagnostic.hint,
10169
+ code: refused.diagnostic.code
10170
+ });
10171
+ return new Response(head ? null : page, {
10030
10172
  status: refused.status,
10031
10173
  headers
10032
10174
  });
@@ -11803,10 +11945,12 @@ function refuse(checks, refused, request) {
11803
11945
  path: request.path,
11804
11946
  origin: checks.policy().origin
11805
11947
  });
11948
+ const pages = checks.pages?.();
11806
11949
  return refusalResponse(refused, {
11807
11950
  document: request.document,
11808
11951
  method: request.method,
11809
- frameAncestors: checks.frameAncestors()
11952
+ frameAncestors: checks.frameAncestors(),
11953
+ ...pages ? { pages } : {}
11810
11954
  });
11811
11955
  }
11812
11956
  const NOT_SERVED_YET = (method, path) => refusal("MOSTRA_HYGIENE_NOT_SERVED", `This Mostra release doesn't serve ${method} ${path} yet.`, 501);
@@ -11976,9 +12120,15 @@ function lingerAfterRefusal(socket) {
11976
12120
  * opened again. The page runs nothing and can't be framed.
11977
12121
  */
11978
12122
  function headersTooLarge(socket) {
11979
- writeRaw(socket, refusal("MOSTRA_HYGIENE_HEADERS_TOO_LARGE", "This browser sent more cookies than any page here sets."), {
11980
- 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>`,
11981
- headers: ["clear-site-data: \"cookies\"", "content-security-policy: default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'"]
12123
+ const refused = refusal("MOSTRA_HYGIENE_HEADERS_TOO_LARGE", "This browser sent more cookies than any page here sets.");
12124
+ const pages = defaultPages().pages;
12125
+ writeRaw(socket, refused, {
12126
+ html: refusalDocument(pages, {
12127
+ title: "This browser sent more cookies than Mostra accepts",
12128
+ detail: "A page on this machine filled them. They have been cleared: open your link again.",
12129
+ code: "MOSTRA_HYGIENE_HEADERS_TOO_LARGE"
12130
+ }),
12131
+ headers: ["clear-site-data: \"cookies\"", `content-security-policy: ${themePageCsp(pages)}`]
11982
12132
  });
11983
12133
  }
11984
12134
  /**
@@ -12776,6 +12926,25 @@ function laterArtifactRoutes(served, acting, ticket) {
12776
12926
  }
12777
12927
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
12778
12928
  function createGateway(options) {
12929
+ const serverPages = options.pages ?? defaultPages();
12930
+ const pagesOf = () => serverPages.pages;
12931
+ /**
12932
+ * `GET /_mostra/theme/*`: the files the gateway's own pages load (D171), on every listener, with
12933
+ * no session: they are the same public files for everyone and carry nothing of an artifact.
12934
+ */
12935
+ const themeAsset = (checks) => (context) => {
12936
+ const url = new URL(context.request.url);
12937
+ const file = serverPages.asset(url.pathname.slice(15));
12938
+ if (!file) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No theme file at this path."), {
12939
+ method: context.request.method,
12940
+ path: url.pathname,
12941
+ document: false
12942
+ });
12943
+ return new Response(context.request.method === "HEAD" ? null : typeof file.body === "string" ? file.body : new Uint8Array(file.body), { headers: {
12944
+ ...BASE_HEADERS,
12945
+ ...file.headers
12946
+ } });
12947
+ };
12779
12948
  const { addressing, capabilities, artifacts, log, interaction } = options;
12780
12949
  const team = options.bus ? createTeamTraffic({
12781
12950
  bus: options.bus,
@@ -12876,7 +13045,8 @@ function createGateway(options) {
12876
13045
  diagnostic: createDiagnostic("MOSTRA_HOME_INTEGRITY", { message: `${number === void 0 ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.` })
12877
13046
  }, {
12878
13047
  document,
12879
- frameAncestors
13048
+ frameAncestors,
13049
+ pages: pagesOf()
12880
13050
  });
12881
13051
  const link = (token) => ({
12882
13052
  url: `${token.shellOrigin}${hosted ? hosted.shellPath(token.artifactId) : `/a/${token.artifactId}`}${token.pinnedVersion !== void 0 ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
@@ -12913,6 +13083,7 @@ function createGateway(options) {
12913
13083
  hosts: way().hosts()
12914
13084
  }),
12915
13085
  log,
13086
+ pages: pagesOf,
12916
13087
  frameAncestors: () => spec.listener === "shell" ? "'none'" : shellOf(way(), spec.group)?.origin() ?? "'none'",
12917
13088
  configure: (app) => {
12918
13089
  if (spec.listener === "shell") mount(app, shellChecks(way), shellRoutes(way, spec.group));
@@ -13141,6 +13312,7 @@ function createGateway(options) {
13141
13312
  log,
13142
13313
  cookieName: () => `mostra-${way().port()}`,
13143
13314
  mode: () => way().by === "hosted" ? "header" : "cookie",
13315
+ pages: pagesOf,
13144
13316
  frameAncestors: () => "'none'",
13145
13317
  artifactOf: (params) => {
13146
13318
  const id = params["artifactId"];
@@ -13469,6 +13641,13 @@ function createGateway(options) {
13469
13641
  auth: "none",
13470
13642
  handler: shellAsset
13471
13643
  },
13644
+ {
13645
+ method: "GET",
13646
+ path: `${THEME_BASE}*`,
13647
+ intent: "read",
13648
+ auth: "none",
13649
+ handler: themeAsset(checks)
13650
+ },
13472
13651
  {
13473
13652
  method: "POST",
13474
13653
  path: "/a/:artifactId/_mostra/session",
@@ -13554,6 +13733,7 @@ function createGateway(options) {
13554
13733
  capabilities,
13555
13734
  log,
13556
13735
  cookieName: () => `mostra-${wayOf().port()}`,
13736
+ pages: pagesOf,
13557
13737
  frameAncestors: () => {
13558
13738
  const way = wayOf();
13559
13739
  if (way.by === "hosted" && hosted?.frameAncestors) return hosted.frameAncestors(artifactId, way.origin() ?? "") || "'none'";
@@ -13802,6 +13982,13 @@ function createGateway(options) {
13802
13982
  auth: "none",
13803
13983
  handler: enter
13804
13984
  },
13985
+ {
13986
+ method: "GET",
13987
+ path: `${THEME_BASE}*`,
13988
+ intent: "read",
13989
+ auth: "none",
13990
+ handler: themeAsset(checks)
13991
+ },
13805
13992
  {
13806
13993
  method: "POST",
13807
13994
  path: "/_mostra/enter",
@@ -13873,6 +14060,7 @@ function createGateway(options) {
13873
14060
  hosts: addressing.hosts(port)
13874
14061
  }),
13875
14062
  log,
14063
+ pages: pagesOf,
13876
14064
  frameAncestors: () => shellOrigin(),
13877
14065
  configure: (app) => mount(app, artifactChecks(artifactId, () => way, void 0), artifactRoutes(artifactId, () => way, void 0)),
13878
14066
  upgrade: socketUpgrade(artifactId, () => way, void 0),
@@ -13950,6 +14138,7 @@ function createGateway(options) {
13950
14138
  hosts: addressing.hosts(shellPort ?? 0)
13951
14139
  }),
13952
14140
  log,
14141
+ pages: pagesOf,
13953
14142
  frameAncestors: () => "'none'",
13954
14143
  configure: (app) => mount(app, shellChecks(() => loopbackShell), shellRoutes(() => loopbackShell, void 0)),
13955
14144
  ...options.traceRequests ? { traceRequests: true } : {}
@@ -23702,6 +23891,6 @@ function sourceDirectory(path) {
23702
23891
  }
23703
23892
  }
23704
23893
  //#endregion
23705
- export { markRunning as A, handler as B, jsonResponse as C, createEphemeralBus as D, createInteraction as E, BINDING_SUBPROTOCOL as F, readFieldCoverage as G, openLedger as H, MAX_FRAME_BYTES as I, coverageMatcher as J, readServerFunctions as K, serveWebSocket as L, markWaiting as M, runState as N, appendRunOutput as O, appendEvent as P, attachInProcess as R, isRefusal as S, openRegistry as T, faultsFrom as U, holdLock as V, noFaults as W, openFileLog as Y, resetOnClose as _, uninstallService as a, BASE_HEADERS as b, resolveHomePath as c, versionIdFor as d, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, markUnknown as j, finishRun as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, readProcess as q, installService as r, platformName as s, runtimeVersion as t, listingDigest as u, Capabilities as v, readJsonObject as w, documentHeaders as x, capabilityKey as y, ProtocolServer as z };
23894
+ export { readProcess as $, themePageCsp as A, appendEvent as B, jsonResponse as C, defaultPages as D, THEME_BASE as E, finishRun as F, ProtocolServer as G, MAX_FRAME_BYTES as H, markRunning as I, openLedger as J, handler as K, markUnknown as L, createInteraction as M, createEphemeralBus as N, refusalDocument as O, appendRunOutput as P, readServerFunctions as Q, markWaiting as R, isRefusal as S, MADE_WITH_HREF as T, serveWebSocket as U, BINDING_SUBPROTOCOL as V, attachInProcess as W, noFaults as X, faultsFrom as Y, readFieldCoverage as Z, resetOnClose as _, uninstallService as a, BASE_HEADERS as b, resolveHomePath as c, versionIdFor as d, coverageMatcher as et, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, openRegistry as j, serverPages as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, holdLock as q, installService as r, platformName as s, runtimeVersion as t, openFileLog as tt, listingDigest as u, Capabilities as v, readJsonObject as w, documentHeaders as x, capabilityKey as y, runState as z };
23706
23895
 
23707
- //# sourceMappingURL=instance-D5gh-sMM.js.map
23896
+ //# sourceMappingURL=instance-CFTw3g-c.js.map