@mupt-ai/dari-gateway 1.0.313 → 1.0.314

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 (71) hide show
  1. package/README.md +17 -20
  2. package/dist/http/handler.js +1 -1
  3. package/dist/ingress/anthropic_messages.js +1 -1
  4. package/dist/ingress/models.js +1 -1
  5. package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
  6. package/dist/{link_client.js → link/client.js} +5 -6
  7. package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
  8. package/dist/{ingress/link.js → link/endpoints.js} +158 -62
  9. package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
  10. package/dist/link/grants.d.ts +151 -0
  11. package/dist/link/grants.js +275 -0
  12. package/dist/link/key_providers.d.ts +6 -0
  13. package/dist/link/key_providers.js +21 -0
  14. package/dist/link/self_hosted.d.ts +3 -0
  15. package/dist/link/self_hosted.js +166 -0
  16. package/dist/link/service.d.ts +85 -0
  17. package/dist/link/service.js +187 -0
  18. package/dist/link/sqlite_store.d.ts +74 -0
  19. package/dist/link/sqlite_store.js +381 -0
  20. package/dist/models/canonical_models.json +19 -0
  21. package/dist/platform/platform.d.ts +42 -47
  22. package/dist/runtime/explicit_model.js +1 -1
  23. package/dist/runtime/prepare_routed_completion.js +1 -1
  24. package/dist/self_host/main.js +2 -2
  25. package/dist/self_host/platform.js +4 -249
  26. package/dist/self_host/resolve.d.ts +2 -2
  27. package/dist/self_host/resolve.js +3 -19
  28. package/dist/self_host/stub_gateway.js +3 -3
  29. package/dist/self_host/subscriptions/http.js +2 -2
  30. package/dist/telemetry/report.js +1 -1
  31. package/package.json +2 -2
  32. package/src/http/handler.ts +1 -1
  33. package/src/ingress/anthropic_messages.ts +1 -1
  34. package/src/ingress/models.ts +1 -1
  35. package/src/{link_client.ts → link/client.ts} +11 -14
  36. package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
  37. package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
  38. package/src/link/grants.ts +436 -0
  39. package/src/link/key_providers.ts +25 -0
  40. package/src/link/self_hosted.ts +186 -0
  41. package/src/link/service.ts +281 -0
  42. package/src/link/sqlite_store.ts +512 -0
  43. package/src/models/canonical_models.json +19 -0
  44. package/src/platform/platform.ts +39 -45
  45. package/src/runtime/explicit_model.ts +1 -1
  46. package/src/runtime/prepare_routed_completion.ts +1 -1
  47. package/src/self_host/main.ts +2 -2
  48. package/src/self_host/platform.ts +5 -267
  49. package/src/self_host/resolve.ts +6 -21
  50. package/src/self_host/stub_gateway.ts +3 -3
  51. package/src/self_host/subscriptions/http.ts +2 -2
  52. package/src/telemetry/report.ts +1 -1
  53. package/dist/self_host/link_store.d.ts +0 -167
  54. package/dist/self_host/link_store.js +0 -564
  55. package/src/self_host/link_store.ts +0 -782
  56. /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
  57. /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
  58. /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
  59. /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
  60. /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
  61. /package/dist/{models/link_errors.js → link/errors.js} +0 -0
  62. /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
  63. /package/dist/{ingress/link_font.js → link/font.js} +0 -0
  64. /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
  65. /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
  66. /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
  67. /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
  68. /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
  69. /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
  70. /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
  71. /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
