local-llm-gateway 0.2.0 → 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.
- package/CHANGELOG.md +18 -0
- package/README.md +22 -0
- package/cli/dist/api/client.js +12 -2
- package/cli/dist/commands/open.js +3 -2
- package/cli/dist/commands/phone.js +85 -0
- package/cli/dist/commands/start.js +3 -1
- package/cli/dist/index.js +13 -0
- package/cli/dist/qr.js +64 -0
- package/cli/dist/repl.js +1 -1
- package/dist/src/api/endpoints.js +31 -5
- package/dist/src/api/schemas.js +24 -0
- package/dist/src/app.js +17 -2
- package/dist/src/config.js +6 -0
- package/dist/src/lib/network.js +129 -0
- package/dist/src/plugins/auth.js +12 -4
- package/dist/src/routes/web-page.js +2 -1
- package/dist/src/routes/web-session.js +70 -14
- package/dist/src/server.js +10 -3
- package/dist/src/services/web-session.service.js +47 -12
- package/dist/src/storage/postgres/schema.js +5 -0
- package/dist/src/storage/postgres/web-sessions.js +31 -9
- package/dist/src/storage/sqlite/schema.js +5 -0
- package/dist/src/storage/sqlite/web-sessions.js +37 -11
- package/dist/web/assets/{index-CDL8Tl5X.css → index-BH2EiFDE.css} +1 -1
- package/dist/web/assets/index-C52qddcS.js +24 -0
- package/dist/web/index.html +4 -3
- package/drizzle/0004_married_frog_thor.sql +3 -0
- package/drizzle/meta/0004_snapshot.json +755 -0
- package/drizzle/meta/_journal.json +7 -0
- package/drizzle/sqlite/0002_dry_the_fallen.sql +3 -0
- package/drizzle/sqlite/meta/0002_snapshot.json +721 -0
- package/drizzle/sqlite/meta/_journal.json +7 -0
- package/package.json +3 -1
- package/dist/web/assets/index-C03RJbF2.js +0 -17
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 (2026-11-25)
|
|
4
|
+
|
|
5
|
+
- **Use it from your phone, no app.** `llm phone` (or **Phones & devices** in the page on
|
|
6
|
+
the computer) shows a QR code; the phone scans it and opens the same chat, signed in. Two
|
|
7
|
+
ways to connect: the same Wi-Fi (`llm start --phone`; not encrypted, home only) or
|
|
8
|
+
Tailscale (`tailscale serve --bg 3000`; encrypted, anywhere).
|
|
9
|
+
- **See and remove devices.** `llm devices` and the page list every signed-in browser and
|
|
10
|
+
phone; removing one signs it out at once. Only the computer running the assistant can
|
|
11
|
+
pair phones or remove other devices: a phone can never add more phones.
|
|
12
|
+
- An `llm open` link now works only on the computer itself, so a leaked link is useless.
|
|
13
|
+
- From the network, single-user mode serves only the page, sign-in and the API;
|
|
14
|
+
`/metrics`, `/readyz` and `/openapi.json` stay on the computer.
|
|
15
|
+
- Phone-friendly page: the conversation list becomes a drawer, room for the home bar.
|
|
16
|
+
- `llm phone` draws a QR code phones can read in macOS Terminal (no font characters when
|
|
17
|
+
the window is big enough); `llm phone --browser` shows it on the web page instead.
|
|
18
|
+
- Fixed: chats didn't show in Chrome (Android phones). Fixed: the page was cached for a
|
|
19
|
+
year, so browsers could keep an old version after an update.
|
|
20
|
+
|
|
3
21
|
## 0.2.0 (2026-11-24)
|
|
4
22
|
|
|
5
23
|
- **Web chat.** `llm open` opens the assistant in your browser at `http://localhost:3000`,
|
package/README.md
CHANGED
|
@@ -58,6 +58,28 @@ fix whatever is wrong.
|
|
|
58
58
|
| `llm backup` | Save a copy of all conversations |
|
|
59
59
|
| `llm restore <file>` | How to put a backup back |
|
|
60
60
|
| `llm stats` | Speed and token use |
|
|
61
|
+
| `llm phone` | Connect a phone: shows a QR code to scan |
|
|
62
|
+
| `llm devices` | Signed-in browsers and phones; `llm devices revoke <id>` removes one |
|
|
63
|
+
|
|
64
|
+
### Use it from your phone
|
|
65
|
+
|
|
66
|
+
No app needed: the phone opens the same chat page in its browser, and your conversations
|
|
67
|
+
are the same on both.
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
llm start --phone # also lets phones on this Wi-Fi connect
|
|
71
|
+
llm phone # shows a QR code: scan it with the phone's camera (works once, 5 minutes)
|
|
72
|
+
llm phone --browser # the same QR code on a web page, if the terminal one won't scan
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **Same Wi-Fi** (at home): the connection is not encrypted, so use it only on a Wi-Fi you
|
|
76
|
+
trust. Guest and many office networks block devices from reaching each other.
|
|
77
|
+
- **Anywhere, encrypted**: install [Tailscale](https://tailscale.com) on the computer and the
|
|
78
|
+
phone, then run `tailscale serve --bg 3000`. `llm phone` then uses the Tailscale address.
|
|
79
|
+
The assistant itself never opens a port on your network.
|
|
80
|
+
- **Lost a phone, or someone left?** `llm devices revoke <id>`, or **Phones & devices** in the
|
|
81
|
+
page on the computer. It is signed out at once. A phone can never pair other phones.
|
|
82
|
+
- The computer has to be awake and running the assistant.
|
|
61
83
|
|
|
62
84
|
### Where your data is
|
|
63
85
|
|
package/cli/dist/api/client.js
CHANGED
|
@@ -86,8 +86,18 @@ export class ApiClient {
|
|
|
86
86
|
return this.json('GET', '/v1/me');
|
|
87
87
|
}
|
|
88
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');
|
|
89
|
+
webCode(purpose = 'open') {
|
|
90
|
+
return this.json('POST', '/v1/web/codes', { purpose });
|
|
91
|
+
}
|
|
92
|
+
/** How a phone can reach this gateway (Wi-Fi addresses, Tailscale), and whether we may pair. */
|
|
93
|
+
phoneInfo() {
|
|
94
|
+
return this.json('GET', '/v1/web/phone');
|
|
95
|
+
}
|
|
96
|
+
devices() {
|
|
97
|
+
return this.json('GET', '/v1/web/sessions');
|
|
98
|
+
}
|
|
99
|
+
revokeDevice(id) {
|
|
100
|
+
return this.json('DELETE', `/v1/web/sessions/${encodeURIComponent(id)}`);
|
|
91
101
|
}
|
|
92
102
|
/** Asks the gateway to write a checked backup into its data folder. Single-user mode. */
|
|
93
103
|
backup() {
|
|
@@ -18,7 +18,8 @@ export function browserCommand(url, platform = process.platform) {
|
|
|
18
18
|
export async function openCommand(opts) {
|
|
19
19
|
const { baseUrl } = loadConfig();
|
|
20
20
|
const { code } = await getClient().webCode();
|
|
21
|
-
|
|
21
|
+
// show=phone: the page opens "Phones & devices", which shows the pairing QR as an image.
|
|
22
|
+
const url = `${baseUrl}/#code=${code}${opts.show ? `&show=${opts.show}` : ''}`;
|
|
22
23
|
if (!opts.print) {
|
|
23
24
|
const [cmd, args] = browserCommand(url);
|
|
24
25
|
const opened = await new Promise((done) => {
|
|
@@ -30,7 +31,7 @@ export async function openCommand(opts) {
|
|
|
30
31
|
});
|
|
31
32
|
});
|
|
32
33
|
if (opened) {
|
|
33
|
-
console.log(`Opening the assistant in your browser: ${baseUrl}`);
|
|
34
|
+
console.log(opts.show === 'phone' ? 'Showing the QR code in your browser ("Phones & devices").' : `Opening the assistant in your browser: ${baseUrl}`);
|
|
34
35
|
return;
|
|
35
36
|
}
|
|
36
37
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { terminalQr } from '../qr.js';
|
|
2
|
+
import { openCommand } from './open.js';
|
|
3
|
+
import { loadConfig } from '../config.js';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
import { out, relativeTime, shortId } from '../format.js';
|
|
6
|
+
import { getClient } from './shared.js';
|
|
7
|
+
/** Where a phone should go: Tailscale (HTTPS, anywhere) first, else the Wi-Fi address. */
|
|
8
|
+
export function phoneUrl(info) {
|
|
9
|
+
if (info.tailscale.serving && info.tailscale.url)
|
|
10
|
+
return { url: info.tailscale.url, via: 'tailscale' };
|
|
11
|
+
if (info.wifi.listening && info.wifi.urls[0])
|
|
12
|
+
return { url: info.wifi.urls[0], via: 'wifi' };
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
/** What to do when no phone can reach the assistant yet. */
|
|
16
|
+
export function howToEnable(info, port) {
|
|
17
|
+
const tailscale = info.tailscale.name
|
|
18
|
+
? `Tailscale is installed here (${info.tailscale.name}). Run: tailscale serve --bg ${port}`
|
|
19
|
+
: 'Install Tailscale on this computer and your phone (tailscale.com), sign in to both, then run: tailscale serve --bg ' + port;
|
|
20
|
+
return [
|
|
21
|
+
"Phones can't reach the assistant yet. Choose one:",
|
|
22
|
+
'',
|
|
23
|
+
' Same Wi-Fi (at home; the connection is not encrypted):',
|
|
24
|
+
' stop the assistant (Ctrl+C), then start it with: llm start --phone',
|
|
25
|
+
'',
|
|
26
|
+
' Anywhere, encrypted (Tailscale):',
|
|
27
|
+
` ${tailscale}`,
|
|
28
|
+
'',
|
|
29
|
+
'Then run llm phone again.',
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
32
|
+
export async function phoneCommand(opts) {
|
|
33
|
+
const client = getClient();
|
|
34
|
+
const info = await client.phoneInfo();
|
|
35
|
+
if (!info.canPair) {
|
|
36
|
+
throw new CliError("Phones can only be connected from the computer running the assistant.");
|
|
37
|
+
}
|
|
38
|
+
const target = phoneUrl(info);
|
|
39
|
+
if (!target)
|
|
40
|
+
throw new CliError(howToEnable(info, Number(new URL(loadConfig().baseUrl).port || 80)));
|
|
41
|
+
// The page's "Phones & devices" makes its own pairing code and shows the QR as an image.
|
|
42
|
+
if (opts.browser)
|
|
43
|
+
return openCommand({ show: 'phone' });
|
|
44
|
+
const { code } = await client.webCode('pair');
|
|
45
|
+
const link = `${target.url}/#code=${code}`;
|
|
46
|
+
if (opts.print)
|
|
47
|
+
return void console.log(link);
|
|
48
|
+
const qr = terminalQr(link, { columns: process.stdout.columns, rows: process.stdout.rows });
|
|
49
|
+
console.log(qr.text);
|
|
50
|
+
console.log("Scan this with your phone's camera. It works once, for 5 minutes.");
|
|
51
|
+
if (qr.mode === 'compact') {
|
|
52
|
+
// Some terminals (macOS Terminal with many fonts) leave thin gaps between lines here,
|
|
53
|
+
// which phones can't read. The sharp form has no such gaps but needs a bigger window.
|
|
54
|
+
const now = `${process.stdout.columns}x${process.stdout.rows}`;
|
|
55
|
+
console.log(out.yellow(`This window is small (${now}), so the code may not scan. Either:`));
|
|
56
|
+
console.log(out.yellow(` make the window at least ${qr.needs.columns}x${qr.needs.rows} (or shrink the text with Cmd -) and run llm phone again,`));
|
|
57
|
+
console.log(out.yellow(' or show it in your browser: llm phone --browser'));
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
console.log(out.dim("Won't scan? Show it in your browser: llm phone --browser"));
|
|
61
|
+
}
|
|
62
|
+
console.log(out.dim(` ${target.url} (${target.via === 'tailscale' ? 'Tailscale, encrypted, works anywhere' : 'same Wi-Fi only, not encrypted'})`));
|
|
63
|
+
console.log(out.dim('See or remove connected phones: llm devices'));
|
|
64
|
+
}
|
|
65
|
+
export async function devicesCommand() {
|
|
66
|
+
const { data } = await getClient().devices();
|
|
67
|
+
if (data.length === 0)
|
|
68
|
+
return void console.log(out.dim('No signed-in browsers or phones. Connect a phone with: llm phone'));
|
|
69
|
+
for (const d of data) {
|
|
70
|
+
const where = d.createdFrom === 'local' ? 'this computer' : 'paired device';
|
|
71
|
+
console.log(`${shortId(d.id)} ${(d.deviceName ?? 'Browser').padEnd(14)} ${where.padEnd(14)} ${out.dim(`last used ${relativeTime(d.lastSeenAt)}`)}`);
|
|
72
|
+
}
|
|
73
|
+
console.log(out.dim('\nRemove one (it is signed out at once): llm devices revoke <id>'));
|
|
74
|
+
}
|
|
75
|
+
export async function revokeDeviceCommand(idOrPrefix) {
|
|
76
|
+
const client = getClient();
|
|
77
|
+
const { data } = await client.devices();
|
|
78
|
+
const hits = data.filter((d) => d.id.startsWith(idOrPrefix));
|
|
79
|
+
if (hits.length === 0)
|
|
80
|
+
throw new CliError(`No signed-in device starts with "${idOrPrefix}". See: llm devices`);
|
|
81
|
+
if (hits.length > 1)
|
|
82
|
+
throw new CliError(`"${idOrPrefix}" matches ${hits.length} devices; use more characters.`);
|
|
83
|
+
await client.revokeDevice(hits[0].id);
|
|
84
|
+
console.log(`Removed ${hits[0].deviceName ?? 'the device'} (${shortId(hits[0].id)}). It is signed out.`);
|
|
85
|
+
}
|
|
@@ -21,7 +21,9 @@ export async function startCommand(opts) {
|
|
|
21
21
|
throw new CliError(`There is no file at ${file}.`);
|
|
22
22
|
args.push(`--env-file=${file}`);
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
// --phone: also listen on the local network so paired phones on this Wi-Fi can connect.
|
|
25
|
+
const env = opts.phone ? { ...process.env, PHONE_ACCESS: 'wifi' } : process.env;
|
|
26
|
+
const child = spawn(process.execPath, [...args, entry], { stdio: 'inherit', env });
|
|
25
27
|
// Pass stop signals on and wait, so the gateway always shuts down cleanly (releases its
|
|
26
28
|
// lock, closes the database). Ctrl+C in a terminal reaches both processes anyway; a
|
|
27
29
|
// signal sent to `llm` alone (a process manager, `kill`) must still reach the gateway.
|
package/cli/dist/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { backupCommand, restoreCommand } from './commands/backup.js';
|
|
|
7
7
|
import { doctorCommand } from './commands/doctor.js';
|
|
8
8
|
import { startCommand } from './commands/start.js';
|
|
9
9
|
import { openCommand } from './commands/open.js';
|
|
10
|
+
import { devicesCommand, phoneCommand, revokeDeviceCommand } from './commands/phone.js';
|
|
10
11
|
import { CliError } from './errors.js';
|
|
11
12
|
import { describeErrorFully } from './key-diagnosis.js';
|
|
12
13
|
import { errc } from './format.js';
|
|
@@ -84,9 +85,21 @@ program
|
|
|
84
85
|
.description('open the web chat in your browser, already signed in')
|
|
85
86
|
.option('--print', "print the sign-in link instead of opening the browser")
|
|
86
87
|
.action(wrap(openCommand));
|
|
88
|
+
program
|
|
89
|
+
.command('phone')
|
|
90
|
+
.description('connect a phone: shows a QR code to scan (works once, for 5 minutes)')
|
|
91
|
+
.option('--print', 'print the link instead of a QR code')
|
|
92
|
+
.option('--browser', 'show the QR code in your browser instead (if the terminal one will not scan)')
|
|
93
|
+
.action(wrap(phoneCommand));
|
|
94
|
+
const devices = program
|
|
95
|
+
.command('devices')
|
|
96
|
+
.description('signed-in browsers and phones; remove one with: llm devices revoke <id>')
|
|
97
|
+
.action(wrap(devicesCommand));
|
|
98
|
+
devices.command('revoke').argument('<id>', 'device id or its first characters').description('sign a device out').action(wrap(revokeDeviceCommand));
|
|
87
99
|
program
|
|
88
100
|
.command('start')
|
|
89
101
|
.description('start the assistant in this window (Ctrl+C stops it)')
|
|
102
|
+
.option('--phone', 'also let phones on this Wi-Fi connect (pair them with llm phone)')
|
|
90
103
|
.option('--env-file <path>', 'read settings from this file (for example server mode: DATABASE_URL, REDIS_URL)')
|
|
91
104
|
.action(wrap(startCommand));
|
|
92
105
|
program
|
package/cli/dist/qr.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import QRCode from 'qrcode';
|
|
2
|
+
// A QR code drawn in the terminal that phones can actually scan. The qrcode package's own
|
|
3
|
+
// terminal output uses the theme's "white" and "black" (often grey and dark grey) and only a
|
|
4
|
+
// 1-module border, so cameras often can't read it. Here:
|
|
5
|
+
// - pure black and white from the 256-colour cube (16 = #000000, 231 = #ffffff), which
|
|
6
|
+
// themes don't remap; black on white also passes any minimum-contrast setting unchanged;
|
|
7
|
+
// - a white border (quiet zone): 4 modules as the QR standard asks, 2 when space is short;
|
|
8
|
+
// - error correction L: the smallest code for the link, so each module is as big as possible.
|
|
9
|
+
//
|
|
10
|
+
// Two ways to draw it:
|
|
11
|
+
// - "sharp": each module is two spaces with a background colour. No font glyphs at all, so
|
|
12
|
+
// it can't break: terminals fill the background across the whole cell, line spacing
|
|
13
|
+
// included. macOS Terminal leaves gaps between lines of block characters with many fonts,
|
|
14
|
+
// which stripes a half-block QR code and makes Android scanners fail. Needs a big window
|
|
15
|
+
// (about 74 x 41 for a Wi-Fi link).
|
|
16
|
+
// - "compact": two modules per cell, '▀' with the top as foreground and the bottom as
|
|
17
|
+
// background. Half the height, but depends on the font drawing '▀' edge to edge.
|
|
18
|
+
const BLACK = 16;
|
|
19
|
+
const WHITE = 231;
|
|
20
|
+
/** The QR code for `text` as rows of dark (true) / light (false) modules, border included. */
|
|
21
|
+
export function qrMatrix(text, quiet = 4) {
|
|
22
|
+
const { modules } = QRCode.create(text, { errorCorrectionLevel: 'L' });
|
|
23
|
+
const n = modules.size + quiet * 2;
|
|
24
|
+
return Array.from({ length: n }, (_, y) => Array.from({ length: n }, (_, x) => {
|
|
25
|
+
const r = y - quiet;
|
|
26
|
+
const c = x - quiet;
|
|
27
|
+
return r >= 0 && c >= 0 && r < modules.size && c < modules.size && Boolean(modules.get(r, c));
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
const colour = (dark) => (dark ? BLACK : WHITE);
|
|
31
|
+
function sharp(m) {
|
|
32
|
+
return m.map((row) => row.map((dark) => `\x1b[48;5;${colour(dark)}m `).join('') + '\x1b[0m').join('\n');
|
|
33
|
+
}
|
|
34
|
+
function compact(m) {
|
|
35
|
+
const lines = [];
|
|
36
|
+
for (let y = 0; y < m.length; y += 2) {
|
|
37
|
+
let line = '';
|
|
38
|
+
for (let x = 0; x < m.length; x++) {
|
|
39
|
+
const top = m[y][x];
|
|
40
|
+
const bottom = y + 1 < m.length ? m[y + 1][x] : false;
|
|
41
|
+
line += `\x1b[38;5;${colour(top)}m\x1b[48;5;${colour(bottom)}m▀`;
|
|
42
|
+
}
|
|
43
|
+
lines.push(`${line}\x1b[0m`);
|
|
44
|
+
}
|
|
45
|
+
return lines.join('\n');
|
|
46
|
+
}
|
|
47
|
+
/** Lines printed under the code (instructions); the sharp code must leave room for them. */
|
|
48
|
+
const LINES_BELOW = 5; // 4 lines of text, then the shell prompt
|
|
49
|
+
/**
|
|
50
|
+
* Terminal text for the QR code: the sharp form when the window has room for it (4-module
|
|
51
|
+
* border, else 2), otherwise the compact form. `window` is the terminal size; without one
|
|
52
|
+
* (output piped to a file) the sharp form is used.
|
|
53
|
+
*/
|
|
54
|
+
export function terminalQr(text, window) {
|
|
55
|
+
const smallest = qrMatrix(text, 2).length;
|
|
56
|
+
const needs = { columns: smallest * 2, rows: smallest + LINES_BELOW }; // the smallest sharp form
|
|
57
|
+
for (const quiet of [4, 2]) {
|
|
58
|
+
const m = qrMatrix(text, quiet);
|
|
59
|
+
const fits = !window?.columns || !window.rows || (m.length * 2 <= window.columns && m.length + LINES_BELOW <= window.rows);
|
|
60
|
+
if (fits)
|
|
61
|
+
return { text: sharp(m), mode: 'sharp', needs };
|
|
62
|
+
}
|
|
63
|
+
return { text: compact(qrMatrix(text, 4)), mode: 'compact', needs };
|
|
64
|
+
}
|
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 = 'open|profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
|
|
34
|
+
const LLM_SUBCOMMANDS = 'open|phone|devices|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) {
|
|
@@ -83,15 +83,41 @@ export const ENDPOINTS = [
|
|
|
83
83
|
},
|
|
84
84
|
// ---- web sign-in ----
|
|
85
85
|
{
|
|
86
|
-
method: 'post', path: '/v1/web/codes', tag: 'web', auth: true,
|
|
87
|
-
summary: 'Make a one-time sign-in code
|
|
88
|
-
description: 'API key only
|
|
86
|
+
method: 'post', path: '/v1/web/codes', tag: 'web', auth: true,
|
|
87
|
+
summary: 'Make a one-time sign-in code (llm open) or a phone pairing code (llm phone)',
|
|
88
|
+
description: "'open' (default): API key only; works once, for 60 seconds, and only on this computer. " +
|
|
89
|
+
"'pair': an API key or a browser on this computer; works once, for 5 minutes, from a phone. A paired phone can't make codes.",
|
|
90
|
+
body: S.WebCodeBody,
|
|
89
91
|
responses: {
|
|
90
92
|
201: { description: 'A code', schema: S.WebCode },
|
|
93
|
+
...INVALID,
|
|
94
|
+
...AUTH_ERRORS,
|
|
95
|
+
403: err('Not allowed from this caller (`key_required`, `pair_from_computer`)'),
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
method: 'get', path: '/v1/web/sessions', tag: 'web', auth: true,
|
|
100
|
+
summary: 'Signed-in devices: this computer\'s browser and paired phones',
|
|
101
|
+
responses: { 200: { description: 'Devices, most recently used first', schema: S.DeviceList }, ...AUTH_ERRORS },
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
method: 'delete', path: '/v1/web/sessions/{id}', tag: 'web', auth: true,
|
|
105
|
+
summary: 'Remove a device: it is signed out on its next request',
|
|
106
|
+
description: 'From this computer (API key or its browser) any device; a phone only itself.',
|
|
107
|
+
params: S.IdParams,
|
|
108
|
+
responses: {
|
|
109
|
+
204: { description: 'Removed' },
|
|
110
|
+
...INVALID,
|
|
91
111
|
...AUTH_ERRORS,
|
|
92
|
-
403: err('
|
|
112
|
+
403: err('A phone removing another device (`manage_from_computer`)'),
|
|
113
|
+
404: err('No such signed-in device (`device_not_found`)'),
|
|
93
114
|
},
|
|
94
115
|
},
|
|
116
|
+
{
|
|
117
|
+
method: 'get', path: '/v1/web/phone', tag: 'web', auth: true,
|
|
118
|
+
summary: 'How a phone can reach this assistant (for the pairing QR code)',
|
|
119
|
+
responses: { 200: { description: 'Addresses and whether this caller may pair', schema: S.PhoneInfo }, ...AUTH_ERRORS },
|
|
120
|
+
},
|
|
95
121
|
{
|
|
96
122
|
method: 'post', path: '/web/session', tag: 'web', auth: false,
|
|
97
123
|
summary: 'Exchange a sign-in code for a session cookie',
|
|
@@ -102,7 +128,7 @@ export const ENDPOINTS = [
|
|
|
102
128
|
204: { description: 'Signed in: the session cookie is set' },
|
|
103
129
|
...INVALID,
|
|
104
130
|
401: err('The code is unknown, used or expired (`invalid_code`)'),
|
|
105
|
-
403: err('Wrong host or origin (`forbidden_host`, `bad_origin`)'),
|
|
131
|
+
403: err('Wrong host or origin (`forbidden_host`, `bad_origin`), or an llm open link used from another device (`open_link_local_only`)'),
|
|
106
132
|
},
|
|
107
133
|
},
|
|
108
134
|
{
|
package/dist/src/api/schemas.js
CHANGED
|
@@ -53,6 +53,9 @@ 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 WebCodeBody = z.object({
|
|
57
|
+
purpose: z.enum(['open', 'pair']).default('open').describe("'open': this computer's browser (llm open); 'pair': a phone (llm phone)"),
|
|
58
|
+
});
|
|
56
59
|
export const RedeemCodeBody = z.object({ code: z.string().min(16).max(200).describe('The one-time code from the sign-in link') });
|
|
57
60
|
export const LegacyChatBody = z.object({
|
|
58
61
|
model: z.string(),
|
|
@@ -143,6 +146,27 @@ export const BackupSummary = named(z.strictObject({
|
|
|
143
146
|
createdAt: timestamp,
|
|
144
147
|
}), 'BackupSummary');
|
|
145
148
|
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');
|
|
149
|
+
export const Device = named(z.strictObject({
|
|
150
|
+
id: z.uuid(),
|
|
151
|
+
deviceName: z.string().nullable().describe('From the browser, e.g. "iPhone"'),
|
|
152
|
+
createdFrom: z.enum(['local', 'network']).describe("'local': signed in on the computer running the assistant; 'network': a paired device"),
|
|
153
|
+
createdAt: timestamp,
|
|
154
|
+
lastSeenAt: timestamp,
|
|
155
|
+
current: z.boolean().describe('The device making this request'),
|
|
156
|
+
}), 'Device', 'A browser signed in to this account: the laptop, or a paired phone');
|
|
157
|
+
export const DeviceList = named(z.strictObject({ data: z.array(Device) }), 'DeviceList');
|
|
158
|
+
export const PhoneInfo = named(z.strictObject({
|
|
159
|
+
canPair: z.boolean().describe('Whether this caller may create pairing codes (an API key, or the computer itself)'),
|
|
160
|
+
wifi: z.strictObject({
|
|
161
|
+
listening: z.boolean().describe('Started with phone access (llm start --phone)'),
|
|
162
|
+
urls: z.array(z.string()).describe('Addresses a phone on the same Wi-Fi can open'),
|
|
163
|
+
}),
|
|
164
|
+
tailscale: z.strictObject({
|
|
165
|
+
name: z.string().nullable(),
|
|
166
|
+
url: z.string().nullable(),
|
|
167
|
+
serving: z.boolean().describe('tailscale serve forwards to this gateway'),
|
|
168
|
+
}),
|
|
169
|
+
}), 'PhoneInfo', 'How a phone can reach this assistant');
|
|
146
170
|
export const Health = named(z.strictObject({ ok: z.literal(true), mode: z.enum(['single', 'server']) }), 'Health');
|
|
147
171
|
export const Readiness = named(z.strictObject({ ok: z.boolean(), ollama: z.boolean(), db: z.boolean() }), 'Readiness');
|
|
148
172
|
export const LegacyChatResponse = named(z.looseObject({}).describe('OpenAI-compatible chat completion, passed through from Ollama'), 'LegacyChatResponse');
|
package/dist/src/app.js
CHANGED
|
@@ -30,6 +30,7 @@ import { backupRoutes } from './routes/backup.js';
|
|
|
30
30
|
import { webCodeRoutes, webSessionRoutes } from './routes/web-session.js';
|
|
31
31
|
import { webPageRoutes } from './routes/web-page.js';
|
|
32
32
|
import { findWebRoot } from './lib/web-root.js';
|
|
33
|
+
import { isLocalRequest, WebHosts } from './lib/network.js';
|
|
33
34
|
import { WebSessionService } from './services/web-session.service.js';
|
|
34
35
|
export async function buildApp(opts = {}) {
|
|
35
36
|
const config = opts.config ?? createConfig();
|
|
@@ -49,6 +50,19 @@ export async function buildApp(opts = {}) {
|
|
|
49
50
|
if (method !== 'HEAD')
|
|
50
51
|
routes.push({ method, url: r.url });
|
|
51
52
|
});
|
|
53
|
+
// Single-user mode, request from the network (a paired phone, or through Tailscale): only
|
|
54
|
+
// what the phone needs. Metrics, readiness and the API description stay on this computer.
|
|
55
|
+
if (config.mode === 'single') {
|
|
56
|
+
app.addHook('onRequest', async (req, reply) => {
|
|
57
|
+
if (isLocalRequest(req))
|
|
58
|
+
return;
|
|
59
|
+
const path = req.url.split('?')[0];
|
|
60
|
+
const allowed = path === '/' || path.startsWith('/assets/') || path === '/web/session' || path.startsWith('/v1/') || path === '/healthz';
|
|
61
|
+
if (!allowed) {
|
|
62
|
+
return reply.code(404).send({ error: { code: 'not_found', message: `There is no ${req.method} ${path}.`, request_id: req.id } });
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
52
66
|
// Unknown URLs get the same error shape as everything else.
|
|
53
67
|
app.setNotFoundHandler((req, reply) => reply.code(404).send({
|
|
54
68
|
error: { code: 'not_found', message: `There is no ${req.method} ${req.url.split('?')[0]}.`, request_id: req.id },
|
|
@@ -100,6 +114,7 @@ export async function buildApp(opts = {}) {
|
|
|
100
114
|
const ollama = opts.ollama ?? new OllamaModels(config.OLLAMA_URL);
|
|
101
115
|
const auth = new AuthService(repos.apiKeys);
|
|
102
116
|
const webSessions = new WebSessionService(storage.webSessions);
|
|
117
|
+
const webHosts = new WebHosts({ extra: config.webHosts, detect: opts.detectNetwork ?? false, port: config.PORT, fixed: opts.networkHosts });
|
|
103
118
|
const models = new ModelsService({
|
|
104
119
|
...config.models,
|
|
105
120
|
source: ollama,
|
|
@@ -121,7 +136,7 @@ export async function buildApp(opts = {}) {
|
|
|
121
136
|
messages: repos.messages,
|
|
122
137
|
generations: repos.generations,
|
|
123
138
|
});
|
|
124
|
-
const deps = { config, storage, limiter, metrics, provider, ollama, auth, webSessions, conversations, models, repos };
|
|
139
|
+
const deps = { config, storage, limiter, metrics, provider, ollama, auth, webSessions, webHosts, conversations, models, repos };
|
|
125
140
|
let redis = null;
|
|
126
141
|
if (config.REDIS_URL) {
|
|
127
142
|
redis = new Redis(config.REDIS_URL, {
|
|
@@ -167,7 +182,7 @@ export async function buildApp(opts = {}) {
|
|
|
167
182
|
await app.register(webSessionRoutes, { deps });
|
|
168
183
|
await app.register(webPageRoutes, { root: opts.webRoot === undefined ? findWebRoot() : opts.webRoot });
|
|
169
184
|
await app.register(async (v1) => {
|
|
170
|
-
v1.addHook('onRequest', makeAuthHook(auth, webSessions,
|
|
185
|
+
v1.addHook('onRequest', makeAuthHook(auth, webSessions, webHosts)); // auth first, so rate limiting can key on the key id
|
|
171
186
|
await v1.register(rateLimit, {
|
|
172
187
|
max: config.RATE_LIMIT_MAX,
|
|
173
188
|
timeWindow: config.RATE_LIMIT_WINDOW,
|
package/dist/src/config.js
CHANGED
|
@@ -26,6 +26,8 @@ const Env = z.object({
|
|
|
26
26
|
LEASE_SECONDS: z.coerce.number().int().positive().default(180),
|
|
27
27
|
// Extra host names the web page may be reached by (comma-separated), beyond localhost.
|
|
28
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')),
|
|
29
31
|
});
|
|
30
32
|
const list = (s) => s.split(',').map((x) => x.trim()).filter(Boolean);
|
|
31
33
|
/** Where single-user mode keeps its database, following each OS's convention. */
|
|
@@ -55,3 +57,7 @@ export function createConfig(env = process.env) {
|
|
|
55
57
|
},
|
|
56
58
|
};
|
|
57
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
|
+
}
|
package/dist/src/plugins/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestHost } from '../lib/network.js';
|
|
1
2
|
import { allowedHost, SAFE_METHODS, sameOrigin, SESSION_COOKIE } from './web-guard.js';
|
|
2
3
|
const deny = (req, reply, status, code, message, hint) => reply.code(status).send({ error: { code, message, ...(hint ? { hint } : {}), request_id: req.id } });
|
|
3
4
|
/**
|
|
@@ -5,7 +6,7 @@ const deny = (req, reply, status, code, message, hint) => reply.code(status).sen
|
|
|
5
6
|
* page, a session cookie. A key always wins. Cookie requests must also pass the host and
|
|
6
7
|
* origin checks (see web-guard.ts).
|
|
7
8
|
*/
|
|
8
|
-
export function makeAuthHook(auth, web,
|
|
9
|
+
export function makeAuthHook(auth, web, hosts) {
|
|
9
10
|
return async function requireAuth(req, reply) {
|
|
10
11
|
const header = req.headers.authorization;
|
|
11
12
|
const key = header?.startsWith('Bearer ') ? header.slice(7).trim() : undefined;
|
|
@@ -18,15 +19,22 @@ export function makeAuthHook(auth, web, webHosts) {
|
|
|
18
19
|
}
|
|
19
20
|
const token = req.cookies?.[SESSION_COOKIE];
|
|
20
21
|
if (token) {
|
|
21
|
-
|
|
22
|
+
const host = requestHost(req); // behind `tailscale serve`, the host the phone used
|
|
23
|
+
if (!allowedHost(host, hosts.list())) {
|
|
22
24
|
return deny(req, reply, 403, 'forbidden_host', 'This address is not allowed to use a signed-in session.');
|
|
23
25
|
}
|
|
24
|
-
if (!SAFE_METHODS.has(req.method) && !sameOrigin(req.headers.origin,
|
|
26
|
+
if (!SAFE_METHODS.has(req.method) && !sameOrigin(req.headers.origin, host)) {
|
|
25
27
|
return deny(req, reply, 403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
|
|
26
28
|
}
|
|
27
29
|
const session = await web.authenticate(token);
|
|
28
30
|
if (session) {
|
|
29
|
-
req.auth = {
|
|
31
|
+
req.auth = {
|
|
32
|
+
userId: session.userId,
|
|
33
|
+
keyId: `session:${session.sessionId}`,
|
|
34
|
+
via: 'session',
|
|
35
|
+
sessionId: session.sessionId,
|
|
36
|
+
sessionFrom: session.createdFrom,
|
|
37
|
+
};
|
|
30
38
|
return;
|
|
31
39
|
}
|
|
32
40
|
return deny(req, reply, 401, 'session_expired', 'Your sign-in has ended.', 'Sign in again: run llm open');
|
|
@@ -37,6 +37,7 @@ export const webPageRoutes = async (app, { root }) => {
|
|
|
37
37
|
throw new AppError(404, 'page_not_built', "The web page isn't built.", { hint: 'Run: npm run build (or use llm chat)' });
|
|
38
38
|
}
|
|
39
39
|
securityHeaders(reply).header('cache-control', 'no-cache'); // always pick up a new version
|
|
40
|
-
|
|
40
|
+
// cacheControl: false, or sendFile would replace no-cache with the assets' one-year rule.
|
|
41
|
+
return reply.sendFile('index.html', root, { cacheControl: false });
|
|
41
42
|
});
|
|
42
43
|
};
|