keryx 0.38.2 → 0.39.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.
@@ -12,6 +12,11 @@ export const configServerWeb = {
12
12
  `http://${host}:${port}`,
13
13
  ),
14
14
  apiRoute: await loadFromEnvIfSet("WEB_SERVER_API_ROUTE", "/api"),
15
+ // Optional path (relative to the app's rootDir, or absolute) to a theme
16
+ // stylesheet inlined into every framework-rendered HTML surface: the OAuth
17
+ // authorization page and MCP App shells. Accepts a `.css` file or a
18
+ // `.ts`/`.js` entrypoint that default-exports a CSS string. Empty = no theme.
19
+ theme: await loadFromEnvIfSet("WEB_SERVER_THEME", ""),
15
20
  allowedOrigins: await loadFromEnvIfSet("WEB_SERVER_ALLOWED_ORIGINS", "*"),
16
21
  allowedMethods: await loadFromEnvIfSet(
17
22
  "WEB_SERVER_ALLOWED_METHODS",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.38.2",
3
+ "version": "0.39.0",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -5,7 +5,9 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Authorize Application</title>
7
7
  <style>
8
+ {{> defaultThemeCss}}
8
9
  {{> commonCss}}
10
+ {{> themeCss}}
9
11
  </style>
10
12
  </head>
11
13
  <body>
@@ -1,12 +1,14 @@
1
+ /* Styling for the OAuth authorization page. The --keryx-* design tokens this file
2
+ references are supplied by the framework's shared default theme (DEFAULT_THEME_CSS),
3
+ inlined ahead of this file, and can be overridden via config.server.web.theme. */
1
4
  * {
2
5
  box-sizing: border-box;
3
6
  margin: 0;
4
7
  padding: 0;
5
8
  }
6
9
  body {
7
- font-family:
8
- -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
9
- background: linear-gradient(135deg, #2f5266 0%, #3a6a84 50%, #e14e3a 100%);
10
+ font-family: var(--keryx-font-family);
11
+ background: var(--keryx-bg);
10
12
  display: flex;
11
13
  flex-direction: column;
12
14
  justify-content: center;
@@ -14,8 +16,8 @@ body {
14
16
  min-height: 100vh;
15
17
  }
16
18
  .container {
17
- background: #fff;
18
- border-radius: 12px;
19
+ background: var(--keryx-surface);
20
+ border-radius: var(--keryx-radius);
19
21
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
20
22
  padding: 36px;
21
23
  width: 100%;
@@ -23,7 +25,7 @@ body {
23
25
  }
24
26
  h2 {
25
27
  margin-bottom: 20px;
26
- color: #2f5266;
28
+ color: var(--keryx-color-primary);
27
29
  }
28
30
  .error {
29
31
  background: #fef2f0;
@@ -46,14 +48,14 @@ h2 {
46
48
  cursor: pointer;
47
49
  border-bottom: 2px solid transparent;
48
50
  margin-bottom: -2px;
49
- color: #666;
51
+ color: var(--keryx-color-text-muted);
50
52
  transition:
51
53
  color 0.2s,
52
54
  border-color 0.2s;
53
55
  }
54
56
  .tab.active {
55
- border-bottom-color: #2f5266;
56
- color: #2f5266;
57
+ border-bottom-color: var(--keryx-color-primary);
58
+ color: var(--keryx-color-primary);
57
59
  font-weight: 600;
58
60
  }
59
61
  .form-section {
@@ -66,7 +68,7 @@ label {
66
68
  display: block;
67
69
  margin-bottom: 4px;
68
70
  font-weight: 500;
69
- color: #555;
71
+ color: var(--keryx-color-text);
70
72
  font-size: 14px;
71
73
  }
72
74
  input[type="text"],
@@ -74,7 +76,7 @@ input[type="email"],
74
76
  input[type="password"] {
75
77
  width: 100%;
76
78
  padding: 10px;
77
- border: 1px solid #ddd;
79
+ border: 1px solid var(--keryx-color-border);
78
80
  border-radius: 6px;
79
81
  font-size: 14px;
80
82
  margin-bottom: 12px;
@@ -84,13 +86,14 @@ input[type="password"] {
84
86
  }
85
87
  input:focus {
86
88
  outline: none;
87
- border-color: #2f5266;
88
- box-shadow: 0 0 0 2px rgba(47, 82, 102, 0.2);
89
+ border-color: var(--keryx-color-primary);
90
+ box-shadow: 0 0 0 2px
91
+ color-mix(in srgb, var(--keryx-color-primary) 20%, transparent);
89
92
  }
90
93
  button {
91
94
  width: 100%;
92
95
  padding: 12px;
93
- background: #2f5266;
96
+ background: var(--keryx-color-primary);
94
97
  color: #fff;
95
98
  border: none;
96
99
  border-radius: 6px;
@@ -100,14 +103,14 @@ button {
100
103
  transition: background 0.2s;
101
104
  }
102
105
  button:hover {
103
- background: #3a6a84;
106
+ background: var(--keryx-color-primary-hover);
104
107
  }
105
108
  .checkmark {
106
109
  width: 64px;
107
110
  height: 64px;
108
111
  margin: 0 auto 16px;
109
112
  border-radius: 50%;
110
- background: rgba(47, 82, 102, 0.1);
113
+ background: color-mix(in srgb, var(--keryx-color-primary) 10%, transparent);
111
114
  display: flex;
112
115
  align-items: center;
113
116
  justify-content: center;
@@ -115,14 +118,14 @@ button:hover {
115
118
  .checkmark svg {
116
119
  width: 32px;
117
120
  height: 32px;
118
- stroke: #2f5266;
121
+ stroke: var(--keryx-color-primary);
119
122
  fill: none;
120
123
  stroke-width: 3;
121
124
  stroke-linecap: round;
122
125
  stroke-linejoin: round;
123
126
  }
124
127
  p {
125
- color: #666;
128
+ color: var(--keryx-color-text-muted);
126
129
  font-size: 14px;
127
130
  margin-bottom: 8px;
128
131
  }
@@ -0,0 +1,38 @@
1
+ import { ErrorType, TypedError } from "../classes/TypedError";
2
+
3
+ /**
4
+ * Run `bun build` in a **child process** and return its stdout.
5
+ *
6
+ * A child process is used rather than the in-process `Bun.build` API because once the
7
+ * server has started, Bun has memory-mapped its loaded modules (e.g. zod) and the
8
+ * in-process bundler fails to re-read them ("Unseekable reading file"). A fresh process
9
+ * sidesteps that and is only paid once, at boot.
10
+ *
11
+ * @param args - Arguments passed to `bun build` (entrypoint plus flags).
12
+ * @param label - Human description of what is being built, used in the error message.
13
+ * @returns The build's stdout (the bundled output).
14
+ * @throws {TypedError} When the build exits non-zero or produces no output (includes stderr).
15
+ */
16
+ export async function spawnBunBuild(
17
+ args: string[],
18
+ label: string,
19
+ ): Promise<string> {
20
+ const proc = Bun.spawn([process.execPath, "build", ...args], {
21
+ stdout: "pipe",
22
+ stderr: "pipe",
23
+ });
24
+ const [output, stderr, exitCode] = await Promise.all([
25
+ new Response(proc.stdout).text(),
26
+ new Response(proc.stderr).text(),
27
+ proc.exited,
28
+ ]);
29
+
30
+ if (exitCode !== 0 || output.trim().length === 0) {
31
+ throw new TypedError({
32
+ message: `Failed to build ${label}:\n${stderr || "no output"}`,
33
+ type: ErrorType.SERVER_INITIALIZATION,
34
+ });
35
+ }
36
+
37
+ return output;
38
+ }
@@ -2,6 +2,8 @@ import { fileURLToPath } from "node:url";
2
2
  import { api, logger } from "../api";
3
3
  import type { Action, McpUiConfig } from "../classes/Action";
4
4
  import { ErrorType, TypedError } from "../classes/TypedError";
5
+ import { spawnBunBuild } from "./bunBuild";
6
+ import { DEFAULT_THEME_CSS, resolveThemeCss } from "./theme";
5
7
 
6
8
  /**
7
9
  * Default self-contained HTML shell for an MCP App declared with only `mcp.ui.client`.
@@ -14,8 +16,10 @@ export const DEFAULT_MCP_APP_SHELL = `<!doctype html>
14
16
  <meta charset="utf-8" />
15
17
  <meta name="viewport" content="width=device-width, initial-scale=1" />
16
18
  <style>
17
- :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
19
+ ${DEFAULT_THEME_CSS}
20
+ :root { color-scheme: light dark; font-family: var(--keryx-font-family); }
18
21
  body { margin: 0; padding: 16px; }
22
+ /* MCP_APP_THEME */
19
23
  </style>
20
24
  </head>
21
25
  <body>
@@ -27,6 +31,8 @@ export const DEFAULT_MCP_APP_SHELL = `<!doctype html>
27
31
 
28
32
  /** Placeholder comment a shell may use to mark where the bundled client is inlined. */
29
33
  const COMMENT_PLACEHOLDER = "/* MCP_APP_CLIENT */";
34
+ /** Placeholder comment a shell may use to mark where the shared theme CSS is inlined. */
35
+ const THEME_PLACEHOLDER = "/* MCP_APP_THEME */";
30
36
  /** Matches an empty `<script type="module">` tag (the preferred, declarative injection point). */
31
37
  const EMPTY_MODULE_SCRIPT = /<script\s+type=["']module["']>\s*<\/script>/;
32
38
 
@@ -36,11 +42,6 @@ const resolvedUiHtml = new Map<Action, string>();
36
42
  /**
37
43
  * Bundle a browser entrypoint into a single minified ESM string.
38
44
  *
39
- * Runs `bun build` in a **child process** rather than the in-process `Bun.build` API:
40
- * once the server has started, Bun has memory-mapped its loaded modules (e.g. zod), and
41
- * the in-process bundler fails to re-read them ("Unseekable reading file"). A fresh
42
- * process sidesteps that and is only paid once, at boot.
43
- *
44
45
  * @param client - Path or `file:` URL to the browser entrypoint (`.ts`/`.tsx`/`.js`).
45
46
  * @returns The minified, bundled client script.
46
47
  * @throws {TypedError} When the bundle fails (message includes the bundler's stderr).
@@ -55,31 +56,10 @@ export async function bundleMcpAppClient(
55
56
  ? fileURLToPath(new URL(client))
56
57
  : client;
57
58
 
58
- const proc = Bun.spawn(
59
- [
60
- process.execPath,
61
- "build",
62
- entrypoint,
63
- "--target=browser",
64
- "--format=esm",
65
- "--minify",
66
- ],
67
- { stdout: "pipe", stderr: "pipe" },
59
+ return spawnBunBuild(
60
+ [entrypoint, "--target=browser", "--format=esm", "--minify"],
61
+ `MCP App client "${entrypoint}"`,
68
62
  );
69
- const [script, stderr, exitCode] = await Promise.all([
70
- new Response(proc.stdout).text(),
71
- new Response(proc.stderr).text(),
72
- proc.exited,
73
- ]);
74
-
75
- if (exitCode !== 0 || script.trim().length === 0) {
76
- throw new TypedError({
77
- message: `Failed to bundle MCP App client "${entrypoint}":\n${stderr || "no output"}`,
78
- type: ErrorType.SERVER_INITIALIZATION,
79
- });
80
- }
81
-
82
- return script;
83
63
  }
84
64
 
85
65
  /**
@@ -106,22 +86,51 @@ function injectClientScript(shell: string, script: string): string {
106
86
  return `${shell}${scriptTag}`;
107
87
  }
108
88
 
89
+ /**
90
+ * Inline the shared theme CSS into an HTML shell. Prefers a `MCP_APP_THEME` placeholder
91
+ * comment (so custom shells position the theme precisely), then inserts a `<style>` block
92
+ * before `</head>`, then before `</body>`, and finally appends as a last resort. When the
93
+ * theme is empty and no placeholder is present, the shell is returned unchanged.
94
+ *
95
+ * Uses a replacer function so `$`-sequences in the CSS are inserted literally.
96
+ */
97
+ export function injectThemeCss(shell: string, themeCss: string): string {
98
+ if (shell.includes(THEME_PLACEHOLDER)) {
99
+ return shell.replace(THEME_PLACEHOLDER, () => themeCss);
100
+ }
101
+ if (!themeCss) return shell;
102
+ const styleTag = `<style>${themeCss}</style>`;
103
+ if (shell.includes("</head>")) {
104
+ return shell.replace("</head>", () => `${styleTag}</head>`);
105
+ }
106
+ if (shell.includes("</body>")) {
107
+ return shell.replace("</body>", () => `${styleTag}</body>`);
108
+ }
109
+ return `${shell}${styleTag}`;
110
+ }
111
+
109
112
  /**
110
113
  * Compute the served HTML for an MCP App's `mcp.ui` config.
111
114
  *
112
115
  * - With `client`: bundles it and inlines the result into `html` (or {@link DEFAULT_MCP_APP_SHELL}).
113
- * - With only `html`: returns it verbatim.
116
+ * - With only `html`: returns it as-is.
117
+ *
118
+ * In both cases the app's shared theme CSS ({@link resolveThemeCss}) is inlined — into the
119
+ * `MCP_APP_THEME` placeholder when present, otherwise as a `<style>` block. When no theme is
120
+ * configured, custom `html` shells are returned byte-for-byte verbatim.
114
121
  *
115
122
  * @param ui - The action's `mcp.ui` config.
116
123
  * @returns The self-contained HTML to serve as the `ui://` resource.
117
124
  * @throws {TypedError} When neither `client` nor `html` is set, or bundling fails.
118
125
  */
119
126
  export async function resolveMcpAppHtml(ui: McpUiConfig): Promise<string> {
127
+ const themeCss = await resolveThemeCss();
120
128
  if (ui.client) {
121
129
  const script = await bundleMcpAppClient(ui.client);
122
- return injectClientScript(ui.html ?? DEFAULT_MCP_APP_SHELL, script);
130
+ const shell = injectClientScript(ui.html ?? DEFAULT_MCP_APP_SHELL, script);
131
+ return injectThemeCss(shell, themeCss);
123
132
  }
124
- if (ui.html !== undefined) return ui.html;
133
+ if (ui.html !== undefined) return injectThemeCss(ui.html, themeCss);
125
134
  throw new TypedError({
126
135
  message: "mcp.ui requires either `client` or `html` to be set",
127
136
  type: ErrorType.ACTION_VALIDATION,
@@ -2,6 +2,7 @@ import Mustache from "mustache";
2
2
  import type { z } from "zod";
3
3
  import type { Action } from "../classes/Action";
4
4
  import { escapeHtml } from "./oauth";
5
+ import { DEFAULT_THEME_CSS, resolveThemeCss } from "./theme";
5
6
  import { isSecret } from "./zodMixins";
6
7
 
7
8
  export type FormField = {
@@ -17,6 +18,8 @@ export type OAuthTemplates = {
17
18
  authTemplate: string;
18
19
  commonCss: string;
19
20
  lionSvg: string;
21
+ /** App's shared theme CSS, inlined after {@link commonCss} so its overrides win. */
22
+ themeCss: string;
20
23
  };
21
24
 
22
25
  const frameworkTemplatesDir = import.meta.dir + "/../templates";
@@ -51,12 +54,13 @@ export async function loadOAuthTemplates(
51
54
  rootDir: string,
52
55
  packageDir: string,
53
56
  ): Promise<OAuthTemplates> {
54
- const [authTemplate, commonCss, lionSvg] = await Promise.all([
57
+ const [authTemplate, commonCss, lionSvg, themeCss] = await Promise.all([
55
58
  resolveTemplate("oauth-authorize.html", rootDir, packageDir),
56
59
  resolveTemplate("oauth-common.css", rootDir, packageDir),
57
60
  resolveTemplate("lion.svg", rootDir, packageDir),
61
+ resolveThemeCss(),
58
62
  ]);
59
- return { authTemplate, commonCss, lionSvg };
63
+ return { authTemplate, commonCss, lionSvg, themeCss };
60
64
  }
61
65
 
62
66
  /**
@@ -201,7 +205,12 @@ export function renderAuthPage(
201
205
  signinFieldsHtml,
202
206
  signupFieldsHtml,
203
207
  },
204
- { commonCss: templates.commonCss, lionSvg: templates.lionSvg },
208
+ {
209
+ defaultThemeCss: DEFAULT_THEME_CSS,
210
+ commonCss: templates.commonCss,
211
+ lionSvg: templates.lionSvg,
212
+ themeCss: templates.themeCss,
213
+ },
205
214
  );
206
215
 
207
216
  return new Response(html, {
package/util/theme.ts ADDED
@@ -0,0 +1,136 @@
1
+ import path from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { api } from "../api";
4
+ import { ErrorType, TypedError } from "../classes/TypedError";
5
+ import { config } from "../config";
6
+ import { spawnBunBuild } from "./bunBuild";
7
+
8
+ /**
9
+ * The framework's default theme: the shared `--keryx-*` design tokens (palette, fonts,
10
+ * radius) that every framework-rendered HTML surface inlines as its baseline. It is the
11
+ * single source of truth for default branding — the OAuth authorization page and MCP App
12
+ * shells both include it, and a user theme ({@link resolveThemeCss}) is inlined *after* it
13
+ * so any token it redeclares wins by cascade order.
14
+ *
15
+ * This block defines tokens only (no layout/chrome), so surfaces share a vocabulary without
16
+ * sharing page structure: the OAuth page styles itself with these tokens, and MCP App widgets
17
+ * may reference them (e.g. `color: var(--keryx-color-primary)`).
18
+ */
19
+ export const DEFAULT_THEME_CSS = `:root {
20
+ --keryx-font-family:
21
+ -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
22
+ --keryx-color-primary: #2f5266;
23
+ --keryx-color-primary-hover: #3a6a84;
24
+ --keryx-color-accent: #e14e3a;
25
+ --keryx-bg: linear-gradient(
26
+ 135deg,
27
+ var(--keryx-color-primary) 0%,
28
+ var(--keryx-color-primary-hover) 50%,
29
+ var(--keryx-color-accent) 100%
30
+ );
31
+ --keryx-surface: #fff;
32
+ --keryx-color-text: #555;
33
+ --keryx-color-text-muted: #666;
34
+ --keryx-color-border: #ddd;
35
+ --keryx-radius: 12px;
36
+ }`;
37
+
38
+ /** Extensions bundled through Bun's CSS pipeline (`bun build`). */
39
+ const CSS_EXTENSIONS = new Set([".css"]);
40
+ /** Extensions dynamically imported for a default-exported CSS string. */
41
+ const MODULE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs"]);
42
+ /** Preprocessor extensions Bun cannot compile natively; surfaced with a targeted error. */
43
+ const PREPROCESSOR_EXTENSIONS = new Set([".scss", ".sass", ".less", ".styl"]);
44
+
45
+ /**
46
+ * Memoized promise for the resolved theme CSS. Resolved once on first access (by whichever
47
+ * of the OAuth or MCP initializers runs first) and reused for the process lifetime, so the
48
+ * theme source is read/compiled exactly once regardless of which surfaces are enabled.
49
+ */
50
+ let themePromise: Promise<string> | undefined;
51
+
52
+ /**
53
+ * Resolve the app's shared theme CSS, compiling the configured source once and caching the
54
+ * result. The returned string is inlined verbatim into every framework-rendered HTML surface
55
+ * (the OAuth authorization page and MCP App shells).
56
+ *
57
+ * Dispatch by extension of {@link config.server.web.theme}:
58
+ * - `.css` — bundled through `bun build` (resolves `@import`, minifies).
59
+ * - `.ts`/`.tsx`/`.js`/`.jsx`/`.mjs` — dynamically imported; the module's `default` export
60
+ * must be a CSS `string` (lets a theme compute CSS from design tokens).
61
+ * - `.scss`/`.sass`/`.less`/`.styl` — not compiled natively by Bun; a {@link TypedError}
62
+ * directs you to precompile to `.css` or use a `.ts` entrypoint that returns a CSS string.
63
+ *
64
+ * @param themePath - Path to the theme source (defaults to `config.server.web.theme`). Empty
65
+ * returns `""` (no theme). Explicit for testability.
66
+ * @param rootDir - Base directory relative paths resolve against (defaults to `api.rootDir`).
67
+ * @returns The theme CSS string, or `""` when no theme is configured.
68
+ * @throws {TypedError} When the path is missing, the extension is unsupported, a `.css`
69
+ * bundle fails, or a module entrypoint does not default-export a string.
70
+ */
71
+ export function resolveThemeCss(
72
+ themePath: string = config.server.web.theme,
73
+ rootDir: string = api.rootDir,
74
+ ): Promise<string> {
75
+ if (!themePromise) themePromise = compileTheme(themePath, rootDir);
76
+ return themePromise;
77
+ }
78
+
79
+ async function compileTheme(
80
+ themePath: string,
81
+ rootDir: string,
82
+ ): Promise<string> {
83
+ if (!themePath) return "";
84
+
85
+ const absolutePath = path.isAbsolute(themePath)
86
+ ? themePath
87
+ : path.join(rootDir, themePath);
88
+
89
+ if (!(await Bun.file(absolutePath).exists())) {
90
+ throw new TypedError({
91
+ message: `Theme CSS not found: "${absolutePath}" (config.server.web.theme)`,
92
+ type: ErrorType.SERVER_INITIALIZATION,
93
+ });
94
+ }
95
+
96
+ const extension = path.extname(absolutePath).toLowerCase();
97
+
98
+ if (CSS_EXTENSIONS.has(extension)) {
99
+ return spawnBunBuild(
100
+ [absolutePath, "--minify"],
101
+ `theme CSS "${absolutePath}"`,
102
+ );
103
+ }
104
+
105
+ if (MODULE_EXTENSIONS.has(extension)) {
106
+ const module = await import(pathToFileURL(absolutePath).href);
107
+ const css = module.default;
108
+ if (typeof css !== "string") {
109
+ throw new TypedError({
110
+ message: `Theme module "${absolutePath}" must default-export a CSS string (got ${typeof css})`,
111
+ type: ErrorType.SERVER_INITIALIZATION,
112
+ });
113
+ }
114
+ return css;
115
+ }
116
+
117
+ if (PREPROCESSOR_EXTENSIONS.has(extension)) {
118
+ throw new TypedError({
119
+ message: `Theme "${absolutePath}": Bun cannot compile "${extension}" natively. Precompile it to a .css file, or use a .ts entrypoint that default-exports a CSS string.`,
120
+ type: ErrorType.SERVER_INITIALIZATION,
121
+ });
122
+ }
123
+
124
+ throw new TypedError({
125
+ message: `Theme "${absolutePath}": unsupported extension "${extension}". Use a .css file or a .ts/.js entrypoint that default-exports a CSS string.`,
126
+ type: ErrorType.SERVER_INITIALIZATION,
127
+ });
128
+ }
129
+
130
+ /**
131
+ * Clear the memoized theme so the next {@link resolveThemeCss} call recompiles. Intended for
132
+ * tests that exercise multiple theme sources within one process.
133
+ */
134
+ export function resetThemeCache(): void {
135
+ themePromise = undefined;
136
+ }