local-llm-gateway 0.1.0 → 0.2.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 (36) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +16 -8
  3. package/cli/dist/api/client.js +4 -0
  4. package/cli/dist/commands/open.js +40 -0
  5. package/cli/dist/index.js +6 -0
  6. package/cli/dist/key-diagnosis.js +7 -7
  7. package/cli/dist/repl.js +11 -1
  8. package/dist/src/api/endpoints.js +39 -1
  9. package/dist/src/api/openapi.js +9 -2
  10. package/dist/src/api/schemas.js +2 -0
  11. package/dist/src/app.js +27 -2
  12. package/dist/src/config.js +3 -0
  13. package/dist/src/lib/web-root.js +16 -0
  14. package/dist/src/plugins/auth.js +31 -8
  15. package/dist/src/plugins/metrics.js +1 -1
  16. package/dist/src/plugins/web-guard.js +37 -0
  17. package/dist/src/routes/web-page.js +42 -0
  18. package/dist/src/routes/web-session.js +52 -0
  19. package/dist/src/server.js +0 -0
  20. package/dist/src/services/web-session.service.js +50 -0
  21. package/dist/src/storage/postgres/index.js +2 -0
  22. package/dist/src/storage/postgres/schema.js +19 -0
  23. package/dist/src/storage/postgres/web-sessions.js +50 -0
  24. package/dist/src/storage/sqlite/index.js +2 -0
  25. package/dist/src/storage/sqlite/schema.js +18 -0
  26. package/dist/src/storage/sqlite/web-sessions.js +50 -0
  27. package/dist/web/assets/index-C03RJbF2.js +17 -0
  28. package/dist/web/assets/index-CDL8Tl5X.css +1 -0
  29. package/dist/web/index.html +14 -0
  30. package/drizzle/0003_pale_spectrum.sql +24 -0
  31. package/drizzle/meta/0003_snapshot.json +735 -0
  32. package/drizzle/meta/_journal.json +7 -0
  33. package/drizzle/sqlite/0001_blushing_jack_murdock.sql +24 -0
  34. package/drizzle/sqlite/meta/0001_snapshot.json +698 -0
  35. package/drizzle/sqlite/meta/_journal.json +7 -0
  36. package/package.json +22 -9
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-24)
4
+
5
+ - **Web chat.** `llm open` opens the assistant in your browser at `http://localhost:3000`,
6
+ already signed in: conversations, streaming answers with Stop, rename, delete, a model
7
+ picker, a Back up button, and "Branch from here" on any message. Problems show as a plain
8
+ banner with what to do. Light and dark mode.
9
+ - Browser sign-in is a one-time link (60 seconds, works once) exchanged for an HttpOnly,
10
+ SameSite=Strict session cookie. Other websites can't use it: the gateway checks the Host
11
+ and Origin of every cookie request, and the page runs under a strict Content-Security-
12
+ Policy. Model answers are shown as text, never as HTML. API keys work as before.
13
+ - The gateway waits up to a second for Redis at startup, so rate limits apply from the
14
+ first request (server mode).
15
+
16
+ ## 0.1.1 (2026-11-20)
17
+
18
+ - `npx local-llm-gateway` now starts the assistant (0.1.0 said "could not determine
19
+ executable to run"). Installing also adds a `local-llm-gateway` command, the same as
20
+ `llm-gateway`.
21
+ - `llm` commands typed into the chat (for example `llm profile use local`) are no longer
22
+ sent to the assistant; the chat says to type `/exit` first.
23
+ - Messages about a rejected key name the mode in plain words ("the single-user assistant")
24
+ instead of developer commands.
25
+ - Metrics use `@prometheus-io/client`, the new name of `prom-client`, so installing no longer
26
+ prints a deprecation warning. Metric names and output are unchanged.
27
+ - Built commands stay executable after a clean build (affected development links only).
28
+
29
+ ## 0.1.0 (2026-11-20)
30
+
31
+ First release: the gateway and the `llm` terminal app in one package. `llm start` runs the
32
+ assistant with no setup (single-user mode, SQLite); `llm chat`, `llm doctor`, `llm backup`,
33
+ `llm restore`. Server mode (Postgres, Redis) by environment variables.
package/README.md CHANGED
@@ -13,22 +13,29 @@ You need **Node.js 22 or newer** and **Ollama**. No Docker, no database to set u
13
13
  ```bash
14
14
  # 1. Start Ollama: open the Ollama app (or run `ollama serve` in its own window)
15
15
 
16
- # 2. The assistant
17
- git clone https://github.com/japp47/local-llm-gateway.git && cd local-llm-gateway
18
- npm ci && npm run build
19
- npm start
16
+ # 2. Install and start the assistant
17
+ npm install -g local-llm-gateway
18
+ llm start
20
19
  ```
21
20
 
22
21
  On first start it creates its data folder, picks a model for your memory size, and makes
23
22
  a key for the terminal app. If no model is downloaded yet, the log tells you which one to
24
- get, for example `ollama pull qwen3:8b`.
23
+ get, for example `ollama pull qwen3:8b`. `llm start` keeps running in that window; Ctrl+C
24
+ stops it.
25
25
 
26
26
  ```bash
27
- # 3. The terminal app, in a second window
28
- cd cli && npm ci && npm run build && npm install -g .
27
+ # 3. In a second window: chat in your browser...
28
+ llm open
29
+ # ...or in the terminal
29
30
  llm chat "hello"
30
31
  ```
31
32
 
33
+ `llm open` opens the chat page at `http://localhost:3000`, already signed in. Only your
34
+ browser on this computer can use that sign-in: other websites can't.
35
+
36
+ To try it without installing: `npx local-llm-gateway` starts the assistant, and
37
+ `npx -p local-llm-gateway llm chat "hello"` chats from a second window.
38
+
32
39
  No key to copy: `llm` finds the one the assistant made. If anything doesn't work:
33
40
 
34
41
  ```bash
@@ -42,7 +49,8 @@ fix whatever is wrong.
42
49
 
43
50
  | Command | What it does |
44
51
  | --- | --- |
45
- | `llm chat` | Talk (interactive). `llm chat "question"` asks once |
52
+ | `llm open` | Chat in your browser (opens already signed in) |
53
+ | `llm chat` | Talk in the terminal. `llm chat "question"` asks once |
46
54
  | `llm ls`, `llm show <id>`, `llm resume <id>` | Your conversations |
47
55
  | `llm fork <id>` | Try another way from an earlier answer |
48
56
  | `llm models` | Downloaded models; `*` marks the one in use |
@@ -85,6 +85,10 @@ export class ApiClient {
85
85
  me() {
86
86
  return this.json('GET', '/v1/me');
87
87
  }
88
+ /** A one-time code that signs the web page in (60 seconds, works once). API key only. */
89
+ webCode() {
90
+ return this.json('POST', '/v1/web/codes');
91
+ }
88
92
  /** Asks the gateway to write a checked backup into its data folder. Single-user mode. */
89
93
  backup() {
90
94
  return this.json('POST', '/v1/backup');
@@ -0,0 +1,40 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { loadConfig } from '../config.js';
3
+ import { out } from '../format.js';
4
+ import { getClient } from './shared.js';
5
+ /** How to open a URL in the default browser on this system. */
6
+ export function browserCommand(url, platform = process.platform) {
7
+ if (platform === 'darwin')
8
+ return ['open', [url]];
9
+ if (platform === 'win32')
10
+ return ['cmd', ['/c', 'start', '""', url]];
11
+ return ['xdg-open', [url]];
12
+ }
13
+ /**
14
+ * Opens the web chat, already signed in: asks the gateway (with this CLI's key) for a
15
+ * one-time code and opens `<gateway>/#code=...`. The code sits after `#`, so it never
16
+ * reaches a server log; the page exchanges it once for a session cookie.
17
+ */
18
+ export async function openCommand(opts) {
19
+ const { baseUrl } = loadConfig();
20
+ const { code } = await getClient().webCode();
21
+ const url = `${baseUrl}/#code=${code}`;
22
+ if (!opts.print) {
23
+ const [cmd, args] = browserCommand(url);
24
+ const opened = await new Promise((done) => {
25
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
26
+ child.on('error', () => done(false));
27
+ child.on('spawn', () => {
28
+ child.unref();
29
+ done(true);
30
+ });
31
+ });
32
+ if (opened) {
33
+ console.log(`Opening the assistant in your browser: ${baseUrl}`);
34
+ return;
35
+ }
36
+ }
37
+ console.log('Open this link to sign in (it works once, within 60 seconds):');
38
+ console.log(` ${url}`);
39
+ console.log(out.dim('Then the page stays signed in for 30 days of use. To sign in again later: llm open'));
40
+ }
package/cli/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { configPathCommand, configSetCommand, configShowCommand, modelsCommand,
6
6
  import { backupCommand, restoreCommand } from './commands/backup.js';
7
7
  import { doctorCommand } from './commands/doctor.js';
8
8
  import { startCommand } from './commands/start.js';
9
+ import { openCommand } from './commands/open.js';
9
10
  import { CliError } from './errors.js';
10
11
  import { describeErrorFully } from './key-diagnosis.js';
11
12
  import { errc } from './format.js';
@@ -78,6 +79,11 @@ program
78
79
  .option('--recent <n>', 'recent generations to list', '5')
79
80
  .option('--json', 'machine-readable output')
80
81
  .action(wrap(statsCommand));
82
+ program
83
+ .command('open')
84
+ .description('open the web chat in your browser, already signed in')
85
+ .option('--print', "print the sign-in link instead of opening the browser")
86
+ .action(wrap(openCommand));
81
87
  program
82
88
  .command('start')
83
89
  .description('start the assistant in this window (Ctrl+C stops it)')
@@ -1,8 +1,8 @@
1
1
  // Explains a rejected API key in terms of what is actually running.
2
2
  //
3
- // The usual cause on one machine: single-user mode (npm run dev:single, SQLite) and server
4
- // mode (npm run dev, Postgres) both listen on localhost:3000 but have separate databases, so
5
- // a key made for one is unknown to the other. We ask the gateway which mode it runs in, and
3
+ // The usual cause on one machine: single-user mode (SQLite) and server mode (Postgres) both
4
+ // listen on localhost:3000 but have separate databases, so a key made for one is unknown
5
+ // to the other. We ask the gateway which mode it runs in, and
6
6
  // try the other keys saved for this same URL to name the profile that works.
7
7
  //
8
8
  // Safety rule kept: a saved key is only ever sent to the URL it was saved for.
@@ -11,8 +11,8 @@ import { listProfiles, loadConfig, sameGateway } from './config.js';
11
11
  import { describeError } from './errors.js';
12
12
  import { localCredentialsPath, readLocalCredentials, sameLocalGateway, } from './local-credentials.js';
13
13
  const MODE_LABEL = {
14
- single: 'the single-user gateway (npm run dev:single, SQLite)',
15
- server: 'the server-mode gateway (npm run dev, Postgres)',
14
+ single: 'the single-user assistant (SQLite)',
15
+ server: 'the server-mode gateway (Postgres)',
16
16
  };
17
17
  /** Older gateways don't report a mode; that is fine, the advice is just less specific. */
18
18
  export async function gatewayMode(baseUrl, fetchImpl = fetch, timeoutMs = 2000) {
@@ -87,10 +87,10 @@ export async function explainRejectedKey(input) {
87
87
  : "→ Use the gateway's own key: llm profile add local --local then llm profile use local");
88
88
  }
89
89
  else if (mode === 'single') {
90
- lines.push('→ This key is probably for server mode. Start that instead: npm run dev');
90
+ lines.push('→ This key is probably for a server-mode gateway (npm run dev in the repo, or llm start --env-file .env). Start that instead, or use a profile for this assistant.');
91
91
  }
92
92
  else if (mode === 'server') {
93
- lines.push('→ If you meant the single-user gateway, start it instead: npm run dev:single', ' Otherwise make a key on the server: npm run key:create -- you@example.com then llm config set apiKey');
93
+ lines.push('→ If you meant the single-user assistant, stop this one and start that: llm start (without DATABASE_URL)', ' Otherwise make a key on the server: npm run key:create -- you@example.com then llm config set apiKey');
94
94
  }
95
95
  else {
96
96
  lines.push('→ Save a valid key with: llm config set apiKey (you will be prompted)');
package/cli/dist/repl.js CHANGED
@@ -31,6 +31,9 @@ export function printSummary(res, quiet) {
31
31
  }
32
32
  return ok;
33
33
  }
34
+ const LLM_SUBCOMMANDS = 'open|profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
35
+ /** `llm profile use local` typed into the chat: a command for the terminal, not a question. */
36
+ export const looksLikeLlmCommand = (line) => new RegExp(`^llm\\s+(${LLM_SUBCOMMANDS})\\b`).test(line);
34
37
  export async function runRepl(opts) {
35
38
  const { client } = opts;
36
39
  let conversationId = opts.conversationId;
@@ -204,12 +207,19 @@ export async function runRepl(opts) {
204
207
  if (!(await slash(line)))
205
208
  break;
206
209
  }
210
+ else if (looksLikeLlmCommand(line)) {
211
+ // Not sent to the model: the user meant their terminal, not the chat.
212
+ console.error(errc.yellow(`That's a terminal command, so it wasn't sent to the assistant.\n → Type /exit, then run: ${line}`));
213
+ }
207
214
  else {
208
215
  await turn(line);
209
216
  }
210
217
  }
211
218
  catch (e) {
212
- console.error(errc.red(await describeErrorFully(e)));
219
+ const text = await describeErrorFully(e);
220
+ console.error(errc.red(text));
221
+ if (/→ .*\bllm /.test(text))
222
+ console.error(errc.dim(' (Those are terminal commands: type /exit first.)'));
213
223
  }
214
224
  rl.setPrompt(promptText());
215
225
  rl.prompt();
@@ -2,7 +2,7 @@ import * as S from './schemas.js';
2
2
  const err = (description) => ({ description, schema: S.ErrorBody });
3
3
  /** Errors any authenticated endpoint can return. */
4
4
  const AUTH_ERRORS = {
5
- 401: err('Missing, unknown or revoked API key (`invalid_api_key`)'),
5
+ 401: err('Missing, unknown or revoked API key (`invalid_api_key`), or an ended web session (`session_expired`)'),
6
6
  429: err('Too many requests for this key (`rate_limited`)'),
7
7
  };
8
8
  const NOT_FOUND = { 404: err('No such conversation for this key (`conversation_not_found`)') };
@@ -28,6 +28,15 @@ export const ENDPOINTS = [
28
28
  summary: 'Prometheus metrics',
29
29
  responses: { 200: { description: 'Prometheus text format', contentType: 'text/plain' } },
30
30
  },
31
+ {
32
+ method: 'get', path: '/', tag: 'web', auth: false,
33
+ summary: 'The web chat page',
34
+ description: 'Served with a strict Content-Security-Policy (only the gateway\'s own scripts and styles). Its files are under /assets/.',
35
+ responses: {
36
+ 200: { description: 'The page', contentType: 'text/html' },
37
+ 404: err("The page hasn't been built (`page_not_built`)"),
38
+ },
39
+ },
31
40
  {
32
41
  method: 'get', path: '/openapi.json', tag: 'health', auth: false,
33
42
  summary: 'This document',
@@ -72,6 +81,35 @@ export const ENDPOINTS = [
72
81
  500: err('The backup could not be written or verified (`backup_failed`)'),
73
82
  },
74
83
  },
84
+ // ---- web sign-in ----
85
+ {
86
+ method: 'post', path: '/v1/web/codes', tag: 'web', auth: true, authBy: ['apiKey'],
87
+ summary: 'Make a one-time sign-in code for the web page (used by `llm open`)',
88
+ description: 'API key only: a signed-in browser cannot make codes. The code works once, for 60 seconds.',
89
+ responses: {
90
+ 201: { description: 'A code', schema: S.WebCode },
91
+ ...AUTH_ERRORS,
92
+ 403: err('Called with a session cookie instead of an API key (`key_required`)'),
93
+ },
94
+ },
95
+ {
96
+ method: 'post', path: '/web/session', tag: 'web', auth: false,
97
+ summary: 'Exchange a sign-in code for a session cookie',
98
+ description: 'Sets an HttpOnly, SameSite=Strict cookie. Refused for a host other than localhost (or `WEB_HOSTS`), ' +
99
+ 'and for an `Origin` other than the gateway itself.',
100
+ body: S.RedeemCodeBody,
101
+ responses: {
102
+ 204: { description: 'Signed in: the session cookie is set' },
103
+ ...INVALID,
104
+ 401: err('The code is unknown, used or expired (`invalid_code`)'),
105
+ 403: err('Wrong host or origin (`forbidden_host`, `bad_origin`)'),
106
+ },
107
+ },
108
+ {
109
+ method: 'delete', path: '/web/session', tag: 'web', auth: true, authBy: ['cookie'],
110
+ summary: 'Sign out: end the session and clear the cookie',
111
+ responses: { 204: { description: 'Signed out' }, 403: err('Wrong host or origin (`forbidden_host`, `bad_origin`)') },
112
+ },
75
113
  // ---- conversations ----
76
114
  {
77
115
  method: 'post', path: '/v1/conversations', tag: 'conversations', auth: true,
@@ -47,7 +47,7 @@ function operation(e) {
47
47
  ...(e.description ? { description: e.description } : {}),
48
48
  tags: [e.tag],
49
49
  ...(e.deprecated ? { deprecated: true } : {}),
50
- ...(e.auth ? {} : { security: [] }),
50
+ ...(!e.auth ? { security: [] } : e.authBy ? { security: e.authBy.map((a) => ({ [a === 'cookie' ? 'webSession' : 'apiKey']: [] })) } : {}),
51
51
  ...(e.params || e.query ? { parameters: [...parameters('path', e.params), ...parameters('query', e.query)] } : {}),
52
52
  ...(e.body ? { requestBody: { required: true, content: { 'application/json': { schema: schemaFor(e.body, 'input') } } } } : {}),
53
53
  responses,
@@ -68,12 +68,13 @@ export function buildOpenApi(version = '1.0.0') {
68
68
  '`code` is stable for programs, `message` and `hint` are written for people.',
69
69
  },
70
70
  servers: [{ url: 'http://localhost:3000' }],
71
- security: [{ apiKey: [] }],
71
+ security: [{ apiKey: [] }, { webSession: [] }],
72
72
  tags: [
73
73
  { name: 'conversations' },
74
74
  { name: 'models' },
75
75
  { name: 'account' },
76
76
  { name: 'operations' },
77
+ { name: 'web' },
77
78
  { name: 'health' },
78
79
  { name: 'legacy' },
79
80
  ],
@@ -81,6 +82,12 @@ export function buildOpenApi(version = '1.0.0') {
81
82
  components: {
82
83
  securitySchemes: {
83
84
  apiKey: { type: 'http', scheme: 'bearer', description: 'An API key: `Authorization: Bearer llmgw_...`' },
85
+ webSession: {
86
+ type: 'apiKey',
87
+ in: 'cookie',
88
+ name: 'llmgw_session',
89
+ description: 'The web page\'s session, from `POST /web/session`. State-changing requests must come from the gateway\'s own origin.',
90
+ },
84
91
  },
85
92
  schemas: Object.fromEntries(Object.entries(schemas).map(([id, s]) => [id, clean(s)])),
86
93
  },
@@ -53,6 +53,7 @@ export const StatsQuery = z.object({
53
53
  hours: z.coerce.number().int().min(1).max(720).default(24),
54
54
  recent: z.coerce.number().int().min(0).max(50).default(5),
55
55
  });
56
+ export const RedeemCodeBody = z.object({ code: z.string().min(16).max(200).describe('The one-time code from the sign-in link') });
56
57
  export const LegacyChatBody = z.object({
57
58
  model: z.string(),
58
59
  messages: z
@@ -141,6 +142,7 @@ export const BackupSummary = named(z.strictObject({
141
142
  bytes: z.number().int(),
142
143
  createdAt: timestamp,
143
144
  }), 'BackupSummary');
145
+ export const WebCode = named(z.strictObject({ code: z.string(), expiresAt: timestamp }), 'WebCode', 'A one-time sign-in code for the web page; works once, for 60 seconds');
144
146
  export const Health = named(z.strictObject({ ok: z.literal(true), mode: z.enum(['single', 'server']) }), 'Health');
145
147
  export const Readiness = named(z.strictObject({ ok: z.boolean(), ollama: z.boolean(), db: z.boolean() }), 'Readiness');
146
148
  export const LegacyChatResponse = named(z.looseObject({}).describe('OpenAI-compatible chat completion, passed through from Ollama'), 'LegacyChatResponse');
package/dist/src/app.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { totalmem } from 'node:os';
3
+ import cookie from '@fastify/cookie';
3
4
  import rateLimit from '@fastify/rate-limit';
4
5
  import Fastify from 'fastify';
5
6
  import { Redis } from 'ioredis';
@@ -26,6 +27,10 @@ import { meRoutes } from './routes/me.js';
26
27
  import { statsRoutes } from './routes/stats.js';
27
28
  import { doctorRoutes } from './routes/doctor.js';
28
29
  import { backupRoutes } from './routes/backup.js';
30
+ import { webCodeRoutes, webSessionRoutes } from './routes/web-session.js';
31
+ import { webPageRoutes } from './routes/web-page.js';
32
+ import { findWebRoot } from './lib/web-root.js';
33
+ import { WebSessionService } from './services/web-session.service.js';
29
34
  export async function buildApp(opts = {}) {
30
35
  const config = opts.config ?? createConfig();
31
36
  const app = Fastify({
@@ -94,6 +99,7 @@ export async function buildApp(opts = {}) {
94
99
  const provider = opts.provider ?? new OllamaProvider(config.OLLAMA_URL);
95
100
  const ollama = opts.ollama ?? new OllamaModels(config.OLLAMA_URL);
96
101
  const auth = new AuthService(repos.apiKeys);
102
+ const webSessions = new WebSessionService(storage.webSessions);
97
103
  const models = new ModelsService({
98
104
  ...config.models,
99
105
  source: ollama,
@@ -115,7 +121,7 @@ export async function buildApp(opts = {}) {
115
121
  messages: repos.messages,
116
122
  generations: repos.generations,
117
123
  });
118
- const deps = { config, storage, limiter, metrics, provider, ollama, auth, conversations, models, repos };
124
+ const deps = { config, storage, limiter, metrics, provider, ollama, auth, webSessions, conversations, models, repos };
119
125
  let redis = null;
120
126
  if (config.REDIS_URL) {
121
127
  redis = new Redis(config.REDIS_URL, {
@@ -124,6 +130,21 @@ export async function buildApp(opts = {}) {
124
130
  enableOfflineQueue: false, // fail fast if Redis is down
125
131
  });
126
132
  redis.on('error', (e) => app.log.warn({ err: e.message }, 'redis error'));
133
+ // Wait briefly for the connection, so limits apply from the first request. Without this,
134
+ // requests that arrive before Redis is ready skip the limit (skipOnError below). If Redis
135
+ // is down, start anyway after 1 s: serving beats refusing.
136
+ const client = redis;
137
+ if (client.status !== 'ready') {
138
+ await new Promise((done) => {
139
+ const timer = setTimeout(done, 1000);
140
+ const finish = () => {
141
+ clearTimeout(timer);
142
+ done();
143
+ };
144
+ client.once('ready', finish);
145
+ client.once('error', finish);
146
+ });
147
+ }
127
148
  }
128
149
  app.log.info({
129
150
  mode: config.mode,
@@ -141,9 +162,12 @@ export async function buildApp(opts = {}) {
141
162
  await storage.close();
142
163
  });
143
164
  // ---- routes ----
165
+ await app.register(cookie); // parses cookies for the web page's session (no signing: the token is random)
144
166
  await app.register(healthRoutes, { deps });
167
+ await app.register(webSessionRoutes, { deps });
168
+ await app.register(webPageRoutes, { root: opts.webRoot === undefined ? findWebRoot() : opts.webRoot });
145
169
  await app.register(async (v1) => {
146
- v1.addHook('onRequest', makeAuthHook(auth)); // auth first, so rate limiting can key on the key id
170
+ v1.addHook('onRequest', makeAuthHook(auth, webSessions, config.webHosts)); // auth first, so rate limiting can key on the key id
147
171
  await v1.register(rateLimit, {
148
172
  max: config.RATE_LIMIT_MAX,
149
173
  timeWindow: config.RATE_LIMIT_WINDOW,
@@ -159,6 +183,7 @@ export async function buildApp(opts = {}) {
159
183
  await v1.register(statsRoutes, { deps });
160
184
  await v1.register(doctorRoutes, { deps });
161
185
  await v1.register(backupRoutes, { deps });
186
+ await v1.register(webCodeRoutes, { deps });
162
187
  }, { prefix: '/v1' });
163
188
  return { app, deps, routes };
164
189
  }
@@ -24,6 +24,8 @@ const Env = z.object({
24
24
  RESERVE_OUTPUT_TOKENS: z.coerce.number().int().positive().default(800),
25
25
  MAX_HISTORY_MESSAGES: z.coerce.number().int().positive().default(100),
26
26
  LEASE_SECONDS: z.coerce.number().int().positive().default(180),
27
+ // Extra host names the web page may be reached by (comma-separated), beyond localhost.
28
+ WEB_HOSTS: optionalString,
27
29
  });
28
30
  const list = (s) => s.split(',').map((x) => x.trim()).filter(Boolean);
29
31
  /** Where single-user mode keeps its database, following each OS's convention. */
@@ -45,6 +47,7 @@ export function createConfig(env = process.env) {
45
47
  ...e,
46
48
  mode,
47
49
  dataDir: e.DATA_DIR ?? defaultDataDir(process.platform, env),
50
+ webHosts: e.WEB_HOSTS ? list(e.WEB_HOSTS) : [],
48
51
  /** `undefined` means "discover from Ollama" (single-user mode only). */
49
52
  models: {
50
53
  allowed: e.ALLOWED_MODELS ? list(e.ALLOWED_MODELS) : fallback ? [fallback] : undefined,
@@ -0,0 +1,16 @@
1
+ // Finds the built web page (Vite's output, dist/web) from wherever the code runs:
2
+ // dist/src/... in the repo or the npm package, or src/... under tsx in development.
3
+ // Returns null when the page hasn't been built (the API still works without it).
4
+ import { existsSync } from 'node:fs';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ export function findWebRoot(from = dirname(fileURLToPath(import.meta.url))) {
8
+ for (let dir = from;; dir = dirname(dir)) {
9
+ if (basename(dir) === 'dist' && existsSync(join(dir, 'web', 'index.html')))
10
+ return join(dir, 'web');
11
+ if (existsSync(join(dir, 'dist', 'web', 'index.html')))
12
+ return join(dir, 'dist', 'web');
13
+ if (dirname(dir) === dir)
14
+ return null;
15
+ }
16
+ }
@@ -1,13 +1,36 @@
1
- export function makeAuthHook(auth) {
2
- return async function requireApiKey(req, reply) {
1
+ import { allowedHost, SAFE_METHODS, sameOrigin, SESSION_COOKIE } from './web-guard.js';
2
+ const deny = (req, reply, status, code, message, hint) => reply.code(status).send({ error: { code, message, ...(hint ? { hint } : {}), request_id: req.id } });
3
+ /**
4
+ * Who is calling: an API key (`Authorization: Bearer`, the CLI and scripts) or, for the web
5
+ * page, a session cookie. A key always wins. Cookie requests must also pass the host and
6
+ * origin checks (see web-guard.ts).
7
+ */
8
+ export function makeAuthHook(auth, web, webHosts) {
9
+ return async function requireAuth(req, reply) {
3
10
  const header = req.headers.authorization;
4
11
  const key = header?.startsWith('Bearer ') ? header.slice(7).trim() : undefined;
5
- const ctx = key ? await auth.authenticate(key) : null;
6
- if (!ctx) {
7
- return reply.code(401).send({
8
- error: { code: 'invalid_api_key', message: 'invalid api key', request_id: req.id },
9
- });
12
+ if (key) {
13
+ const ctx = await auth.authenticate(key);
14
+ if (!ctx)
15
+ return deny(req, reply, 401, 'invalid_api_key', 'invalid api key');
16
+ req.auth = { ...ctx, via: 'key' };
17
+ return;
10
18
  }
11
- req.auth = ctx;
19
+ const token = req.cookies?.[SESSION_COOKIE];
20
+ if (token) {
21
+ if (!allowedHost(req.headers.host, webHosts)) {
22
+ return deny(req, reply, 403, 'forbidden_host', 'This address is not allowed to use a signed-in session.');
23
+ }
24
+ if (!SAFE_METHODS.has(req.method) && !sameOrigin(req.headers.origin, req.headers.host)) {
25
+ return deny(req, reply, 403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
26
+ }
27
+ const session = await web.authenticate(token);
28
+ if (session) {
29
+ req.auth = { userId: session.userId, keyId: `session:${session.sessionId}`, via: 'session' };
30
+ return;
31
+ }
32
+ return deny(req, reply, 401, 'session_expired', 'Your sign-in has ended.', 'Sign in again: run llm open');
33
+ }
34
+ return deny(req, reply, 401, 'invalid_api_key', 'invalid api key');
12
35
  };
13
36
  }
@@ -1,4 +1,4 @@
1
- import client from 'prom-client';
1
+ import client from '@prometheus-io/client';
2
2
  export function createMetrics(limiter) {
3
3
  const registry = new client.Registry();
4
4
  client.collectDefaultMetrics({ register: registry });
@@ -0,0 +1,37 @@
1
+ // Checks that keep other websites from using the gateway through the user's browser.
2
+ //
3
+ // The gateway listens on localhost, and any page the user visits can send requests there.
4
+ // A cookie session must not let them in:
5
+ // - Host check: a browser on a DNS-rebinding page sends that page's domain as `Host`, so a
6
+ // cookie request (or a sign-in) must be addressed to a loopback name or a configured host.
7
+ // - Origin check: a cookie request that changes something must come from the gateway's own
8
+ // page (`Origin` equal to the gateway). SameSite=Strict already stops cross-site cookies;
9
+ // this is the second lock.
10
+ // API keys in `Authorization` are not affected: another site can't know the key.
11
+ export const SESSION_COOKIE = 'llmgw_session';
12
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
13
+ export const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
14
+ /** The host part of a Host header, lower-cased, without the port ("[::1]:3000" -> "[::1]"). */
15
+ export function hostName(host) {
16
+ if (!host)
17
+ return '';
18
+ const h = host.trim().toLowerCase();
19
+ if (h.startsWith('['))
20
+ return h.slice(0, h.indexOf(']') + 1);
21
+ return h.split(':')[0];
22
+ }
23
+ export function allowedHost(host, extra) {
24
+ const name = hostName(host);
25
+ return LOOPBACK.has(name) || extra.map((e) => e.toLowerCase()).includes(name);
26
+ }
27
+ /** True when `origin` is exactly this gateway (same scheme-agnostic host and port as `Host`). */
28
+ export function sameOrigin(origin, host) {
29
+ if (!origin || !host || origin === 'null')
30
+ return false;
31
+ try {
32
+ return new URL(origin).host.toLowerCase() === host.trim().toLowerCase();
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
@@ -0,0 +1,42 @@
1
+ // Serves the web chat page: `/` (index.html) and `/assets/*` (Vite's hashed files).
2
+ import { join } from 'node:path';
3
+ import fastifyStatic from '@fastify/static';
4
+ import { AppError } from '../lib/errors.js';
5
+ /**
6
+ * Only the gateway's own files may run or style the page: no inline code, no other sites.
7
+ * Model answers are shown as text by the page; this is the second line of defence.
8
+ */
9
+ export const CONTENT_SECURITY_POLICY = [
10
+ "default-src 'self'",
11
+ "script-src 'self'",
12
+ "style-src 'self'",
13
+ "img-src 'self' data:",
14
+ "connect-src 'self'",
15
+ "base-uri 'none'",
16
+ "form-action 'self'",
17
+ "frame-ancestors 'none'", // no other site may frame the page (clickjacking)
18
+ "object-src 'none'",
19
+ ].join('; ');
20
+ const securityHeaders = (reply) => reply
21
+ .header('content-security-policy', CONTENT_SECURITY_POLICY)
22
+ .header('x-content-type-options', 'nosniff')
23
+ .header('referrer-policy', 'no-referrer')
24
+ .header('x-frame-options', 'DENY');
25
+ export const webPageRoutes = async (app, { root }) => {
26
+ if (root) {
27
+ await app.register(fastifyStatic, {
28
+ root: join(root, 'assets'),
29
+ prefix: '/assets/',
30
+ immutable: true, // file names contain a content hash: cache forever
31
+ maxAge: '365d',
32
+ setHeaders: (res) => void res.header('x-content-type-options', 'nosniff'),
33
+ });
34
+ }
35
+ app.get('/', async (_req, reply) => {
36
+ if (!root) {
37
+ throw new AppError(404, 'page_not_built', "The web page isn't built.", { hint: 'Run: npm run build (or use llm chat)' });
38
+ }
39
+ securityHeaders(reply).header('cache-control', 'no-cache'); // always pick up a new version
40
+ return reply.sendFile('index.html', root);
41
+ });
42
+ };
@@ -0,0 +1,52 @@
1
+ import { RedeemCodeBody } from '../api/schemas.js';
2
+ import { AppError } from '../lib/errors.js';
3
+ import { allowedHost, sameOrigin, SESSION_COOKIE } from '../plugins/web-guard.js';
4
+ /** Sign-in and sign-out are reached from the page: the same host and origin rules apply. */
5
+ function guard(req, webHosts) {
6
+ if (!allowedHost(req.headers.host, webHosts)) {
7
+ throw new AppError(403, 'forbidden_host', 'This address is not allowed to sign in.');
8
+ }
9
+ // Browsers always send Origin on a cross-site POST/DELETE; a non-browser client may send none.
10
+ if (req.headers.origin !== undefined && !sameOrigin(req.headers.origin, req.headers.host)) {
11
+ throw new AppError(403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
12
+ }
13
+ }
14
+ const cookieOptions = (req) => ({
15
+ httpOnly: true, // the page's scripts can't read it, so injected scripts can't steal it
16
+ sameSite: 'strict', // other sites' requests don't carry it
17
+ path: '/',
18
+ secure: req.protocol === 'https', // http://localhost has no TLS; over HTTPS (e.g. Tailscale) it's Secure
19
+ });
20
+ /** POST /v1/web/codes, inside the authenticated /v1 scope. */
21
+ export const webCodeRoutes = async (app, { deps }) => {
22
+ app.post('/web/codes', async (req, reply) => {
23
+ if (req.auth?.via !== 'key') {
24
+ throw new AppError(403, 'key_required', 'Only an API key can create a sign-in link.', { hint: 'Run llm open in a terminal.' });
25
+ }
26
+ const { code, expiresAt } = await deps.webSessions.createCode(req.auth.userId);
27
+ return reply.code(201).send({ code, expiresAt: expiresAt.toISOString() });
28
+ });
29
+ };
30
+ /** POST and DELETE /web/session: public paths (the page has no key), guarded by host and origin. */
31
+ export const webSessionRoutes = async (app, { deps }) => {
32
+ app.post('/web/session', async (req, reply) => {
33
+ guard(req, deps.config.webHosts);
34
+ const { code } = RedeemCodeBody.parse(req.body);
35
+ const session = await deps.webSessions.redeem(code);
36
+ if (!session) {
37
+ throw new AppError(401, 'invalid_code', 'This sign-in link has expired or was already used.', {
38
+ hint: 'Run llm open again for a new one.',
39
+ });
40
+ }
41
+ reply.setCookie(SESSION_COOKIE, session.token, { ...cookieOptions(req), maxAge: session.maxAgeSeconds });
42
+ return reply.code(204).send();
43
+ });
44
+ app.delete('/web/session', async (req, reply) => {
45
+ guard(req, deps.config.webHosts);
46
+ const token = req.cookies[SESSION_COOKIE];
47
+ if (token)
48
+ await deps.webSessions.signOut(token);
49
+ reply.clearCookie(SESSION_COOKIE, cookieOptions(req));
50
+ return reply.code(204).send();
51
+ });
52
+ };
File without changes