@@ -1,782 +0,0 @@
1
- /**
2
- * SQLite storage for Dari Link: registered apps, the grants users approve for
3
- * them, and each grant's tokens. A grant names the subscriptions it may use.
4
- * Every token is its own row holding only the token's SHA-256, so an access
5
- * token lives until its own expiry whatever is issued after it; revoking the
6
- * grant stops them all at once.
7
- *
8
- * - access tokens last an hour.
9
- * - refresh tokens do not expire. A public client's rotates on use; a
10
- * confidential client, which also proves its secret, keeps its own.
11
- * - child tokens serve one model, for up to twelve hours, and cannot refresh
12
- * or mint.
13
- */
14
- import type { Database } from "bun:sqlite";
15
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
16
-
17
- import { HttpError } from "../http/errors.js";
18
- import { type SecretBox, openWithoutKey } from "./secret_box.js";
19
- import type {
20
- LinkApp,
21
- LinkBudget,
22
- LinkChildToken,
23
- LinkGrant,
24
- LinkTokens,
25
- LinkUsage,
26
- LinkUsageQuery,
27
- LinkUsageTotals,
28
- } from "../platform/platform.js";
29
- import { LINK_ACCESS_TOKEN_PREFIX, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
30
- import { type BudgetStanding, budgetLookbackMs, budgetStandings } from "../runtime/link_budget.js";
31
-
32
- export const LINK_ACCESS_TOKEN_TTL_MS = 60 * 60_000;
33
- const LINK_CODE_TTL_MS = 10 * 60_000;
34
- // A rotated refresh token presented again this soon lost a race with its own
35
- // rotation (two instances, or a retry after a lost response); later, it leaked.
36
- export const LINK_REFRESH_RACE_MS = 60_000;
37
- // Expired tokens are kept this long so they are told apart from unknown ones.
38
- const LINK_TOKEN_RETENTION_MS = 24 * 60 * 60_000;
39
-
40
- // Prefixes keep link tokens apart from gateway keys and from each other.
41
- const REFRESH_TOKEN_PREFIX = "dlk_rt_";
42
- const CODE_PREFIX = "dlk_code_";
43
- const CLIENT_SECRET_PREFIX = "dlk_cs_";
44
-
45
- export type LinkRevoker = "user" | "app" | "reuse_detected";
46
-
47
- export type ActiveLinkGrant = {
48
- id: string;
49
- clientId: string;
50
- credentialIds: ReadonlySet<string>;
51
- // Set for a child token: the models it serves, each with its pinned thinking.
52
- pins?: LinkPin[];
53
- tags?: Record<string, string>;
54
- };
55
-
56
- /** What a presented link token is; null when it is not one this store issued. */
57
- export type LinkPin = { model: string; thinking: string | null };
58
-
59
- export type LinkTokenAuth =
60
- | { status: "active"; grant: ActiveLinkGrant }
61
- | { status: "expired" }
62
- | { status: "revoked"; revokedBy: string | null; revokedAt: string | null };
63
-
64
- type AppRow = {
65
- client_id: string;
66
- name: string;
67
- redirect_uris: string;
68
- client_secret_hash: string | null;
69
- };
70
-
71
- type GrantRow = {
72
- id: string;
73
- client_id: string;
74
- credential_ids: string;
75
- code_challenge: string | null;
76
- redirect_uri: string | null;
77
- code_expires_at: number | null;
78
- created_at: number;
79
- revoked_at: number | null;
80
- revoked_by: string | null;
81
- budget: string | null;
82
- };
83
-
84
- /** An API key a user added on the approval page, for one model provider or gateway. */
85
- export type LinkApiKey = { id: string; subject: string; provider: string; apiKey: string };
86
-
87
- type KeyRow = { id: string; subject: string; provider: string; api_key: string };
88
-
89
- // Where a stored API key belongs, which its encryption is bound to.
90
- function keyPlace(id: string): string {
91
- return `link_api_keys:${id}:api_key`;
92
- }
93
-
94
- type TokenRow = {
95
- kind: "access" | "refresh" | "child";
96
- expires_at: number | null;
97
- rotated_at: number | null;
98
- model: string | null;
99
- thinking: string | null;
100
- pins: string | null;
101
- tags: string | null;
102
- grant_id: string;
103
- client_id: string;
104
- credential_ids: string;
105
- revoked_at: number | null;
106
- revoked_by: string | null;
107
- };
108
-
109
- const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
110
- link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
111
- link_grants.credential_ids, link_grants.revoked_at, link_grants.revoked_by
112
- FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
113
- WHERE link_tokens.token_hash = ?`;
114
-
115
- export class LinkStore {
116
- constructor(private readonly db: Database, private readonly box: SecretBox | null = null) {
117
- db.run(`CREATE TABLE IF NOT EXISTS link_apps (
118
- client_id TEXT PRIMARY KEY,
119
- name TEXT NOT NULL,
120
- redirect_uris TEXT NOT NULL,
121
- client_secret_hash TEXT,
122
- created_at INTEGER NOT NULL
123
- )`);
124
- db.run(`CREATE TABLE IF NOT EXISTS link_grants (
125
- id TEXT PRIMARY KEY,
126
- client_id TEXT NOT NULL REFERENCES link_apps (client_id),
127
- credential_ids TEXT NOT NULL,
128
- code_hash TEXT UNIQUE,
129
- code_challenge TEXT,
130
- redirect_uri TEXT,
131
- code_expires_at INTEGER,
132
- created_at INTEGER NOT NULL,
133
- revoked_at INTEGER,
134
- revoked_by TEXT
135
- )`);
136
- db.run(`CREATE TABLE IF NOT EXISTS link_tokens (
137
- token_hash TEXT PRIMARY KEY,
138
- grant_id TEXT NOT NULL REFERENCES link_grants (id),
139
- kind TEXT NOT NULL,
140
- expires_at INTEGER,
141
- rotated_at INTEGER,
142
- model TEXT,
143
- thinking TEXT,
144
- tags TEXT,
145
- created_at INTEGER NOT NULL
146
- )`);
147
- db.run("CREATE INDEX IF NOT EXISTS link_tokens_grant_id ON link_tokens (grant_id)");
148
- db.run(`CREATE TABLE IF NOT EXISTS link_usage (
149
- request_id TEXT PRIMARY KEY,
150
- grant_id TEXT NOT NULL REFERENCES link_grants (id),
151
- received_at INTEGER NOT NULL,
152
- model TEXT,
153
- thinking TEXT,
154
- tags TEXT NOT NULL,
155
- input_tokens INTEGER NOT NULL,
156
- output_tokens INTEGER NOT NULL,
157
- cache_read_tokens INTEGER NOT NULL,
158
- cache_write_tokens INTEGER NOT NULL
159
- )`);
160
- db.run("CREATE INDEX IF NOT EXISTS link_usage_grant_received ON link_usage (grant_id, received_at)");
161
- // Added after link_grants shipped: a gateway database from before gains it.
162
- const grantColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_grants)").all();
163
- if (!grantColumns.some((column) => column.name === "budget")) db.run("ALTER TABLE link_grants ADD COLUMN budget TEXT");
164
- // The user who approved the grant on the approval page.
165
- if (!grantColumns.some((column) => column.name === "subject")) db.run("ALTER TABLE link_grants ADD COLUMN subject TEXT");
166
- const tokenColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_tokens)").all();
167
- if (!tokenColumns.some((column) => column.name === "pins")) db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
168
- const usageColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_usage)").all();
169
- if (!usageColumns.some((column) => column.name === "status")) db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
170
- // API keys users added on the approval page: one per user and provider.
171
- db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
172
- id TEXT PRIMARY KEY,
173
- subject TEXT NOT NULL,
174
- provider TEXT NOT NULL,
175
- api_key TEXT NOT NULL,
176
- created_at INTEGER NOT NULL,
177
- UNIQUE (subject, provider)
178
- )`);
179
- this.encryptStored();
180
- }
181
-
182
- // Seal API keys stored before encryption was turned on, or under a key
183
- // that no longer encrypts.
184
- private encryptStored(): void {
185
- const box = this.box;
186
- if (box === null) return;
187
- this.db.transaction(() => {
188
- for (const row of this.db.query<KeyRow, []>("SELECT * FROM link_api_keys").all()) {
189
- if (box.current(row.api_key)) continue;
190
- this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [
191
- box.seal(box.adopt(row.api_key, keyPlace(row.id)), keyPlace(row.id)),
192
- row.id,
193
- ]);
194
- }
195
- })();
196
- }
197
-
198
- private seal(value: string, place: string): string {
199
- return this.box === null ? value : this.box.seal(value, place);
200
- }
201
-
202
- private key(row: KeyRow): LinkApiKey {
203
- const stored = row.api_key;
204
- return {
205
- id: row.id,
206
- subject: row.subject,
207
- provider: row.provider,
208
- apiKey: this.box === null ? openWithoutKey(stored) : this.box.open(stored, keyPlace(row.id)),
209
- };
210
- }
211
-
212
- /** Store a user's API key for a provider, replacing their earlier one for it. */
213
- addKey(subject: string, provider: string, apiKey: string, now = new Date()): LinkApiKey {
214
- const existing = this.keys(subject).find((key) => key.provider === provider);
215
- if (existing !== undefined) {
216
- this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [this.seal(apiKey, keyPlace(existing.id)), existing.id]);
217
- return { ...existing, apiKey };
218
- }
219
- const id = `key_${randomUUID().replaceAll("-", "")}`;
220
- this.db.run(
221
- "INSERT INTO link_api_keys (id, subject, provider, api_key, created_at) VALUES (?, ?, ?, ?, ?)",
222
- [id, subject, provider, this.seal(apiKey, keyPlace(id)), now.getTime()],
223
- );
224
- return { id, subject, provider, apiKey };
225
- }
226
-
227
- /** Delete a user's API key; false when they have none by that id. */
228
- removeKey(subject: string, id: string): boolean {
229
- return this.db.run("DELETE FROM link_api_keys WHERE id = ? AND subject = ?", [id, subject]).changes > 0;
230
- }
231
-
232
- /**
233
- * Take a deleted plan or key out of every live grant; a grant left with
234
- * nothing is revoked as the user's doing.
235
- */
236
- dropCredential(credentialId: string, now = new Date()): void {
237
- this.db.transaction(() => {
238
- const grants = this.db
239
- .query<Pick<GrantRow, "id" | "credential_ids">, []>("SELECT id, credential_ids FROM link_grants WHERE revoked_at IS NULL")
240
- .all();
241
- for (const grant of grants) {
242
- const ids = parseIds(grant.credential_ids);
243
- if (!ids.includes(credentialId)) continue;
244
- const left = ids.filter((id) => id !== credentialId);
245
- if (left.length === 0) this.revoke(grant.id, "user", now);
246
- else this.db.run("UPDATE link_grants SET credential_ids = ? WHERE id = ?", [JSON.stringify(left), grant.id]);
247
- }
248
- })();
249
- }
250
-
251
- /** The API keys a user added, oldest first. */
252
- keys(subject: string): LinkApiKey[] {
253
- return this.db
254
- .query<KeyRow, [string]>("SELECT * FROM link_api_keys WHERE subject = ? ORDER BY created_at, rowid")
255
- .all(subject)
256
- .map((row) => this.key(row));
257
- }
258
-
259
- /** The API keys with these ids, whoever added them. */
260
- keysWithIds(ids: ReadonlySet<string>): LinkApiKey[] {
261
- return this.db
262
- .query<KeyRow, []>("SELECT * FROM link_api_keys ORDER BY created_at, rowid")
263
- .all()
264
- .filter((row) => ids.has(row.id))
265
- .map((row) => this.key(row));
266
- }
267
-
268
- /** A grant's budget; empty when it has none or is unknown. */
269
- budget(grantId: string): LinkBudget[] {
270
- const row = this.db.query<Pick<GrantRow, "budget">, [string]>("SELECT budget FROM link_grants WHERE id = ?").get(grantId);
271
- return parseBudget(row?.budget ?? null);
272
- }
273
-
274
- /** Replace a live grant's budget; false when none is live by that id. */
275
- setBudget(grantId: string, budget: LinkBudget[]): boolean {
276
- return this.db.run(
277
- "UPDATE link_grants SET budget = ? WHERE id = ? AND revoked_at IS NULL",
278
- [budget.length === 0 ? null : JSON.stringify(budget), grantId],
279
- ).changes > 0;
280
- }
281
-
282
- /** Each of a grant's budget windows as it stands now (see runtime/link_budget.ts). */
283
- budgetStandings(grantId: string, now = new Date()): BudgetStanding[] {
284
- const budget = this.budget(grantId);
285
- if (budget.length === 0) return [];
286
- const uses = this.db
287
- .query<{ received_at: number; tokens: number }, [string, number]>(
288
- `SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
289
- FROM link_usage WHERE grant_id = ? AND received_at > ?`,
290
- )
291
- .all(grantId, now.getTime() - budgetLookbackMs(budget))
292
- .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
293
- return budgetStandings(budget, uses, now);
294
- }
295
-
296
- /** Record what one of a grant's requests used; a repeated request id is ignored. */
297
- recordUsage(entry: LinkUsageEntry): void {
298
- this.db.run(
299
- `INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
300
- input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
301
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
302
- [
303
- entry.requestId,
304
- entry.grantId,
305
- entry.receivedAt.getTime(),
306
- entry.model,
307
- entry.thinking,
308
- JSON.stringify(entry.tags),
309
- entry.inputTokens,
310
- entry.outputTokens,
311
- entry.cacheReadTokens,
312
- entry.cacheWriteTokens,
313
- entry.status,
314
- ],
315
- );
316
- }
317
-
318
- /** What a grant's requests used, filtered by tags and receive time. */
319
- usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Omit<LinkUsage, "completeThrough"> {
320
- const rows = query.requestId !== undefined
321
- ? this.db
322
- .query<UsageRow, [string, string]>("SELECT * FROM link_usage WHERE grant_id = ? AND request_id = ?")
323
- .all(grantId, query.requestId)
324
- : this.db
325
- .query<UsageRow, [string, number, number]>(
326
- `SELECT * FROM link_usage WHERE grant_id = ? AND received_at >= ? AND received_at < ?`,
327
- )
328
- .all(grantId, query.since?.getTime() ?? 0, query.until?.getTime() ?? Number.MAX_SAFE_INTEGER);
329
- const filters = Object.entries(query.tags);
330
- return summarizeLinkUsage(
331
- rows
332
- .map((row) => ({ row, tags: JSON.parse(row.tags) as Record<string, string> }))
333
- .filter(({ tags }) => filters.every(([key, value]) => tags[key] === value))
334
- .map(({ row, tags }) => ({
335
- model: row.model,
336
- thinking: row.thinking,
337
- tag: query.groupByTag === undefined ? null : tags[query.groupByTag] ?? null,
338
- failed: row.status === "provider_error" || row.status === "selector_error",
339
- inputTokens: row.input_tokens,
340
- outputTokens: row.output_tokens,
341
- cacheReadTokens: row.cache_read_tokens,
342
- cacheWriteTokens: row.cache_write_tokens,
343
- })),
344
- query.groupByTag !== undefined,
345
- );
346
- }
347
-
348
- /** Register an app; a confidential one gets a secret, returned this once. */
349
- registerApp(
350
- name: string,
351
- redirectUris: string[],
352
- confidential = false,
353
- now = new Date(),
354
- ): LinkApp & { clientSecret?: string } {
355
- const clientId = `lnk_${randomUUID().replaceAll("-", "")}`;
356
- const clientSecret = confidential ? secret(CLIENT_SECRET_PREFIX) : undefined;
357
- this.db.run(
358
- "INSERT INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, ?, ?, ?)",
359
- [clientId, name, JSON.stringify(redirectUris), clientSecret === undefined ? null : hash(clientSecret), now.getTime()],
360
- );
361
- return { clientId, name, redirectUris, confidential, ...(clientSecret === undefined ? {} : { clientSecret }) };
362
- }
363
-
364
- app(clientId: string): LinkApp | null {
365
- const row = this.db.query<AppRow, [string]>("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
366
- return row === null ? null : appFromRow(row);
367
- }
368
-
369
- /**
370
- * Create a grant awaiting its code exchange and return the code. With
371
- * `grantId` (update mode), change that live grant of the app's plans and
372
- * budget in place instead: its tokens keep working, and the code redeems
373
- * for more tokens of the same grant.
374
- */
375
- approve(
376
- request: {
377
- subject?: string;
378
- grantId?: string;
379
- clientId: string;
380
- redirectUri: string;
381
- codeChallenge: string;
382
- credentialIds: string[];
383
- budget?: LinkBudget[];
384
- },
385
- now = new Date(),
386
- ): string {
387
- const app = this.app(request.clientId);
388
- if (app === null || !app.redirectUris.includes(request.redirectUri)) {
389
- throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
390
- }
391
- const code = secret(CODE_PREFIX);
392
- const budget = request.budget === undefined || request.budget.length === 0 ? null : JSON.stringify(request.budget);
393
- if (request.grantId !== undefined) {
394
- const updated = this.db.run(
395
- `UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
396
- code_expires_at = ?
397
- WHERE id = ? AND client_id = ? AND revoked_at IS NULL`,
398
- [
399
- JSON.stringify(request.credentialIds),
400
- budget,
401
- hash(code),
402
- request.codeChallenge,
403
- request.redirectUri,
404
- now.getTime() + LINK_CODE_TTL_MS,
405
- request.grantId,
406
- request.clientId,
407
- ],
408
- ).changes;
409
- if (updated === 0) throw new HttpError(400, "That connection no longer exists.", "invalid_request");
410
- return code;
411
- }
412
- this.db.run(
413
- `INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
414
- code_expires_at, created_at, budget, subject)
415
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
416
- [
417
- `lgr_${randomUUID().replaceAll("-", "")}`,
418
- request.clientId,
419
- JSON.stringify(request.credentialIds),
420
- hash(code),
421
- request.codeChallenge,
422
- request.redirectUri,
423
- now.getTime() + LINK_CODE_TTL_MS,
424
- now.getTime(),
425
- budget,
426
- request.subject ?? null,
427
- ],
428
- );
429
- return code;
430
- }
431
-
432
- /** Redeem a code once: the grant's first tokens. */
433
- exchangeCode(
434
- request: { clientId: string; clientSecret?: string; code: string; redirectUri: string; codeChallenge: string },
435
- now = new Date(),
436
- ): LinkTokens {
437
- this.authenticateClient(request.clientId, request.clientSecret);
438
- return this.db.transaction(() => {
439
- const row = this.db
440
- .query<GrantRow, [string]>("SELECT * FROM link_grants WHERE code_hash = ?")
441
- .get(hash(request.code));
442
- if (
443
- row === null
444
- || row.revoked_at !== null
445
- || row.client_id !== request.clientId
446
- || row.redirect_uri !== request.redirectUri
447
- || row.code_expires_at === null
448
- || row.code_expires_at <= now.getTime()
449
- || row.code_challenge !== request.codeChallenge
450
- ) {
451
- throw invalidGrant("The authorization code is invalid, expired, or already used.");
452
- }
453
- this.db.run(
454
- "UPDATE link_grants SET code_hash = NULL, code_challenge = NULL, code_expires_at = NULL WHERE id = ?",
455
- [row.id],
456
- );
457
- return {
458
- accessToken: this.issue(row.id, "access", now, now.getTime() + LINK_ACCESS_TOKEN_TTL_MS),
459
- refreshToken: this.issue(row.id, "refresh", now, null),
460
- expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000,
461
- };
462
- })();
463
- }
464
-
465
- /**
466
- * A new access token for a grant. A public client's refresh token rotates;
467
- * a confidential client keeps the one it presented.
468
- */
469
- refresh(
470
- request: { clientId: string; clientSecret?: string; refreshToken: string },
471
- now = new Date(),
472
- ): LinkTokens {
473
- const app = this.authenticateClient(request.clientId, request.clientSecret);
474
- const presented = hash(request.refreshToken);
475
- // The refusal is thrown after the transaction, so a revoke in it holds.
476
- const result = this.db.transaction((): LinkTokens | "invalid" | "race" => {
477
- const row = this.db.query<TokenRow, [string]>(TOKEN_WITH_GRANT).get(presented);
478
- if (row === null || row.kind !== "refresh" || row.client_id !== request.clientId || row.revoked_at !== null) {
479
- return "invalid";
480
- }
481
- if (row.rotated_at !== null) {
482
- if (now.getTime() - row.rotated_at <= LINK_REFRESH_RACE_MS) return "race";
483
- // A rotated refresh token came back long after: it leaked.
484
- this.revoke(row.grant_id, "reuse_detected", now);
485
- return "invalid";
486
- }
487
- const accessToken = this.issue(row.grant_id, "access", now, now.getTime() + LINK_ACCESS_TOKEN_TTL_MS);
488
- if (app.confidential) {
489
- return { accessToken, refreshToken: request.refreshToken, expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000 };
490
- }
491
- this.db.run("UPDATE link_tokens SET rotated_at = ? WHERE token_hash = ?", [now.getTime(), presented]);
492
- return {
493
- accessToken,
494
- refreshToken: this.issue(row.grant_id, "refresh", now, null),
495
- expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000,
496
- };
497
- })();
498
- if (result === "race") {
499
- throw new HttpError(
500
- 400,
501
- "This refresh token was just rotated by another request. Use the tokens that request received.",
502
- "refresh_race",
503
- );
504
- }
505
- if (result === "invalid") throw invalidGrant("The refresh token is invalid or revoked.");
506
- return result;
507
- }
508
-
509
- /** Mint a child token from the grant's access token. */
510
- exchangeToken(
511
- request: {
512
- clientId: string;
513
- clientSecret?: string;
514
- subjectToken: string;
515
- models: Array<{ model: string; thinking?: string }>;
516
- expiresIn: number;
517
- tags: Record<string, string>;
518
- },
519
- now = new Date(),
520
- ): LinkChildToken {
521
- this.authenticateClient(request.clientId, request.clientSecret);
522
- const subject = this.authenticate(request.subjectToken, now);
523
- if (
524
- subject?.status !== "active"
525
- || subject.grant.pins !== undefined
526
- || subject.grant.clientId !== request.clientId
527
- ) {
528
- throw invalidGrant("subject_token must be a live access token of this client's grant.");
529
- }
530
- const accessToken = this.issue(subject.grant.id, "child", now, now.getTime() + request.expiresIn * 1000, {
531
- pins: JSON.stringify(request.models.map((entry): LinkPin => ({ model: entry.model, thinking: entry.thinking ?? null }))),
532
- tags: Object.keys(request.tags).length === 0 ? null : JSON.stringify(request.tags),
533
- });
534
- return { accessToken, expiresIn: request.expiresIn, grantId: subject.grant.id };
535
- }
536
-
537
- /** What a presented access or child token is, or null when it is neither. */
538
- authenticate(token: string, now = new Date()): LinkTokenAuth | null {
539
- if (!token.startsWith(LINK_ACCESS_TOKEN_PREFIX) && !token.startsWith(LINK_CHILD_TOKEN_PREFIX)) return null;
540
- const row = this.db.query<TokenRow, [string]>(TOKEN_WITH_GRANT).get(hash(token));
541
- if (row === null || row.kind === "refresh") return null;
542
- if (row.revoked_at !== null) {
543
- return { status: "revoked", revokedBy: row.revoked_by, revokedAt: new Date(row.revoked_at).toISOString() };
544
- }
545
- if (row.expires_at === null || row.expires_at <= now.getTime()) return { status: "expired" };
546
- const pins = row.kind === "child" ? childPins(row) : undefined;
547
- // A child token that names no model serves nothing.
548
- if (pins?.length === 0) return null;
549
- return {
550
- status: "active",
551
- grant: {
552
- id: row.grant_id,
553
- clientId: row.client_id,
554
- credentialIds: new Set(parseIds(row.credential_ids)),
555
- ...(pins === undefined ? {} : { pins }),
556
- ...(row.tags === null ? {} : { tags: JSON.parse(row.tags) as Record<string, string> }),
557
- },
558
- };
559
- }
560
-
561
- /** Revoke the grant any of its tokens names, when the client owns it (RFC 7009). */
562
- revokeToken(request: { clientId: string; clientSecret?: string; token: string }, now = new Date()): void {
563
- this.authenticateClient(request.clientId, request.clientSecret);
564
- const row = this.db.query<TokenRow, [string]>(TOKEN_WITH_GRANT).get(hash(request.token));
565
- if (row === null || row.client_id !== request.clientId) return;
566
- // A child token ends only itself: a sandbox holding one cannot end the grant.
567
- if (row.kind === "child") this.db.run("DELETE FROM link_tokens WHERE token_hash = ?", [hash(request.token)]);
568
- else this.revoke(row.grant_id, "app", now);
569
- }
570
-
571
- /** The subscriptions a grant may use; empty once it is revoked. */
572
- credentialIds(grantId: string): ReadonlySet<string> {
573
- const row = this.db
574
- .query<GrantRow, [string]>("SELECT * FROM link_grants WHERE id = ? AND revoked_at IS NULL")
575
- .get(grantId);
576
- return new Set(row === null ? [] : parseIds(row.credential_ids));
577
- }
578
-
579
- /** The user who approved a grant; null when it has none or is unknown. */
580
- subject(grantId: string): string | null {
581
- return this.db
582
- .query<{ subject: string | null }, [string]>("SELECT subject FROM link_grants WHERE id = ?")
583
- .get(grantId)?.subject ?? null;
584
- }
585
-
586
- /** Grants that are not revoked, oldest first. */
587
- grants(): LinkGrant[] {
588
- return this.db
589
- .query<GrantRow & { app_name: string }, []>(
590
- `SELECT link_grants.*, link_apps.name AS app_name FROM link_grants
591
- JOIN link_apps ON link_apps.client_id = link_grants.client_id
592
- WHERE link_grants.revoked_at IS NULL ORDER BY link_grants.created_at, link_grants.id`,
593
- )
594
- .all()
595
- .map((row) => ({
596
- id: row.id,
597
- clientId: row.client_id,
598
- appName: row.app_name,
599
- credentialIds: parseIds(row.credential_ids),
600
- createdAt: new Date(row.created_at).toISOString(),
601
- budget: parseBudget(row.budget),
602
- }));
603
- }
604
-
605
- /**
606
- * Revoke a grant: its code and refresh tokens go, and its access and child
607
- * tokens stop working. False when none is active by that id.
608
- */
609
- revoke(grantId: string, by: LinkRevoker, now = new Date()): boolean {
610
- const result = this.db.run(
611
- "UPDATE link_grants SET revoked_at = ?, revoked_by = ?, code_hash = NULL WHERE id = ? AND revoked_at IS NULL",
612
- [now.getTime(), by, grantId],
613
- );
614
- if (result.changes === 0) return false;
615
- this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND kind = 'refresh'", [grantId]);
616
- return true;
617
- }
618
-
619
- /**
620
- * The app a client id names, once it has proven its secret when it has one.
621
- * A confidential client must send its secret; a public one must not.
622
- */
623
- private authenticateClient(clientId: string, clientSecret: string | undefined): LinkApp {
624
- const row = this.db.query<AppRow, [string]>("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
625
- const proven = row !== null && (row.client_secret_hash === null
626
- ? !clientSecret
627
- : clientSecret !== undefined && sameHash(row.client_secret_hash, hash(clientSecret)));
628
- if (row === null || !proven) {
629
- throw new HttpError(401, "Unknown client, or a missing or wrong client secret.", "invalid_client");
630
- }
631
- return appFromRow(row);
632
- }
633
-
634
- private issue(
635
- grantId: string,
636
- kind: TokenRow["kind"],
637
- now: Date,
638
- expiresAt: number | null,
639
- child: { pins: string; tags: string | null } | null = null,
640
- ): string {
641
- const stale = now.getTime() - LINK_TOKEN_RETENTION_MS;
642
- // Rotated refresh tokens stay while the grant lives (revoking it deletes
643
- // them): presenting one again is how a stolen refresh token is caught.
644
- this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
645
- const token = secret(
646
- kind === "access" ? LINK_ACCESS_TOKEN_PREFIX : kind === "child" ? LINK_CHILD_TOKEN_PREFIX : REFRESH_TOKEN_PREFIX,
647
- );
648
- this.db.run(
649
- `INSERT INTO link_tokens (token_hash, grant_id, kind, expires_at, pins, tags, created_at)
650
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
651
- [hash(token), grantId, kind, expiresAt, child?.pins ?? null, child?.tags ?? null, now.getTime()],
652
- );
653
- return token;
654
- }
655
- }
656
-
657
- export type LinkUsageEntry = {
658
- requestId: string;
659
- grantId: string;
660
- receivedAt: Date;
661
- model: string | null;
662
- thinking: string | null;
663
- tags: Record<string, string>;
664
- inputTokens: number;
665
- outputTokens: number;
666
- cacheReadTokens: number;
667
- cacheWriteTokens: number;
668
- // The request's outcome, as the request record's `status`.
669
- status: string;
670
- };
671
-
672
- type UsageRow = {
673
- status: string | null;
674
- model: string | null;
675
- thinking: string | null;
676
- tags: string;
677
- input_tokens: number;
678
- output_tokens: number;
679
- cache_read_tokens: number;
680
- cache_write_tokens: number;
681
- };
682
-
683
- type UsageCounts = Omit<LinkUsageTotals, "requests" | "errors"> & {
684
- model: string | null;
685
- thinking: string | null;
686
- tag: string | null;
687
- failed: boolean;
688
- };
689
-
690
- function summarizeLinkUsage(requests: UsageCounts[], groupByTag: boolean): Omit<LinkUsage, "completeThrough"> {
691
- const empty = (): LinkUsageTotals => ({
692
- requests: 0,
693
- errors: 0,
694
- inputTokens: 0,
695
- outputTokens: 0,
696
- cacheReadTokens: 0,
697
- cacheWriteTokens: 0,
698
- });
699
- const add = (totals: LinkUsageTotals, request: UsageCounts) => {
700
- totals.requests += 1;
701
- totals.errors += request.failed ? 1 : 0;
702
- totals.inputTokens += request.inputTokens;
703
- totals.outputTokens += request.outputTokens;
704
- totals.cacheReadTokens += request.cacheReadTokens;
705
- totals.cacheWriteTokens += request.cacheWriteTokens;
706
- };
707
- const total = empty();
708
- const byModel = new Map<string, LinkUsage["byModel"][number]>();
709
- const byTag = new Map<string | null, NonNullable<LinkUsage["byTag"]>[number]>();
710
- for (const request of requests) {
711
- add(total, request);
712
- if (groupByTag) {
713
- let tagged = byTag.get(request.tag);
714
- if (tagged === undefined) {
715
- tagged = { value: request.tag, ...empty() };
716
- byTag.set(request.tag, tagged);
717
- }
718
- add(tagged, request);
719
- }
720
- const model = request.model ?? "unknown";
721
- const key = `${model}\u0000${request.thinking ?? ""}`;
722
- let entry = byModel.get(key);
723
- if (entry === undefined) {
724
- entry = { model, thinking: request.thinking, ...empty() };
725
- byModel.set(key, entry);
726
- }
727
- add(entry, request);
728
- }
729
- return {
730
- ...total,
731
- byModel: [...byModel.values()].sort((a, b) => b.requests - a.requests || a.model.localeCompare(b.model)),
732
- ...(groupByTag
733
- ? {
734
- byTag: [...byTag.values()].sort(
735
- (a, b) => b.requests - a.requests || (a.value ?? "").localeCompare(b.value ?? ""),
736
- ),
737
- }
738
- : {}),
739
- };
740
- }
741
-
742
- function secret(prefix: string): string {
743
- return `${prefix}${randomBytes(32).toString("base64url")}`;
744
- }
745
-
746
- function hash(value: string): string {
747
- return createHash("sha256").update(value).digest("hex");
748
- }
749
-
750
- function sameHash(a: string, b: string): boolean {
751
- return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
752
- }
753
-
754
- function invalidGrant(message: string): HttpError {
755
- return new HttpError(400, message, "invalid_grant");
756
- }
757
-
758
- function appFromRow(row: AppRow): LinkApp {
759
- return {
760
- clientId: row.client_id,
761
- name: row.name,
762
- redirectUris: JSON.parse(row.redirect_uris) as string[],
763
- confidential: row.client_secret_hash !== null,
764
- };
765
- }
766
-
767
- // A child token's models. One minted before `pins` existed kept its one model
768
- // in `model` and `thinking`.
769
- function childPins(row: TokenRow): LinkPin[] {
770
- if (row.pins !== null) return JSON.parse(row.pins) as LinkPin[];
771
- return row.model === null ? [] : [{ model: row.model, thinking: row.thinking }];
772
- }
773
-
774
- function parseIds(value: string): string[] {
775
- return JSON.parse(value) as string[];
776
- }
777
-
778
- // An entry without maxTokens (a share-of-plan limit from before token caps) is no limit.
779
- function parseBudget(value: string | null): LinkBudget[] {
780
- const entries = value === null ? [] : JSON.parse(value) as Array<Partial<LinkBudget>>;
781
- return entries.filter((entry): entry is LinkBudget => typeof entry.maxTokens === "number");
782
- }