local-llm-gateway 0.1.1 → 0.3.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 (42) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +30 -2
  3. package/cli/dist/api/client.js +14 -0
  4. package/cli/dist/commands/open.js +41 -0
  5. package/cli/dist/commands/phone.js +85 -0
  6. package/cli/dist/commands/start.js +3 -1
  7. package/cli/dist/index.js +19 -0
  8. package/cli/dist/qr.js +64 -0
  9. package/cli/dist/repl.js +1 -1
  10. package/dist/src/api/endpoints.js +65 -1
  11. package/dist/src/api/openapi.js +9 -2
  12. package/dist/src/api/schemas.js +26 -0
  13. package/dist/src/app.js +42 -2
  14. package/dist/src/config.js +9 -0
  15. package/dist/src/lib/network.js +129 -0
  16. package/dist/src/lib/web-root.js +16 -0
  17. package/dist/src/plugins/auth.js +39 -8
  18. package/dist/src/plugins/web-guard.js +37 -0
  19. package/dist/src/routes/web-page.js +43 -0
  20. package/dist/src/routes/web-session.js +108 -0
  21. package/dist/src/server.js +10 -3
  22. package/dist/src/services/web-session.service.js +85 -0
  23. package/dist/src/storage/postgres/index.js +2 -0
  24. package/dist/src/storage/postgres/schema.js +24 -0
  25. package/dist/src/storage/postgres/web-sessions.js +72 -0
  26. package/dist/src/storage/sqlite/index.js +2 -0
  27. package/dist/src/storage/sqlite/schema.js +23 -0
  28. package/dist/src/storage/sqlite/web-sessions.js +76 -0
  29. package/dist/web/assets/index-BH2EiFDE.css +1 -0
  30. package/dist/web/assets/index-C52qddcS.js +24 -0
  31. package/dist/web/index.html +15 -0
  32. package/drizzle/0003_pale_spectrum.sql +24 -0
  33. package/drizzle/0004_married_frog_thor.sql +3 -0
  34. package/drizzle/meta/0003_snapshot.json +735 -0
  35. package/drizzle/meta/0004_snapshot.json +755 -0
  36. package/drizzle/meta/_journal.json +14 -0
  37. package/drizzle/sqlite/0001_blushing_jack_murdock.sql +24 -0
  38. package/drizzle/sqlite/0002_dry_the_fallen.sql +3 -0
  39. package/drizzle/sqlite/meta/0001_snapshot.json +698 -0
  40. package/drizzle/sqlite/meta/0002_snapshot.json +721 -0
  41. package/drizzle/sqlite/meta/_journal.json +14 -0
  42. package/package.json +18 -5
@@ -24,6 +24,10 @@ 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,
29
+ // 'wifi': single-user mode also listens on the local network, for paired phones (llm start --phone).
30
+ PHONE_ACCESS: z.preprocess((v) => (v === '' ? undefined : v), z.enum(['off', 'wifi']).default('off')),
27
31
  });
28
32
  const list = (s) => s.split(',').map((x) => x.trim()).filter(Boolean);
29
33
  /** Where single-user mode keeps its database, following each OS's convention. */
@@ -45,6 +49,7 @@ export function createConfig(env = process.env) {
45
49
  ...e,
46
50
  mode,
47
51
  dataDir: e.DATA_DIR ?? defaultDataDir(process.platform, env),
52
+ webHosts: e.WEB_HOSTS ? list(e.WEB_HOSTS) : [],
48
53
  /** `undefined` means "discover from Ollama" (single-user mode only). */
49
54
  models: {
50
55
  allowed: e.ALLOWED_MODELS ? list(e.ALLOWED_MODELS) : fallback ? [fallback] : undefined,
@@ -52,3 +57,7 @@ export function createConfig(env = process.env) {
52
57
  },
53
58
  };
54
59
  }
