local-llm-gateway 0.1.1 → 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.
- package/CHANGELOG.md +13 -0
- package/README.md +8 -2
- package/cli/dist/api/client.js +4 -0
- package/cli/dist/commands/open.js +40 -0
- package/cli/dist/index.js +6 -0
- package/cli/dist/repl.js +1 -1
- package/dist/src/api/endpoints.js +39 -1
- package/dist/src/api/openapi.js +9 -2
- package/dist/src/api/schemas.js +2 -0
- package/dist/src/app.js +27 -2
- package/dist/src/config.js +3 -0
- package/dist/src/lib/web-root.js +16 -0
- package/dist/src/plugins/auth.js +31 -8
- package/dist/src/plugins/web-guard.js +37 -0
- package/dist/src/routes/web-page.js +42 -0
- package/dist/src/routes/web-session.js +52 -0
- package/dist/src/services/web-session.service.js +50 -0
- package/dist/src/storage/postgres/index.js +2 -0
- package/dist/src/storage/postgres/schema.js +19 -0
- package/dist/src/storage/postgres/web-sessions.js +50 -0
- package/dist/src/storage/sqlite/index.js +2 -0
- package/dist/src/storage/sqlite/schema.js +18 -0
- package/dist/src/storage/sqlite/web-sessions.js +50 -0
- package/dist/web/assets/index-C03RJbF2.js +17 -0
- package/dist/web/assets/index-CDL8Tl5X.css +1 -0
- package/dist/web/index.html +14 -0
- package/drizzle/0003_pale_spectrum.sql +24 -0
- package/drizzle/meta/0003_snapshot.json +735 -0
- package/drizzle/meta/_journal.json +7 -0
- package/drizzle/sqlite/0001_blushing_jack_murdock.sql +24 -0
- package/drizzle/sqlite/meta/0001_snapshot.json +698 -0
- package/drizzle/sqlite/meta/_journal.json +7 -0
- package/package.json +16 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
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
|
+
|
|
3
16
|
## 0.1.1 (2026-11-20)
|
|
4
17
|
|
|
5
18
|
- `npx local-llm-gateway` now starts the assistant (0.1.0 said "could not determine
|
package/README.md
CHANGED
|
@@ -24,10 +24,15 @@ get, for example `ollama pull qwen3:8b`. `llm start` keeps running in that windo
|
|
|
24
24
|
stops it.
|
|
25
25
|
|
|
26
26
|
```bash
|
|
27
|
-
# 3. In a second window
|
|
27
|
+
# 3. In a second window: chat in your browser...
|
|
28
|
+
llm open
|
|
29
|
+
# ...or in the terminal
|
|
28
30
|
llm chat "hello"
|
|
29
31
|
```
|
|
30
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
|
+
|
|
31
36
|
To try it without installing: `npx local-llm-gateway` starts the assistant, and
|
|
32
37
|
`npx -p local-llm-gateway llm chat "hello"` chats from a second window.
|
|
33
38
|
|
|
@@ -44,7 +49,8 @@ fix whatever is wrong.
|
|
|
44
49
|
|
|
45
50
|
| Command | What it does |
|
|
46
51
|
| --- | --- |
|
|
47
|
-
| `llm
|
|
52
|
+
| `llm open` | Chat in your browser (opens already signed in) |
|
|
53
|
+
| `llm chat` | Talk in the terminal. `llm chat "question"` asks once |
|
|
48
54
|
| `llm ls`, `llm show <id>`, `llm resume <id>` | Your conversations |
|
|
49
55
|
| `llm fork <id>` | Try another way from an earlier answer |
|
|
50
56
|
| `llm models` | Downloaded models; `*` marks the one in use |
|
package/cli/dist/api/client.js
CHANGED
|
@@ -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)')
|
package/cli/dist/repl.js
CHANGED
|
@@ -31,7 +31,7 @@ export function printSummary(res, quiet) {
|
|
|
31
31
|
}
|
|
32
32
|
return ok;
|
|
33
33
|
}
|
|
34
|
-
const LLM_SUBCOMMANDS = 'profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
|
|
34
|
+
const LLM_SUBCOMMANDS = 'open|profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
|
|
35
35
|
/** `llm profile use local` typed into the chat: a command for the terminal, not a question. */
|
|
36
36
|
export const looksLikeLlmCommand = (line) => new RegExp(`^llm\\s+(${LLM_SUBCOMMANDS})\\b`).test(line);
|
|
37
37
|
export async function runRepl(opts) {
|
|
@@ -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,
|
package/dist/src/api/openapi.js
CHANGED
|
@@ -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
|
},
|
package/dist/src/api/schemas.js
CHANGED
|
@@ -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
|
}
|
package/dist/src/config.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/src/plugins/auth.js
CHANGED
|
@@ -1,13 +1,36 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
|
|
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
|
}
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Browser sign-in for the web chat. The rules, in one place:
|
|
2
|
+
// - `llm open` (holding an API key) asks for a one-time code: random, 60 seconds, works once.
|
|
3
|
+
// - The page exchanges the code for a session token, sent back only as an HttpOnly cookie.
|
|
4
|
+
// - A session ends after 30 days without use; "last seen" is written at most once a minute.
|
|
5
|
+
// Codes and tokens are 256-bit random values; only their SHA-256 hashes are stored.
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { sha256 } from '../lib/hash.js';
|
|
8
|
+
export const CODE_TTL_MS = 60_000;
|
|
9
|
+
export const SESSION_IDLE_MS = 30 * 24 * 3_600_000;
|
|
10
|
+
const TOUCH_EVERY_MS = 60_000;
|
|
11
|
+
const token = () => randomBytes(32).toString('base64url');
|
|
12
|
+
export class WebSessionService {
|
|
13
|
+
store;
|
|
14
|
+
now;
|
|
15
|
+
constructor(store, now = () => new Date()) {
|
|
16
|
+
this.store = store;
|
|
17
|
+
this.now = now;
|
|
18
|
+
}
|
|
19
|
+
async createCode(userId) {
|
|
20
|
+
const now = this.now();
|
|
21
|
+
const code = token();
|
|
22
|
+
const expiresAt = new Date(now.getTime() + CODE_TTL_MS);
|
|
23
|
+
await this.store.deleteExpired(new Date(now.getTime() - 24 * 3_600_000)); // cheap housekeeping
|
|
24
|
+
await this.store.createCode(userId, sha256(code), expiresAt);
|
|
25
|
+
return { code, expiresAt };
|
|
26
|
+
}
|
|
27
|
+
/** The raw session token to put in the cookie, or null if the code is unknown, used or expired. */
|
|
28
|
+
async redeem(code) {
|
|
29
|
+
const now = this.now();
|
|
30
|
+
const hit = await this.store.redeemCode(sha256(code), now);
|
|
31
|
+
if (!hit)
|
|
32
|
+
return null;
|
|
33
|
+
const raw = token();
|
|
34
|
+
await this.store.createSession(hit.userId, sha256(raw), now, new Date(now.getTime() + SESSION_IDLE_MS));
|
|
35
|
+
return { token: raw, maxAgeSeconds: SESSION_IDLE_MS / 1000 };
|
|
36
|
+
}
|
|
37
|
+
async authenticate(rawToken) {
|
|
38
|
+
const now = this.now();
|
|
39
|
+
const s = await this.store.findActiveSession(sha256(rawToken), now);
|
|
40
|
+
if (!s)
|
|
41
|
+
return null;
|
|
42
|
+
if (now.getTime() - s.lastSeenAt.getTime() >= TOUCH_EVERY_MS) {
|
|
43
|
+
await this.store.touchSession(s.id, now, new Date(now.getTime() + SESSION_IDLE_MS));
|
|
44
|
+
}
|
|
45
|
+
return { userId: s.userId, sessionId: s.id };
|
|
46
|
+
}
|
|
47
|
+
signOut(rawToken) {
|
|
48
|
+
return this.store.revokeSession(sha256(rawToken), this.now());
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -6,11 +6,13 @@ import { PgConversationsStore } from './conversations.js';
|
|
|
6
6
|
import { PgGenerationsStore } from './generations.js';
|
|
7
7
|
import { PgApiKeysStore, PgUsersStore } from './identity.js';
|
|
8
8
|
import { PgMessagesStore } from './messages.js';
|
|
9
|
+
import { PgWebSessionsStore } from './web-sessions.js';
|
|
9
10
|
export function createPostgresStorage(url) {
|
|
10
11
|
const { db, close } = createDb(url);
|
|
11
12
|
return {
|
|
12
13
|
db,
|
|
13
14
|
users: new PgUsersStore(db),
|
|
15
|
+
webSessions: new PgWebSessionsStore(db),
|
|
14
16
|
apiKeys: new PgApiKeysStore(db),
|
|
15
17
|
conversations: new PgConversationsStore(db),
|
|
16
18
|
messages: new PgMessagesStore(db),
|
|
@@ -66,3 +66,22 @@ export const generations = pgTable('generations', {
|
|
|
66
66
|
index('generations_user_created_idx').on(t.userId, t.createdAt),
|
|
67
67
|
index('generations_request_idx').on(t.requestId),
|
|
68
68
|
]);
|
|
69
|
+
// Browser sign-in (web chat). Only hashes are stored, like API keys.
|
|
70
|
+
// A one-time code (from `llm open`) is exchanged once for a session cookie.
|
|
71
|
+
export const webCodes = pgTable('web_codes', {
|
|
72
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
73
|
+
userId: uuid('user_id').notNull().references(() => users.id),
|
|
74
|
+
codeHash: text('code_hash').notNull().unique(),
|
|
75
|
+
expiresAt: ts('expires_at').notNull(),
|
|
76
|
+
usedAt: ts('used_at'),
|
|
77
|
+
createdAt: ts('created_at').notNull().defaultNow(),
|
|
78
|
+
});
|
|
79
|
+
export const webSessions = pgTable('web_sessions', {
|
|
80
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
81
|
+
userId: uuid('user_id').notNull().references(() => users.id),
|
|
82
|
+
tokenHash: text('token_hash').notNull().unique(),
|
|
83
|
+
createdAt: ts('created_at').notNull().defaultNow(),
|
|
84
|
+
lastSeenAt: ts('last_seen_at').notNull(),
|
|
85
|
+
expiresAt: ts('expires_at').notNull(), // slides forward with use (idle timeout)
|
|
86
|
+
revokedAt: ts('revoked_at'),
|
|
87
|
+
}, (t) => [index('web_sessions_user_idx').on(t.userId)]);
|