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
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
import { RedeemCodeBody } from '../api/schemas.js';
|
|
1
|
+
import { IdParams, RedeemCodeBody, WebCodeBody } from '../api/schemas.js';
|
|
2
2
|
import { AppError } from '../lib/errors.js';
|
|
3
|
+
import { isLocalRequest, lanAddresses, requestHost, requestProtocol } from '../lib/network.js';
|
|
3
4
|
import { allowedHost, sameOrigin, SESSION_COOKIE } from '../plugins/web-guard.js';
|
|
5
|
+
import { listenHost } from '../config.js';
|
|
4
6
|
/** Sign-in and sign-out are reached from the page: the same host and origin rules apply. */
|
|
5
|
-
function guard(req,
|
|
6
|
-
|
|
7
|
+
function guard(req, deps) {
|
|
8
|
+
const host = requestHost(req);
|
|
9
|
+
if (!allowedHost(host, deps.webHosts.list())) {
|
|
7
10
|
throw new AppError(403, 'forbidden_host', 'This address is not allowed to sign in.');
|
|
8
11
|
}
|
|
9
12
|
// 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,
|
|
13
|
+
if (req.headers.origin !== undefined && !sameOrigin(req.headers.origin, host)) {
|
|
11
14
|
throw new AppError(403, 'bad_origin', 'This request did not come from the assistant\'s own page.');
|
|
12
15
|
}
|
|
13
16
|
}
|
|
@@ -15,34 +18,87 @@ const cookieOptions = (req) => ({
|
|
|
15
18
|
httpOnly: true, // the page's scripts can't read it, so injected scripts can't steal it
|
|
16
19
|
sameSite: 'strict', // other sites' requests don't carry it
|
|
17
20
|
path: '/',
|
|
18
|
-
|
|
21
|
+
// HTTPS (e.g. through Tailscale): Secure. http://localhost or Wi-Fi: no TLS to require.
|
|
22
|
+
secure: requestProtocol(req, req.protocol) === 'https',
|
|
19
23
|
});
|
|
20
|
-
/**
|
|
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. */
|
|
21
31
|
export const webCodeRoutes = async (app, { deps }) => {
|
|
22
32
|
app.post('/web/codes', async (req, reply) => {
|
|
23
|
-
|
|
33
|
+
const { purpose } = WebCodeBody.parse(req.body ?? {});
|
|
34
|
+
if (purpose === 'open' && req.auth?.via !== 'key') {
|
|
24
35
|
throw new AppError(403, 'key_required', 'Only an API key can create a sign-in link.', { hint: 'Run llm open in a terminal.' });
|
|
25
36
|
}
|
|
26
|
-
|
|
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);
|
|
27
43
|
return reply.code(201).send({ code, expiresAt: expiresAt.toISOString() });
|
|
28
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
|
+
});
|
|
29
80
|
};
|
|
30
81
|
/** POST and DELETE /web/session: public paths (the page has no key), guarded by host and origin. */
|
|
31
82
|
export const webSessionRoutes = async (app, { deps }) => {
|
|
32
83
|
app.post('/web/session', async (req, reply) => {
|
|
33
|
-
guard(req, deps
|
|
84
|
+
guard(req, deps);
|
|
34
85
|
const { code } = RedeemCodeBody.parse(req.body);
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
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') {
|
|
37
93
|
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.',
|
|
94
|
+
hint: 'Run llm open again for a new one (llm phone for a phone).',
|
|
39
95
|
});
|
|
40
96
|
}
|
|
41
|
-
reply.setCookie(SESSION_COOKIE,
|
|
97
|
+
reply.setCookie(SESSION_COOKIE, result.token, { ...cookieOptions(req), maxAge: result.maxAgeSeconds });
|
|
42
98
|
return reply.code(204).send();
|
|
43
99
|
});
|
|
44
100
|
app.delete('/web/session', async (req, reply) => {
|
|
45
|
-
guard(req, deps
|
|
101
|
+
guard(req, deps);
|
|
46
102
|
const token = req.cookies[SESSION_COOKIE];
|
|
47
103
|
if (token)
|
|
48
104
|
await deps.webSessions.signOut(token);
|
package/dist/src/server.js
CHANGED
|
@@ -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
|
|
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 {
|
|
@@ -1,14 +1,35 @@
|
|
|
1
|
-
// Browser sign-in for the web chat. The rules, in one place:
|
|
2
|
-
// - `llm open` (holding an API key) asks for
|
|
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.
|
|
3
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).
|
|
4
8
|
// - A session ends after 30 days without use; "last seen" is written at most once a minute.
|
|
5
9
|
// Codes and tokens are 256-bit random values; only their SHA-256 hashes are stored.
|
|
6
10
|
import { randomBytes } from 'node:crypto';
|
|
7
11
|
import { sha256 } from '../lib/hash.js';
|
|
8
|
-
export const CODE_TTL_MS = 60_000;
|
|
12
|
+
export const CODE_TTL_MS = { open: 60_000, pair: 5 * 60_000 };
|
|
9
13
|
export const SESSION_IDLE_MS = 30 * 24 * 3_600_000;
|
|
10
14
|
const TOUCH_EVERY_MS = 60_000;
|
|
11
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
|
+
}
|
|
12
33
|
export class WebSessionService {
|
|
13
34
|
store;
|
|
14
35
|
now;
|
|
@@ -16,23 +37,31 @@ export class WebSessionService {
|
|
|
16
37
|
this.store = store;
|
|
17
38
|
this.now = now;
|
|
18
39
|
}
|
|
19
|
-
async createCode(userId) {
|
|
40
|
+
async createCode(userId, purpose = 'open') {
|
|
20
41
|
const now = this.now();
|
|
21
42
|
const code = token();
|
|
22
|
-
const expiresAt = new Date(now.getTime() + CODE_TTL_MS);
|
|
43
|
+
const expiresAt = new Date(now.getTime() + CODE_TTL_MS[purpose]);
|
|
23
44
|
await this.store.deleteExpired(new Date(now.getTime() - 24 * 3_600_000)); // cheap housekeeping
|
|
24
|
-
await this.store.createCode(userId, sha256(code), expiresAt);
|
|
45
|
+
await this.store.createCode(userId, sha256(code), expiresAt, purpose);
|
|
25
46
|
return { code, expiresAt };
|
|
26
47
|
}
|
|
27
|
-
/**
|
|
28
|
-
|
|
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) {
|
|
29
53
|
const now = this.now();
|
|
30
54
|
const hit = await this.store.redeemCode(sha256(code), now);
|
|
31
55
|
if (!hit)
|
|
32
|
-
return
|
|
56
|
+
return { kind: 'invalid' };
|
|
57
|
+
if (hit.purpose === 'open' && !from.local)
|
|
58
|
+
return { kind: 'local_only' };
|
|
33
59
|
const raw = token();
|
|
34
|
-
await this.store.createSession(hit.userId, sha256(raw), now, new Date(now.getTime() + SESSION_IDLE_MS)
|
|
35
|
-
|
|
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 };
|
|
36
65
|
}
|
|
37
66
|
async authenticate(rawToken) {
|
|
38
67
|
const now = this.now();
|
|
@@ -42,9 +71,15 @@ export class WebSessionService {
|
|
|
42
71
|
if (now.getTime() - s.lastSeenAt.getTime() >= TOUCH_EVERY_MS) {
|
|
43
72
|
await this.store.touchSession(s.id, now, new Date(now.getTime() + SESSION_IDLE_MS));
|
|
44
73
|
}
|
|
45
|
-
return { userId: s.userId, sessionId: s.id };
|
|
74
|
+
return { userId: s.userId, sessionId: s.id, createdFrom: s.createdFrom };
|
|
46
75
|
}
|
|
47
76
|
signOut(rawToken) {
|
|
48
77
|
return this.store.revokeSession(sha256(rawToken), this.now());
|
|
49
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
|
+
}
|
|
50
85
|
}
|
|
@@ -72,6 +72,8 @@ export const webCodes = pgTable('web_codes', {
|
|
|
72
72
|
id: uuid('id').primaryKey().defaultRandom(),
|
|
73
73
|
userId: uuid('user_id').notNull().references(() => users.id),
|
|
74
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'),
|
|
75
77
|
expiresAt: ts('expires_at').notNull(),
|
|
76
78
|
usedAt: ts('used_at'),
|
|
77
79
|
createdAt: ts('created_at').notNull().defaultNow(),
|
|
@@ -80,6 +82,9 @@ export const webSessions = pgTable('web_sessions', {
|
|
|
80
82
|
id: uuid('id').primaryKey().defaultRandom(),
|
|
81
83
|
userId: uuid('user_id').notNull().references(() => users.id),
|
|
82
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'),
|
|
83
88
|
createdAt: ts('created_at').notNull().defaultNow(),
|
|
84
89
|
lastSeenAt: ts('last_seen_at').notNull(),
|
|
85
90
|
expiresAt: ts('expires_at').notNull(), // slides forward with use (idle timeout)
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { and, eq, gt, isNotNull, isNull, lt, or } from 'drizzle-orm';
|
|
1
|
+
import { and, desc, eq, gt, isNotNull, isNull, lt, or } from 'drizzle-orm';
|
|
2
2
|
import { webCodes, webSessions } from './schema.js';
|
|
3
3
|
export class PgWebSessionsStore {
|
|
4
4
|
db;
|
|
5
5
|
constructor(db) {
|
|
6
6
|
this.db = db;
|
|
7
7
|
}
|
|
8
|
-
async createCode(userId, codeHash, expiresAt) {
|
|
9
|
-
await this.db.insert(webCodes).values({ userId, codeHash, expiresAt });
|
|
8
|
+
async createCode(userId, codeHash, expiresAt, purpose) {
|
|
9
|
+
await this.db.insert(webCodes).values({ userId, codeHash, expiresAt, purpose });
|
|
10
10
|
}
|
|
11
11
|
async redeemCode(codeHash, now) {
|
|
12
12
|
// One UPDATE: two concurrent redeems can't both see "unused" (row lock on update).
|
|
@@ -14,23 +14,23 @@ export class PgWebSessionsStore {
|
|
|
14
14
|
.update(webCodes)
|
|
15
15
|
.set({ usedAt: now })
|
|
16
16
|
.where(and(eq(webCodes.codeHash, codeHash), isNull(webCodes.usedAt), gt(webCodes.expiresAt, now)))
|
|
17
|
-
.returning({ userId: webCodes.userId });
|
|
18
|
-
return row
|
|
17
|
+
.returning({ userId: webCodes.userId, purpose: webCodes.purpose });
|
|
18
|
+
return row ? { userId: row.userId, purpose: row.purpose } : null;
|
|
19
19
|
}
|
|
20
|
-
async createSession(userId, tokenHash, now, expiresAt) {
|
|
20
|
+
async createSession(userId, tokenHash, now, expiresAt, device) {
|
|
21
21
|
const [row] = await this.db
|
|
22
22
|
.insert(webSessions)
|
|
23
|
-
.values({ userId, tokenHash, lastSeenAt: now, expiresAt })
|
|
23
|
+
.values({ userId, tokenHash, lastSeenAt: now, expiresAt, deviceName: device.name, createdFrom: device.createdFrom })
|
|
24
24
|
.returning({ id: webSessions.id });
|
|
25
25
|
return row;
|
|
26
26
|
}
|
|
27
27
|
async findActiveSession(tokenHash, now) {
|
|
28
28
|
const [row] = await this.db
|
|
29
|
-
.select({ id: webSessions.id, userId: webSessions.userId, lastSeenAt: webSessions.lastSeenAt })
|
|
29
|
+
.select({ id: webSessions.id, userId: webSessions.userId, lastSeenAt: webSessions.lastSeenAt, createdFrom: webSessions.createdFrom })
|
|
30
30
|
.from(webSessions)
|
|
31
31
|
.where(and(eq(webSessions.tokenHash, tokenHash), isNull(webSessions.revokedAt), gt(webSessions.expiresAt, now)))
|
|
32
32
|
.limit(1);
|
|
33
|
-
return row
|
|
33
|
+
return row ? { ...row, createdFrom: row.createdFrom } : null;
|
|
34
34
|
}
|
|
35
35
|
async touchSession(id, now, expiresAt) {
|
|
36
36
|
await this.db.update(webSessions).set({ lastSeenAt: now, expiresAt }).where(eq(webSessions.id, id));
|
|
@@ -43,6 +43,28 @@ export class PgWebSessionsStore {
|
|
|
43
43
|
.returning({ id: webSessions.id });
|
|
44
44
|
return rows.length > 0;
|
|
45
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
|
+
}
|
|
46
68
|
async deleteExpired(before) {
|
|
47
69
|
await this.db.delete(webCodes).where(or(lt(webCodes.expiresAt, before), isNotNull(webCodes.usedAt)));
|
|
48
70
|
await this.db.delete(webSessions).where(or(lt(webSessions.expiresAt, before), lt(webSessions.revokedAt, before)));
|
|
@@ -77,6 +77,8 @@ export const webCodes = sqliteTable('web_codes', {
|
|
|
77
77
|
id: id(),
|
|
78
78
|
userId: text('user_id').notNull().references(() => users.id),
|
|
79
79
|
codeHash: text('code_hash').notNull().unique(),
|
|
80
|
+
// 'open': `llm open` on this computer (60 s, redeemable only locally); 'pair': a phone (5 min)
|
|
81
|
+
purpose: text('purpose').notNull().default('open'),
|
|
80
82
|
expiresAt: ms('expires_at').notNull(),
|
|
81
83
|
usedAt: ms('used_at'),
|
|
82
84
|
createdAt: createdAt(),
|
|
@@ -85,6 +87,9 @@ export const webSessions = sqliteTable('web_sessions', {
|
|
|
85
87
|
id: id(),
|
|
86
88
|
userId: text('user_id').notNull().references(() => users.id),
|
|
87
89
|
tokenHash: text('token_hash').notNull().unique(),
|
|
90
|
+
deviceName: text('device_name'), // "iPhone", "Mac": shown in the devices list
|
|
91
|
+
// 'local': signed in on the computer running the assistant; 'network': a paired phone
|
|
92
|
+
createdFrom: text('created_from').notNull().default('local'),
|
|
88
93
|
createdAt: createdAt(),
|
|
89
94
|
lastSeenAt: ms('last_seen_at').notNull(),
|
|
90
95
|
expiresAt: ms('expires_at').notNull(), // slides forward with use (idle timeout)
|
|
@@ -1,35 +1,37 @@
|
|
|
1
|
-
import { and, eq, gt, isNotNull, isNull, lt, or } from 'drizzle-orm';
|
|
1
|
+
import { and, desc, eq, gt, isNotNull, isNull, lt, or } from 'drizzle-orm';
|
|
2
2
|
import { webCodes, webSessions } from './schema.js';
|
|
3
3
|
export class SqliteWebSessionsStore {
|
|
4
4
|
db;
|
|
5
5
|
constructor(db) {
|
|
6
6
|
this.db = db;
|
|
7
7
|
}
|
|
8
|
-
async createCode(userId, codeHash, expiresAt) {
|
|
9
|
-
this.db.insert(webCodes).values({ userId, codeHash, expiresAt }).run();
|
|
8
|
+
async createCode(userId, codeHash, expiresAt, purpose) {
|
|
9
|
+
this.db.insert(webCodes).values({ userId, codeHash, expiresAt, purpose }).run();
|
|
10
10
|
}
|
|
11
11
|
async redeemCode(codeHash, now) {
|
|
12
12
|
// One UPDATE ... RETURNING: SQLite runs it as a single write, so a code works once.
|
|
13
|
-
|
|
13
|
+
const row = this.db
|
|
14
14
|
.update(webCodes)
|
|
15
15
|
.set({ usedAt: now })
|
|
16
16
|
.where(and(eq(webCodes.codeHash, codeHash), isNull(webCodes.usedAt), gt(webCodes.expiresAt, now)))
|
|
17
|
-
.returning({ userId: webCodes.userId })
|
|
18
|
-
.get()
|
|
17
|
+
.returning({ userId: webCodes.userId, purpose: webCodes.purpose })
|
|
18
|
+
.get();
|
|
19
|
+
return row ? { userId: row.userId, purpose: row.purpose } : null;
|
|
19
20
|
}
|
|
20
|
-
async createSession(userId, tokenHash, now, expiresAt) {
|
|
21
|
+
async createSession(userId, tokenHash, now, expiresAt, device) {
|
|
21
22
|
return this.db
|
|
22
23
|
.insert(webSessions)
|
|
23
|
-
.values({ userId, tokenHash, lastSeenAt: now, expiresAt })
|
|
24
|
+
.values({ userId, tokenHash, lastSeenAt: now, expiresAt, deviceName: device.name, createdFrom: device.createdFrom })
|
|
24
25
|
.returning({ id: webSessions.id })
|
|
25
26
|
.get();
|
|
26
27
|
}
|
|
27
28
|
async findActiveSession(tokenHash, now) {
|
|
28
|
-
|
|
29
|
-
.select({ id: webSessions.id, userId: webSessions.userId, lastSeenAt: webSessions.lastSeenAt })
|
|
29
|
+
const row = this.db
|
|
30
|
+
.select({ id: webSessions.id, userId: webSessions.userId, lastSeenAt: webSessions.lastSeenAt, createdFrom: webSessions.createdFrom })
|
|
30
31
|
.from(webSessions)
|
|
31
32
|
.where(and(eq(webSessions.tokenHash, tokenHash), isNull(webSessions.revokedAt), gt(webSessions.expiresAt, now)))
|
|
32
|
-
.get()
|
|
33
|
+
.get();
|
|
34
|
+
return row ? { ...row, createdFrom: row.createdFrom } : null;
|
|
33
35
|
}
|
|
34
36
|
async touchSession(id, now, expiresAt) {
|
|
35
37
|
this.db.update(webSessions).set({ lastSeenAt: now, expiresAt }).where(eq(webSessions.id, id)).run();
|
|
@@ -43,6 +45,30 @@ export class SqliteWebSessionsStore {
|
|
|
43
45
|
.all();
|
|
44
46
|
return rows.length > 0;
|
|
45
47
|
}
|
|
48
|
+
async listSessions(userId, now) {
|
|
49
|
+
return this.db
|
|
50
|
+
.select({
|
|
51
|
+
id: webSessions.id,
|
|
52
|
+
deviceName: webSessions.deviceName,
|
|
53
|
+
createdFrom: webSessions.createdFrom,
|
|
54
|
+
createdAt: webSessions.createdAt,
|
|
55
|
+
lastSeenAt: webSessions.lastSeenAt,
|
|
56
|
+
})
|
|
57
|
+
.from(webSessions)
|
|
58
|
+
.where(and(eq(webSessions.userId, userId), isNull(webSessions.revokedAt), gt(webSessions.expiresAt, now)))
|
|
59
|
+
.orderBy(desc(webSessions.lastSeenAt), desc(webSessions.id))
|
|
60
|
+
.all()
|
|
61
|
+
.map((r) => ({ ...r, createdFrom: r.createdFrom }));
|
|
62
|
+
}
|
|
63
|
+
async revokeSessionById(userId, id, now) {
|
|
64
|
+
const rows = this.db
|
|
65
|
+
.update(webSessions)
|
|
66
|
+
.set({ revokedAt: now })
|
|
67
|
+
.where(and(eq(webSessions.id, id), eq(webSessions.userId, userId), isNull(webSessions.revokedAt)))
|
|
68
|
+
.returning({ id: webSessions.id })
|
|
69
|
+
.all();
|
|
70
|
+
return rows.length > 0;
|
|
71
|
+
}
|
|
46
72
|
async deleteExpired(before) {
|
|
47
73
|
this.db.delete(webCodes).where(or(lt(webCodes.expiresAt, before), isNotNull(webCodes.usedAt))).run();
|
|
48
74
|
this.db.delete(webSessions).where(or(lt(webSessions.expiresAt, before), lt(webSessions.revokedAt, before))).run();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
:root{--bg:#f7f7f5;--panel:#fff;--text:#1d1d1b;--muted:#6b6b66;--line:#e4e4df;--accent:#2f5d50;--accent-text:#fff;--user:#eef3f1;--code:#f1f1ed;--danger:#a3302a;--warn-bg:#fff4e5;--warn-line:#f0c27a;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial;--bg:#161615;--panel:#1e1e1c;--text:#ececea;--muted:#a3a39d;--line:#33332f;--accent:#7fb8a6;--accent-text:#10201b;--user:#22302b;--code:#2a2a27;--danger:#e0807a;--warn-bg:#3a2c16;--warn-line:#7a5a26}}*{box-sizing:border-box}html,body,#root{height:100%;margin:0}body{background:var(--bg);color:var(--text);font:15px/1.55 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}button,input,textarea{font:inherit;color:inherit}button{cursor:pointer;border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px}button:disabled{opacity:.5;cursor:default}button.primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}button.ghost{background:0 0;border-color:#0000}button.ghost:hover:not(:disabled){background:var(--line)}button.danger{color:var(--danger)}button.stop{background:var(--danger);color:#fff;border-color:var(--danger)}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.muted{color:var(--muted)}.center{text-align:center;max-width:520px;margin:12vh auto;padding:0 16px}.signed-out h1{margin-bottom:.5rem;font-size:1.6rem}.layout{height:100%;display:flex}.sidebar{border-right:1px solid var(--line);background:var(--panel);flex-direction:column;flex:none;gap:8px;width:260px;padding:12px;display:flex}.new-chat{width:100%;padding:8px}.conversations{flex:1;margin:0;padding:0;list-style:none;overflow-y:auto}.conv{text-align:left;white-space:nowrap;text-overflow:ellipsis;background:0 0;border:none;align-items:center;gap:6px;width:100%;padding:8px 10px;display:flex;overflow:hidden}.conv:hover{background:var(--line)}.conv.active{background:var(--user);font-weight:600}.tag{color:var(--muted);border:1px solid var(--line);border-radius:6px;flex:none;padding:0 5px;font-size:.72rem}.empty{padding:8px 10px}.more{width:100%}.backup{text-align:left;width:100%}.account{border-top:1px solid var(--line);justify-content:space-between;align-items:center;gap:6px;padding-top:8px;font-size:.85rem;display:flex}.account span{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.main{flex-direction:column;flex:1;min-width:0;display:flex}.banner{border:1px solid var(--warn-line);background:var(--warn-bg);border-radius:10px;justify-content:space-between;align-items:flex-start;gap:12px;margin:12px 16px 0;padding:10px 14px;display:flex}.banner .hint{color:var(--muted);word-break:break-all;margin-top:2px}.banner.info{border-color:var(--line);background:var(--user)}.signed-out .banner{text-align:left;margin:0 0 16px}.chat{flex-direction:column;flex:1;min-height:0;display:flex}.chat-header{border-bottom:1px solid var(--line);justify-content:space-between;align-items:center;gap:12px;padding:10px 16px;display:flex}.title{text-overflow:ellipsis;white-space:nowrap;margin:0;font-size:1.05rem;overflow:hidden}.header-actions{flex:none;align-items:center;gap:4px;display:flex}.model{color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:2px 8px;font-size:.8rem}.rename{flex:1;gap:6px;display:flex}.rename input{border:1px solid var(--line);background:var(--panel);border-radius:8px;flex:1;padding:6px 10px}.messages{flex-direction:column;flex:1;gap:14px;padding:16px;display:flex;overflow-y:auto}.welcome{text-align:center;margin:auto}.msg{width:100%;max-width:780px;margin:0 auto}.msg .who{color:var(--muted);margin-bottom:2px;font-size:.78rem}.msg.user .body{background:var(--user);border-radius:12px;padding:10px 14px}.msg .body p{margin:0 0 .6em}.msg .body p:last-child{margin-bottom:0}.msg .plain{white-space:pre-wrap}.msg .branch{color:var(--muted);opacity:0;margin-top:2px;padding:2px 6px;font-size:.78rem}.msg:hover .branch,.msg .branch:focus-visible{opacity:1}@media (hover:none){.msg .branch{opacity:1}}select.model{background:var(--panel);cursor:pointer}.msg .note{color:var(--muted);margin-top:4px;font-size:.8rem;font-style:italic}.heading{font-weight:700}.heading.h1{font-size:1.2em}.heading.h2{font-size:1.1em}pre.code{background:var(--code);border-radius:8px;margin:.4em 0 .8em;padding:10px 12px;overflow-x:auto}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}:not(pre)>code{background:var(--code);border-radius:5px;padding:1px 5px}.link-text{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}ul,ol{margin:.3em 0 .8em;padding-left:1.4em}.composer{align-items:flex-end;gap:8px;width:100%;max-width:812px;margin:0 auto;padding:12px 16px 16px;display:flex}.composer textarea{resize:none;border:1px solid var(--line);background:var(--panel);border-radius:12px;flex:1;min-height:48px;padding:10px 12px}.composer button{padding:10px 16px}
|
|
1
|
+
:root{--bg:#f7f7f5;--panel:#fff;--text:#1d1d1b;--muted:#6b6b66;--line:#e4e4df;--accent:#2f5d50;--accent-text:#fff;--user:#eef3f1;--code:#f1f1ed;--danger:#a3302a;--warn-bg:#fff4e5;--warn-line:#f0c27a;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial;--bg:#161615;--panel:#1e1e1c;--text:#ececea;--muted:#a3a39d;--line:#33332f;--accent:#7fb8a6;--accent-text:#10201b;--user:#22302b;--code:#2a2a27;--danger:#e0807a;--warn-bg:#3a2c16;--warn-line:#7a5a26}}*{box-sizing:border-box}html,body,#root{height:100%;margin:0}body{background:var(--bg);color:var(--text);font:15px/1.55 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}button,input,textarea{font:inherit;color:inherit}button{cursor:pointer;border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px}button:disabled{opacity:.5;cursor:default}button.primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}button.ghost{background:0 0;border-color:#0000}button.ghost:hover:not(:disabled){background:var(--line)}button.danger{color:var(--danger)}button.stop{background:var(--danger);color:#fff;border-color:var(--danger)}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.muted{color:var(--muted)}.center{text-align:center;max-width:520px;margin:12vh auto;padding:0 16px}.signed-out h1{margin-bottom:.5rem;font-size:1.6rem}.layout{height:100%;display:flex}.sidebar{border-right:1px solid var(--line);background:var(--panel);flex-direction:column;flex:none;gap:8px;width:260px;padding:12px;display:flex}.new-chat{width:100%;padding:8px}.conversations{flex:1;margin:0;padding:0;list-style:none;overflow-y:auto}.conv{text-align:left;white-space:nowrap;text-overflow:ellipsis;background:0 0;border:none;align-items:center;gap:6px;width:100%;padding:8px 10px;display:flex;overflow:hidden}.conv:hover{background:var(--line)}.conv.active{background:var(--user);font-weight:600}.tag{color:var(--muted);border:1px solid var(--line);border-radius:6px;flex:none;padding:0 5px;font-size:.72rem}.empty{padding:8px 10px}.more{width:100%}.backup{text-align:left;width:100%}.account{border-top:1px solid var(--line);justify-content:space-between;align-items:center;gap:6px;padding-top:8px;font-size:.85rem;display:flex}.account span{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.main{flex-direction:column;flex:1;min-width:0;display:flex}.banner{border:1px solid var(--warn-line);background:var(--warn-bg);border-radius:10px;justify-content:space-between;align-items:flex-start;gap:12px;margin:12px 16px 0;padding:10px 14px;display:flex}.banner .hint{color:var(--muted);word-break:break-all;margin-top:2px}.banner.info{border-color:var(--line);background:var(--user)}.signed-out .banner{text-align:left;margin:0 0 16px}.chat{flex-direction:column;flex:1;min-height:0;display:flex}.chat-header{border-bottom:1px solid var(--line);justify-content:space-between;align-items:center;gap:12px;padding:10px 16px;display:flex}.title{text-overflow:ellipsis;white-space:nowrap;margin:0;font-size:1.05rem;overflow:hidden}.header-actions{flex:none;align-items:center;gap:4px;display:flex}.model{color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:2px 8px;font-size:.8rem}.rename{flex:1;gap:6px;display:flex}.rename input{border:1px solid var(--line);background:var(--panel);border-radius:8px;flex:1;padding:6px 10px}.messages{flex-direction:column;flex:1;gap:14px;padding:16px;display:flex;overflow-y:auto}.welcome{text-align:center;margin:auto}.msg{width:100%;max-width:780px;margin:0 auto}.msg .who{color:var(--muted);margin-bottom:2px;font-size:.78rem}.msg.user .body{background:var(--user);border-radius:12px;padding:10px 14px}.msg .body p{margin:0 0 .6em}.msg .body p:last-child{margin-bottom:0}.msg .plain{white-space:pre-wrap}.msg .branch{color:var(--muted);opacity:0;margin-top:2px;padding:2px 6px;font-size:.78rem}.msg:hover .branch,.msg .branch:focus-visible{opacity:1}@media (hover:none){.msg .branch{opacity:1}}select.model{background:var(--panel);cursor:pointer}.msg .note{color:var(--muted);margin-top:4px;font-size:.8rem;font-style:italic}.heading{font-weight:700}.heading.h1{font-size:1.2em}.heading.h2{font-size:1.1em}pre.code{background:var(--code);border-radius:8px;margin:.4em 0 .8em;padding:10px 12px;overflow-x:auto}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}:not(pre)>code{background:var(--code);border-radius:5px;padding:1px 5px}.link-text{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}ul,ol{margin:.3em 0 .8em;padding-left:1.4em}.composer{align-items:flex-end;gap:8px;width:100%;max-width:812px;margin:0 auto;padding:12px 16px 16px;display:flex}.composer textarea{resize:none;border:1px solid var(--line);background:var(--panel);border-radius:12px;flex:1;min-height:48px;padding:10px 12px}.composer button{padding:10px 16px}.overlay{z-index:20;background:#0006;justify-content:center;align-items:center;padding:16px;display:flex;position:fixed;inset:0}.panel{background:var(--panel);border-radius:14px;width:100%;max-width:480px;max-height:90vh;padding:16px 18px 20px;overflow-y:auto}.panel-header{justify-content:space-between;align-items:center;display:flex}.panel-header h2{margin:0;font-size:1.1rem}.panel h3{margin:16px 0 8px;font-size:.95rem}.panel-error{color:var(--danger)}.pair ul{padding-left:1.2em}.qr{text-align:center}.qr img{image-rendering:pixelated;background:#fff;border-radius:10px;padding:8px}.small{font-size:.82rem}.devices{margin:0;padding:0;list-style:none}.devices li{border-bottom:1px solid var(--line);justify-content:space-between;align-items:center;gap:10px;padding:8px 0;display:flex}.devices li:last-child{border-bottom:none}.devices .tag{margin-left:6px}.menu{padding:4px 10px;font-size:1.2rem;display:none}.scrim{display:none}@media (width<=720px){.menu{display:inline-block}.sidebar{z-index:10;width:min(84vw,320px);padding-top:max(12px, env(safe-area-inset-top));transition:transform .2s;position:fixed;top:0;bottom:0;left:0;transform:translate(-100%)}.drawer-open .sidebar{transform:none;box-shadow:0 0 24px #00000040}.drawer-open .scrim{z-index:9;background:#00000059;display:block;position:fixed;inset:0}.chat-header{padding-top:max(10px, env(safe-area-inset-top))}.composer{padding-bottom:max(16px, env(safe-area-inset-bottom))}.composer textarea{font-size:16px}button{min-height:40px}.msg .branch{opacity:1}}
|