60
+ /** Where the gateway listens: also on the network when single-user mode has phone access on. */
61
+ export function listenHost(c) {
62
+ return c.mode === 'single' && c.PHONE_ACCESS === 'wifi' && ['127.0.0.1', 'localhost'].includes(c.HOST) ? '0.0.0.0' : c.HOST;
63
+ }
@@ -0,0 +1,129 @@
1
+ // This computer's addresses on the network, for phone access: which host names the page may
2
+ // be reached by, and which URLs to put in a pairing QR code. Detection is best effort; the
3
+ // gateway works the same without it (only localhost is allowed then).
4
+ import { execFile } from 'node:child_process';
5
+ import { networkInterfaces, hostname as osHostname } from 'node:os';
6
+ const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
7
+ const isTailscaleIp = (ip) => {
8
+ const [a, b] = ip.split('.').map(Number);
9
+ return a === 100 && b >= 64 && b <= 127; // 100.64.0.0/10, the range Tailscale uses
10
+ };
11
+ /** IPv4 addresses on the local network (Wi-Fi, Ethernet): not loopback, link-local or Tailscale. */
12
+ export function lanAddresses(ifaces = networkInterfaces()) {
13
+ const out = [];
14
+ for (const list of Object.values(ifaces)) {
15
+ for (const i of list ?? []) {
16
+ if (i.family !== 'IPv4' || i.internal)
17
+ continue;
18
+ if (i.address.startsWith('169.254.') || isTailscaleIp(i.address))
19
+ continue;
20
+ out.push(i.address);
21
+ }
22
+ }
23
+ return [...new Set(out)];
24
+ }
25
+ /** `macbook.local`: the name iPhones (and newer Androids) can use on the same Wi-Fi. */
26
+ export function localName(host = osHostname()) {
27
+ const base = host.toLowerCase().replace(/\.local$/, '');
28
+ return `${base}.local`;
29
+ }
30
+ /** Every host name the page may be reached by, besides localhost. Pure: easy to test. */
31
+ export function networkHosts(input) {
32
+ const names = [...input.addresses, localName(input.hostname), ...(input.tailscaleName ? [input.tailscaleName] : []), ...input.extra];
33
+ return [...new Set(names.map((n) => n.toLowerCase()))];
34
+ }
35
+ const TAILSCALE_BINARIES = ['tailscale', '/Applications/Tailscale.app/Contents/MacOS/Tailscale'];
36
+ function run(bin, args, timeoutMs) {
37
+ return new Promise((done) => {
38
+ execFile(bin, args, { timeout: timeoutMs }, (err, stdout) => done(err ? null : stdout));
39
+ });
40
+ }
41
+ /** This machine's Tailscale name (`mac.tailnet.ts.net`) and whether `tailscale serve` points at `port`. */
42
+ export async function detectTailscale(port, timeoutMs = 2000) {
43
+ for (const bin of TAILSCALE_BINARIES) {
44
+ const status = await run(bin, ['status', '--json'], timeoutMs);
45
+ if (!status)
46
+ continue;
47
+ try {
48
+ const name = String(JSON.parse(status).Self?.DNSName ?? '').replace(/\.$/, '');
49
+ if (!name)
50
+ return null;
51
+ const serve = (await run(bin, ['serve', 'status', '--json'], timeoutMs)) ?? '';
52
+ const serving = serve.includes(`127.0.0.1:${port}`) || serve.includes(`localhost:${port}`);
53
+ return { name: name.toLowerCase(), serving };
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+ const LOOPBACK_ADDRESS = /^(127\.|::1$|::ffff:127\.)/;
62
+ export const isLoopbackAddress = (address) => !!address && LOOPBACK_ADDRESS.test(address);
63
+ const hostOnly = (host) => {
64
+ const h = (host ?? '').trim().toLowerCase();
65
+ return h.startsWith('[') ? h.slice(0, h.indexOf(']') + 1) : h.split(':')[0];
66
+ };
67
+ /**
68
+ * True only for a request from this computer itself. A phone behind `tailscale serve` also
69
+ * connects from 127.0.0.1, but carries forwarding headers and a non-loopback host name, so
70
+ * it counts as the network. (A local program that adds such headers only loses privileges.)
71
+ */
72
+ export function isLocalRequest(req) {
73
+ const h = req.headers;
74
+ return (isLoopbackAddress(req.socket.remoteAddress) &&
75
+ !h['x-forwarded-for'] &&
76
+ !h['x-forwarded-host'] &&
77
+ !h['tailscale-user-login'] &&
78
+ LOOPBACK_NAMES.has(hostOnly(h.host)));
79
+ }
80
+ const first = (v) => (Array.isArray(v) ? v[0] : v)?.split(',')[0]?.trim();
81
+ /** The host the browser used. Behind a local proxy (Tailscale), the forwarded one. */
82
+ export function requestHost(req) {
83
+ if (isLoopbackAddress(req.socket.remoteAddress))
84
+ return first(req.headers['x-forwarded-host']) ?? req.headers.host;
85
+ return req.headers.host;
86
+ }
87
+ /** 'https' when the browser used HTTPS, including through a local proxy that ends TLS. */
88
+ export function requestProtocol(req, direct) {
89
+ if (isLoopbackAddress(req.socket.remoteAddress))
90
+ return first(req.headers['x-forwarded-proto']) ?? direct;
91
+ return direct;
92
+ }
93
+ /**
94
+ * The host names allowed right now. Network addresses can change (a new Wi-Fi), so the list
95
+ * is rebuilt at most every 30 seconds; the Tailscale lookup runs in the background.
96
+ */
97
+ export class WebHosts {
98
+ opts;
99
+ cached = null;
100
+ tailscale = null;
101
+ constructor(opts) {
102
+ this.opts = opts;
103
+ if (opts.detect)
104
+ void this.refreshTailscale();
105
+ }
106
+ list() {
107
+ if (this.opts.fixed)
108
+ return [...this.opts.fixed, ...this.opts.extra];
109
+ if (!this.opts.detect)
110
+ return [...this.opts.extra];
111
+ const now = Date.now();
112
+ if (!this.cached || now - this.cached.at > 30_000) {
113
+ if (this.cached)
114
+ void this.refreshTailscale();
115
+ this.cached = {
116
+ at: now,
117
+ hosts: networkHosts({ addresses: lanAddresses(), hostname: osHostname(), tailscaleName: this.tailscale?.name ?? null, extra: this.opts.extra }),
118
+ };
119
+ }
120
+ return this.cached.hosts;
121
+ }
122
+ tailscaleInfo() {
123
+ return this.tailscale;
124
+ }
125
+ async refreshTailscale() {
126
+ this.tailscale = await detectTailscale(this.opts.port);
127
+ this.cached = null;
128
+ }
129
+ }
@@ -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,44 @@
1
- export function makeAuthHook(auth) {
2
- return async function requireApiKey(req, reply) {
1
+ import { requestHost } from '../lib/network.js';
2
+ import { allowedHost, SAFE_METHODS, sameOrigin, SESSION_COOKIE } from './web-guard.js';
3
+ const deny = (req, reply, status, code, message, hint) => reply.code(status).send({ error: { code, message, ...(hint ? { hint } : {}), request_id: req.id } });
4
+ /**
5
+ * Who is calling: an API key (`Authorization: Bearer`, the CLI and scripts) or, for the web
6
+ * page, a session cookie. A key always wins. Cookie requests must also pass the host and
7
+ * origin checks (see web-guard.ts).
8
+ */
9
+ export function makeAuthHook(auth, web, hosts) {
10
+ return async function requireAuth(req, reply) {
3
11
  const header = req.headers.authorization;
4
12
  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
- });
13
+ if (key) {
14
+ const ctx = await auth.authenticate(key);
15
+ if (!ctx)
16
+ return deny(req, reply, 401, 'invalid_api_key', 'invalid api key');
17
+ req.auth = { ...ctx, via: 'key' };
18
+ return;
10
19
  }
11
- req.auth = ctx;
20
+ const token = req.cookies?.[SESSION_COOKIE];
21
+ if (token) {
22
+ const host = requestHost(req); // behind `tailscale serve`, the host the phone used
23
+ if (!allowedHost(host, hosts.list())) {
24
+ return deny(req, reply, 403, 'forbidden_host', 'This address is not allowed to use a signed-in session.');
25
+ }
26
+ if (!SAFE_METHODS.has(req.method) && !sameOrigin(req.headers.origin, host)) {
27
+ return deny(req, reply, 403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
28
+ }
29
+ const session = await web.authenticate(token);
30
+ if (session) {
31
+ req.auth = {
32
+ userId: session.userId,
33
+ keyId: `session:${session.sessionId}`,
34
+ via: 'session',
35
+ sessionId: session.sessionId,
36
+ sessionFrom: session.createdFrom,
37
+ };
38
+ return;
39
+ }
40
+ return deny(req, reply, 401, 'session_expired', 'Your sign-in has ended.', 'Sign in again: run llm open');
41
+ }
42
+ return deny(req, reply, 401, 'invalid_api_key', 'invalid api key');
12
43
  };
13
44
  }
@@ -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,43 @@
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
+ // cacheControl: false, or sendFile would replace no-cache with the assets' one-year rule.
41
+ return reply.sendFile('index.html', root, { cacheControl: false });
42
+ });
43
+ };
@@ -0,0 +1,108 @@
1
+ import { IdParams, RedeemCodeBody, WebCodeBody } from '../api/schemas.js';
2
+ import { AppError } from '../lib/errors.js';
3
+ import { isLocalRequest, lanAddresses, requestHost, requestProtocol } from '../lib/network.js';
4
+ import { allowedHost, sameOrigin, SESSION_COOKIE } from '../plugins/web-guard.js';
5
+ import { listenHost } from '../config.js';
6
+ /** Sign-in and sign-out are reached from the page: the same host and origin rules apply. */
7
+ function guard(req, deps) {
8
+ const host = requestHost(req);
9
+ if (!allowedHost(host, deps.webHosts.list())) {
10
+ throw new AppError(403, 'forbidden_host', 'This address is not allowed to sign in.');
11
+ }
12
+ // Browsers always send Origin on a cross-site POST/DELETE; a non-browser client may send none.
13
+ if (req.headers.origin !== undefined && !sameOrigin(req.headers.origin, host)) {
14
+ throw new AppError(403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
15
+ }
16
+ }
17
+ const cookieOptions = (req) => ({
18
+ httpOnly: true, // the page's scripts can't read it, so injected scripts can't steal it
19
+ sameSite: 'strict', // other sites' requests don't carry it
20
+ path: '/',
21
+ // HTTPS (e.g. through Tailscale): Secure. http://localhost or Wi-Fi: no TLS to require.
22
+ secure: requestProtocol(req, req.protocol) === 'https',
23
+ });
24
+ /**
25
+ * May this caller pair devices or manage other devices? An API key (the CLI on this
26
+ * computer), or a browser that was signed in on this computer and is still on it.
27
+ * A paired phone never may: a stolen phone can't add more phones.
28
+ */
29
+ const onThisComputer = (req) => req.auth?.via === 'key' || (req.auth?.sessionFrom === 'local' && isLocalRequest(req));
30
+ /** Inside the authenticated /v1 scope: codes, devices, phone info. */
31
+ export const webCodeRoutes = async (app, { deps }) => {
32
+ app.post('/web/codes', async (req, reply) => {
33
+ const { purpose } = WebCodeBody.parse(req.body ?? {});
34
+ if (purpose === 'open' && req.auth?.via !== 'key') {
35
+ throw new AppError(403, 'key_required', 'Only an API key can create a sign-in link.', { hint: 'Run llm open in a terminal.' });
36
+ }
37
+ if (purpose === 'pair' && !onThisComputer(req)) {
38
+ throw new AppError(403, 'pair_from_computer', 'Phones can only be connected from the computer running the assistant.', {
39
+ hint: 'On that computer, run llm phone (or use "Connect a phone" there).',
40
+ });
41
+ }
42
+ const { code, expiresAt } = await deps.webSessions.createCode(req.auth.userId, purpose);
43
+ return reply.code(201).send({ code, expiresAt: expiresAt.toISOString() });
44
+ });
45
+ app.get('/web/sessions', async (req) => {
46
+ const devices = await deps.webSessions.devices(req.auth.userId);
47
+ return {
48
+ data: devices.map((d) => ({
49
+ id: d.id,
50
+ deviceName: d.deviceName,
51
+ createdFrom: d.createdFrom,
52
+ createdAt: d.createdAt.toISOString(),
53
+ lastSeenAt: d.lastSeenAt.toISOString(),
54
+ current: d.id === req.auth.sessionId,
55
+ })),
56
+ };
57
+ });
58
+ app.delete('/web/sessions/:id', async (req, reply) => {
59
+ const { id } = IdParams.parse(req.params);
60
+ // A phone may sign itself out; removing other devices happens on the computer.
61
+ if (id !== req.auth.sessionId && !onThisComputer(req)) {
62
+ throw new AppError(403, 'manage_from_computer', 'Devices can only be removed from the computer running the assistant.', {
63
+ hint: 'On that computer: llm devices, or Devices in the page.',
64
+ });
65
+ }
66
+ if (!(await deps.webSessions.revokeDevice(req.auth.userId, id))) {
67
+ throw new AppError(404, 'device_not_found', 'No such signed-in device.');
68
+ }
69
+ return reply.code(204).send();
70
+ });
71
+ app.get('/web/phone', async (req) => {
72
+ const ts = deps.webHosts.tailscaleInfo();
73
+ const listening = !['127.0.0.1', 'localhost', '::1'].includes(listenHost(deps.config));
74
+ return {
75
+ canPair: onThisComputer(req),
76
+ wifi: { listening, urls: listening ? lanAddresses().map((a) => `http://${a}:${deps.config.PORT}`) : [] },
77
+ tailscale: { name: ts?.name ?? null, url: ts ? `https://${ts.name}` : null, serving: ts?.serving ?? false },
78
+ };
79
+ });
80
+ };
81
+ /** POST and DELETE /web/session: public paths (the page has no key), guarded by host and origin. */
82
+ export const webSessionRoutes = async (app, { deps }) => {
83
+ app.post('/web/session', async (req, reply) => {
84
+ guard(req, deps);
85
+ const { code } = RedeemCodeBody.parse(req.body);
86
+ const result = await deps.webSessions.redeem(code, { local: isLocalRequest(req), userAgent: req.headers['user-agent'] });
87
+ if (result.kind === 'local_only') {
88
+ throw new AppError(403, 'open_link_local_only', 'This sign-in link only works on the computer running the assistant.', {
89
+ hint: 'To connect a phone, use the QR code from llm phone.',
90
+ });
91
+ }
92
+ if (result.kind === 'invalid') {
93
+ throw new AppError(401, 'invalid_code', 'This sign-in link has expired or was already used.', {
94
+ hint: 'Run llm open again for a new one (llm phone for a phone).',
95
+ });
96
+ }
97
+ reply.setCookie(SESSION_COOKIE, result.token, { ...cookieOptions(req), maxAge: result.maxAgeSeconds });
98
+ return reply.code(204).send();
99
+ });
100
+ app.delete('/web/session', async (req, reply) => {
101
+ guard(req, deps);
102
+ const token = req.cookies[SESSION_COOKIE];
103
+ if (token)
104
+ await deps.webSessions.signOut(token);
105
+ reply.clearCookie(SESSION_COOKIE, cookieOptions(req));
106
+ return reply.code(204).send();
107
+ });
108
+ };
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { buildApp } from './app.js';
3
- import { createConfig } from './config.js';
3
+ import { createConfig, listenHost } from './config.js';
4
+ import { lanAddresses } from './lib/network.js';
4
5
  import { StartupError } from './lib/instance-lock.js';
5
6
  import { gatewayChecks } from './services/doctor.js';
6
7
  const config = createConfig();
7
8
  let built;
8
9
  let app;
9
10
  try {
10
- built = await buildApp({ config });
11
+ built = await buildApp({ config, detectNetwork: true });
11
12
  ({ app } = built);
12
13
  }
13
14
  catch (err) {
@@ -17,7 +18,7 @@ catch (err) {
17
18
  process.exit(1);
18
19
  }
19
20
  try {
20
- await app.listen({ host: config.HOST, port: config.PORT });
21
+ await app.listen({ host: listenHost(config), port: config.PORT });
21
22
  }
22
23
  catch (err) {
23
24
  await app.close(); // release storage and the lock before exiting
@@ -26,6 +27,12 @@ catch (err) {
26
27
  console.error(`Port ${config.PORT} is already in use. Stop the other program, or set PORT to a free one.`);
27
28
  process.exit(1);
28
29
  }
30
+ if (listenHost(config) !== config.HOST) {
31
+ const urls = lanAddresses().map((a) => `http://${a}:${config.PORT}`);
32
+ app.log.info({ phone: urls }, urls.length
33
+ ? `Phone access is on: phones on this Wi-Fi can pair with llm phone (${urls[0]}). Use it only on a Wi-Fi you trust: the connection is not encrypted.`
34
+ : 'Phone access is on, but this computer is not connected to a network.');
35
+ }
29
36
  // The same checks as `llm doctor`. Warn, don't fail: Ollama may start (or a model be
30
37
  // pulled) after the gateway, and requests then work without a restart.
31
38
  try {
@@ -0,0 +1,85 @@
1
+ // Browser sign-in for the web chat and paired phones. The rules, in one place:
2
+ // - `llm open` (holding an API key) asks for an 'open' code: 60 seconds, works once, and
3
+ // only on this computer itself, so a leaked link is useless from anywhere else.
4
+ // - `llm phone` or the laptop's page asks for a 'pair' code: 5 minutes (scanning takes
5
+ // time), works once, from the phone.
6
+ // - The page exchanges the code for a session token, sent back only as an HttpOnly cookie.
7
+ // The session remembers the device ("iPhone") and where it was created (local/network).
8
+ // - A session ends after 30 days without use; "last seen" is written at most once a minute.
9
+ // Codes and tokens are 256-bit random values; only their SHA-256 hashes are stored.
10
+ import { randomBytes } from 'node:crypto';
11
+ import { sha256 } from '../lib/hash.js';
12
+ export const CODE_TTL_MS = { open: 60_000, pair: 5 * 60_000 };
13
+ export const SESSION_IDLE_MS = 30 * 24 * 3_600_000;
14
+ const TOUCH_EVERY_MS = 60_000;
15
+ const token = () => randomBytes(32).toString('base64url');
16
+ /** A readable name for the devices list, from the browser's User-Agent. */
17
+ export function deviceName(userAgent) {
18
+ const ua = userAgent ?? '';
19
+ if (/iPhone/i.test(ua))
20
+ return 'iPhone';
21
+ if (/iPad/i.test(ua))
22
+ return 'iPad';
23
+ if (/Android/i.test(ua))
24
+ return /Mobile/i.test(ua) ? 'Android phone' : 'Android tablet';
25
+ if (/Macintosh|Mac OS X/i.test(ua))
26
+ return 'Mac';
27
+ if (/Windows/i.test(ua))
28
+ return 'Windows PC';
29
+ if (/Linux|CrOS/i.test(ua))
30
+ return 'Linux computer';
31
+ return 'Browser';
32
+ }
33
+ export class WebSessionService {
34
+ store;
35
+ now;
36
+ constructor(store, now = () => new Date()) {
37
+ this.store = store;
38
+ this.now = now;
39
+ }
40
+ async createCode(userId, purpose = 'open') {
41
+ const now = this.now();
42
+ const code = token();
43
+ const expiresAt = new Date(now.getTime() + CODE_TTL_MS[purpose]);
44
+ await this.store.deleteExpired(new Date(now.getTime() - 24 * 3_600_000)); // cheap housekeeping
45
+ await this.store.createCode(userId, sha256(code), expiresAt, purpose);
46
+ return { code, expiresAt };
47
+ }
48
+ /**
49
+ * Exchanges a code for a session. An 'open' code is consumed even when refused from the
50
+ * network, so a leaked link can't be retried from this computer by someone else either.
51
+ */
52
+ async redeem(code, from) {
53
+ const now = this.now();
54
+ const hit = await this.store.redeemCode(sha256(code), now);
55
+ if (!hit)
56
+ return { kind: 'invalid' };
57
+ if (hit.purpose === 'open' && !from.local)
58
+ return { kind: 'local_only' };
59
+ const raw = token();
60
+ await this.store.createSession(hit.userId, sha256(raw), now, new Date(now.getTime() + SESSION_IDLE_MS), {
61
+ name: deviceName(from.userAgent),
62
+ createdFrom: from.local ? 'local' : 'network',
63
+ });
64
+ return { kind: 'ok', token: raw, maxAgeSeconds: SESSION_IDLE_MS / 1000 };
65
+ }
66
+ async authenticate(rawToken) {
67
+ const now = this.now();
68
+ const s = await this.store.findActiveSession(sha256(rawToken), now);
69
+ if (!s)
70
+ return null;
71
+ if (now.getTime() - s.lastSeenAt.getTime() >= TOUCH_EVERY_MS) {
72
+ await this.store.touchSession(s.id, now, new Date(now.getTime() + SESSION_IDLE_MS));
73
+ }
74
+ return { userId: s.userId, sessionId: s.id, createdFrom: s.createdFrom };
75
+ }
76
+ signOut(rawToken) {
77
+ return this.store.revokeSession(sha256(rawToken), this.now());
78
+ }
79
+ devices(userId) {
80
+ return this.store.listSessions(userId, this.now());
81
+ }
82
+ revokeDevice(userId, sessionId) {
83
+ return this.store.revokeSessionById(userId, sessionId, this.now());
84
+ }
85
+ }
@@ -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,27 @@ 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
+ // 'open': `llm open` on this computer (60 s, redeemable only locally); 'pair': a phone (5 min)
76
+ purpose: text('purpose').notNull().default('open'),
77
+ expiresAt: ts('expires_at').notNull(),
78
+ usedAt: ts('used_at'),
79
+ createdAt: ts('created_at').notNull().defaultNow(),
80
+ });
81
+ export const webSessions = pgTable('web_sessions', {
82
+ id: uuid('id').primaryKey().defaultRandom(),
83
+ userId: uuid('user_id').notNull().references(() => users.id),
84
+ tokenHash: text('token_hash').notNull().unique(),
85
+ deviceName: text('device_name'), // "iPhone", "Mac": shown in the devices list
86
+ // 'local': signed in on the computer running the assistant; 'network': a paired phone
87
+ createdFrom: text('created_from').notNull().default('local'),
88
+ createdAt: ts('created_at').notNull().defaultNow(),
89
+ lastSeenAt: ts('last_seen_at').notNull(),
90
+ expiresAt: ts('expires_at').notNull(), // slides forward with use (idle timeout)
91
+ revokedAt: ts('revoked_at'),
92
+ }, (t) => [index('web_sessions_user_idx').on(t.userId)]);
@@ -0,0 +1,72 @@
1
+ import { and, desc, eq, gt, isNotNull, isNull, lt, or } from 'drizzle-orm';
2
+ import { webCodes, webSessions } from './schema.js';
3
+ export class PgWebSessionsStore {
4
+ db;
5
+ constructor(db) {
6
+ this.db = db;
7
+ }
8
+ async createCode(userId, codeHash, expiresAt, purpose) {
9
+ await this.db.insert(webCodes).values({ userId, codeHash, expiresAt, purpose });
10
+ }
11
+ async redeemCode(codeHash, now) {
12
+ // One UPDATE: two concurrent redeems can't both see "unused" (row lock on update).
13
+ const [row] = await this.db
14
+ .update(webCodes)
15
+ .set({ usedAt: now })
16
+ .where(and(eq(webCodes.codeHash, codeHash), isNull(webCodes.usedAt), gt(webCodes.expiresAt, now)))
17
+ .returning({ userId: webCodes.userId, purpose: webCodes.purpose });
18
+ return row ? { userId: row.userId, purpose: row.purpose } : null;
19
+ }
20
+ async createSession(userId, tokenHash, now, expiresAt, device) {
21
+ const [row] = await this.db
22
+ .insert(webSessions)
23
+ .values({ userId, tokenHash, lastSeenAt: now, expiresAt, deviceName: device.name, createdFrom: device.createdFrom })
24
+ .returning({ id: webSessions.id });
25
+ return row;
26
+ }
27
+ async findActiveSession(tokenHash, now) {
28
+ const [row] = await this.db
29
+ .select({ id: webSessions.id, userId: webSessions.userId, lastSeenAt: webSessions.lastSeenAt, createdFrom: webSessions.createdFrom })
30
+ .from(webSessions)
31
+ .where(and(eq(webSessions.tokenHash, tokenHash), isNull(webSessions.revokedAt), gt(webSessions.expiresAt, now)))
32
+ .limit(1);
33
+ return row ? { ...row, createdFrom: row.createdFrom } : null;
34
+ }
35
+ async touchSession(id, now, expiresAt) {
36
+ await this.db.update(webSessions).set({ lastSeenAt: now, expiresAt }).where(eq(webSessions.id, id));
37
+ }
38
+ async revokeSession(tokenHash, now) {
39
+ const rows = await this.db
40
+ .update(webSessions)
41
+ .set({ revokedAt: now })
42
+ .where(and(eq(webSessions.tokenHash, tokenHash), isNull(webSessions.revokedAt)))
43
+ .returning({ id: webSessions.id });
44
+ return rows.length > 0;
45
+ }
46
+ async listSessions(userId, now) {
47
+ const rows = await this.db
48
+ .select({
49
+ id: webSessions.id,
50
+ deviceName: webSessions.deviceName,
51
+ createdFrom: webSessions.createdFrom,
52
+ createdAt: webSessions.createdAt,
53
+ lastSeenAt: webSessions.lastSeenAt,
54
+ })
55
+ .from(webSessions)
56
+ .where(and(eq(webSessions.userId, userId), isNull(webSessions.revokedAt), gt(webSessions.expiresAt, now)))
57
+ .orderBy(desc(webSessions.lastSeenAt), desc(webSessions.id));
58
+ return rows.map((r) => ({ ...r, createdFrom: r.createdFrom }));
59
+ }
60
+ async revokeSessionById(userId, id, now) {
61
+ const rows = await this.db
62
+ .update(webSessions)
63
+ .set({ revokedAt: now })
64
+ .where(and(eq(webSessions.id, id), eq(webSessions.userId, userId), isNull(webSessions.revokedAt)))
65
+ .returning({ id: webSessions.id });
66
+ return rows.length > 0;
67
+ }
68
+ async deleteExpired(before) {
69
+ await this.db.delete(webCodes).where(or(lt(webCodes.expiresAt, before), isNotNull(webCodes.usedAt)));
70
+ await this.db.delete(webSessions).where(or(lt(webSessions.expiresAt, before), lt(webSessions.revokedAt, before)));
71
+ }
72
+ }