@mupt-ai/dari-gateway 1.0.312 → 1.0.313

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 (113) hide show
  1. package/README.md +279 -2
  2. package/dist/context/routing_context.js +4 -1
  3. package/dist/http/handler.d.ts +2 -1
  4. package/dist/http/handler.js +12 -2
  5. package/dist/ingress/anthropic_messages.js +15 -3
  6. package/dist/ingress/chat_completions.js +6 -1
  7. package/dist/ingress/codex.js +2 -2
  8. package/dist/ingress/link.d.ts +24 -0
  9. package/dist/ingress/link.js +1519 -0
  10. package/dist/ingress/link_assets.d.ts +14 -0
  11. package/dist/ingress/link_assets.js +49 -0
  12. package/dist/ingress/link_font.d.ts +1 -0
  13. package/dist/ingress/link_font.js +6 -0
  14. package/dist/ingress/models.js +46 -2
  15. package/dist/interaction/types.d.ts +1 -0
  16. package/dist/link_client.d.ts +386 -0
  17. package/dist/link_client.js +579 -0
  18. package/dist/models/gateways.d.ts +2 -0
  19. package/dist/models/gateways.js +2 -0
  20. package/dist/models/link_errors.d.ts +30 -0
  21. package/dist/models/link_errors.js +120 -0
  22. package/dist/models/subscriptions.d.ts +8 -1
  23. package/dist/models/subscriptions.js +13 -2
  24. package/dist/platform/platform.d.ts +303 -1
  25. package/dist/protocol/input/router_model.d.ts +4 -0
  26. package/dist/protocol/input/router_model.js +31 -1
  27. package/dist/providers/execution.js +24 -2
  28. package/dist/providers/pi_options.js +57 -1
  29. package/dist/providers/provider_call.d.ts +4 -0
  30. package/dist/providers/provider_call.js +4 -1
  31. package/dist/providers/stream_finalization.d.ts +1 -0
  32. package/dist/runtime/explicit_model.js +16 -4
  33. package/dist/runtime/harness_identity/extract.js +20 -36
  34. package/dist/runtime/link_budget.d.ts +27 -0
  35. package/dist/runtime/link_budget.js +62 -0
  36. package/dist/runtime/link_grant_access.d.ts +7 -0
  37. package/dist/runtime/link_grant_access.js +99 -0
  38. package/dist/runtime/link_in_flight.d.ts +4 -0
  39. package/dist/runtime/link_in_flight.js +43 -0
  40. package/dist/runtime/prepare_routed_completion.js +5 -1
  41. package/dist/runtime/routed_runtime.js +8 -0
  42. package/dist/runtime/runtime_reporter.d.ts +1 -0
  43. package/dist/runtime/runtime_reporter.js +1 -0
  44. package/dist/self_host/config.d.ts +9 -0
  45. package/dist/self_host/config.js +11 -1
  46. package/dist/self_host/link_store.d.ts +167 -0
  47. package/dist/self_host/link_store.js +564 -0
  48. package/dist/self_host/main.d.ts +10 -3
  49. package/dist/self_host/main.js +19 -4
  50. package/dist/self_host/platform.d.ts +2 -2
  51. package/dist/self_host/platform.js +284 -10
  52. package/dist/self_host/resolve.d.ts +8 -0
  53. package/dist/self_host/resolve.js +146 -15
  54. package/dist/self_host/secret_box.d.ts +23 -0
  55. package/dist/self_host/secret_box.js +105 -0
  56. package/dist/self_host/stub_gateway.d.ts +60 -0
  57. package/dist/self_host/stub_gateway.js +397 -0
  58. package/dist/self_host/stub_main.d.ts +2 -0
  59. package/dist/self_host/stub_main.js +69 -0
  60. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  61. package/dist/self_host/subscription_test_gateway.js +25 -91
  62. package/dist/self_host/subscriptions/http.js +1 -0
  63. package/dist/self_host/subscriptions/index.d.ts +2 -2
  64. package/dist/self_host/subscriptions/index.js +2 -2
  65. package/dist/self_host/subscriptions/store.d.ts +41 -16
  66. package/dist/self_host/subscriptions/store.js +136 -32
  67. package/dist/telemetry/report.js +18 -0
  68. package/dist/types.d.ts +18 -0
  69. package/package.json +4 -3
  70. package/src/context/routing_context.ts +3 -1
  71. package/src/http/handler.ts +14 -2
  72. package/src/ingress/anthropic_messages.ts +19 -4
  73. package/src/ingress/chat_completions.ts +6 -1
  74. package/src/ingress/codex.ts +2 -2
  75. package/src/ingress/link.ts +1731 -0
  76. package/src/ingress/link_assets.ts +56 -0
  77. package/src/ingress/link_font.ts +9 -0
  78. package/src/ingress/models.ts +48 -2
  79. package/src/interaction/types.ts +4 -0
  80. package/src/link_client.ts +796 -0
  81. package/src/models/gateways.ts +3 -0
  82. package/src/models/link_errors.ts +157 -0
  83. package/src/models/subscriptions.ts +15 -1
  84. package/src/platform/platform.ts +330 -1
  85. package/src/protocol/input/router_model.ts +36 -1
  86. package/src/providers/execution.ts +24 -2
  87. package/src/providers/pi_options.ts +57 -1
  88. package/src/providers/provider_call.ts +15 -1
  89. package/src/providers/stream_finalization.ts +1 -0
  90. package/src/runtime/explicit_model.ts +21 -8
  91. package/src/runtime/harness_identity/extract.ts +21 -60
  92. package/src/runtime/link_budget.ts +75 -0
  93. package/src/runtime/link_grant_access.ts +116 -0
  94. package/src/runtime/link_in_flight.ts +46 -0
  95. package/src/runtime/prepare_routed_completion.ts +6 -1
  96. package/src/runtime/routed_runtime.ts +8 -0
  97. package/src/runtime/runtime_reporter.ts +3 -0
  98. package/src/self_host/config.ts +24 -1
  99. package/src/self_host/link_store.ts +782 -0
  100. package/src/self_host/main.ts +21 -4
  101. package/src/self_host/platform.ts +305 -11
  102. package/src/self_host/resolve.ts +172 -15
  103. package/src/self_host/secret_box.ts +112 -0
  104. package/src/self_host/stub_gateway.ts +497 -0
  105. package/src/self_host/stub_main.ts +72 -0
  106. package/src/self_host/subscription_test_gateway.ts +26 -95
  107. package/src/self_host/subscriptions/http.ts +1 -0
  108. package/src/self_host/subscriptions/index.ts +3 -0
  109. package/src/self_host/subscriptions/store.ts +167 -36
  110. package/src/telemetry/report.ts +17 -1
  111. package/src/types.ts +26 -0
  112. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  113. package/dist/self_host/subscriptions/test_support.js +0 -34
@@ -0,0 +1,564 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { HttpError } from "../http/errors.js";
3
+ import { openWithoutKey } from "./secret_box.js";
4
+ import { LINK_ACCESS_TOKEN_PREFIX, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
5
+ import { budgetLookbackMs, budgetStandings } from "../runtime/link_budget.js";
6
+ export const LINK_ACCESS_TOKEN_TTL_MS = 60 * 60_000;
7
+ const LINK_CODE_TTL_MS = 10 * 60_000;
8
+ // A rotated refresh token presented again this soon lost a race with its own
9
+ // rotation (two instances, or a retry after a lost response); later, it leaked.
10
+ export const LINK_REFRESH_RACE_MS = 60_000;
11
+ // Expired tokens are kept this long so they are told apart from unknown ones.
12
+ const LINK_TOKEN_RETENTION_MS = 24 * 60 * 60_000;
13
+ // Prefixes keep link tokens apart from gateway keys and from each other.
14
+ const REFRESH_TOKEN_PREFIX = "dlk_rt_";
15
+ const CODE_PREFIX = "dlk_code_";
16
+ const CLIENT_SECRET_PREFIX = "dlk_cs_";
17
+ // Where a stored API key belongs, which its encryption is bound to.
18
+ function keyPlace(id) {
19
+ return `link_api_keys:${id}:api_key`;
20
+ }
21
+ const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
22
+ link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
23
+ link_grants.credential_ids, link_grants.revoked_at, link_grants.revoked_by
24
+ FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
25
+ WHERE link_tokens.token_hash = ?`;
26
+ export class LinkStore {
27
+ db;
28
+ box;
29
+ constructor(db, box = null) {
30
+ this.db = db;
31
+ this.box = box;
32
+ db.run(`CREATE TABLE IF NOT EXISTS link_apps (
33
+ client_id TEXT PRIMARY KEY,
34
+ name TEXT NOT NULL,
35
+ redirect_uris TEXT NOT NULL,
36
+ client_secret_hash TEXT,
37
+ created_at INTEGER NOT NULL
38
+ )`);
39
+ db.run(`CREATE TABLE IF NOT EXISTS link_grants (
40
+ id TEXT PRIMARY KEY,
41
+ client_id TEXT NOT NULL REFERENCES link_apps (client_id),
42
+ credential_ids TEXT NOT NULL,
43
+ code_hash TEXT UNIQUE,
44
+ code_challenge TEXT,
45
+ redirect_uri TEXT,
46
+ code_expires_at INTEGER,
47
+ created_at INTEGER NOT NULL,
48
+ revoked_at INTEGER,
49
+ revoked_by TEXT
50
+ )`);
51
+ db.run(`CREATE TABLE IF NOT EXISTS link_tokens (
52
+ token_hash TEXT PRIMARY KEY,
53
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
54
+ kind TEXT NOT NULL,
55
+ expires_at INTEGER,
56
+ rotated_at INTEGER,
57
+ model TEXT,
58
+ thinking TEXT,
59
+ tags TEXT,
60
+ created_at INTEGER NOT NULL
61
+ )`);
62
+ db.run("CREATE INDEX IF NOT EXISTS link_tokens_grant_id ON link_tokens (grant_id)");
63
+ db.run(`CREATE TABLE IF NOT EXISTS link_usage (
64
+ request_id TEXT PRIMARY KEY,
65
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
66
+ received_at INTEGER NOT NULL,
67
+ model TEXT,
68
+ thinking TEXT,
69
+ tags TEXT NOT NULL,
70
+ input_tokens INTEGER NOT NULL,
71
+ output_tokens INTEGER NOT NULL,
72
+ cache_read_tokens INTEGER NOT NULL,
73
+ cache_write_tokens INTEGER NOT NULL
74
+ )`);
75
+ db.run("CREATE INDEX IF NOT EXISTS link_usage_grant_received ON link_usage (grant_id, received_at)");
76
+ // Added after link_grants shipped: a gateway database from before gains it.
77
+ const grantColumns = db.query("PRAGMA table_info(link_grants)").all();
78
+ if (!grantColumns.some((column) => column.name === "budget"))
79
+ db.run("ALTER TABLE link_grants ADD COLUMN budget TEXT");
80
+ // The user who approved the grant on the approval page.
81
+ if (!grantColumns.some((column) => column.name === "subject"))
82
+ db.run("ALTER TABLE link_grants ADD COLUMN subject TEXT");
83
+ const tokenColumns = db.query("PRAGMA table_info(link_tokens)").all();
84
+ if (!tokenColumns.some((column) => column.name === "pins"))
85
+ db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
86
+ const usageColumns = db.query("PRAGMA table_info(link_usage)").all();
87
+ if (!usageColumns.some((column) => column.name === "status"))
88
+ db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
89
+ // API keys users added on the approval page: one per user and provider.
90
+ db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
91
+ id TEXT PRIMARY KEY,
92
+ subject TEXT NOT NULL,
93
+ provider TEXT NOT NULL,
94
+ api_key TEXT NOT NULL,
95
+ created_at INTEGER NOT NULL,
96
+ UNIQUE (subject, provider)
97
+ )`);
98
+ this.encryptStored();
99
+ }
100
+ // Seal API keys stored before encryption was turned on, or under a key
101
+ // that no longer encrypts.
102
+ encryptStored() {
103
+ const box = this.box;
104
+ if (box === null)
105
+ return;
106
+ this.db.transaction(() => {
107
+ for (const row of this.db.query("SELECT * FROM link_api_keys").all()) {
108
+ if (box.current(row.api_key))
109
+ continue;
110
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [
111
+ box.seal(box.adopt(row.api_key, keyPlace(row.id)), keyPlace(row.id)),
112
+ row.id,
113
+ ]);
114
+ }
115
+ })();
116
+ }
117
+ seal(value, place) {
118
+ return this.box === null ? value : this.box.seal(value, place);
119
+ }
120
+ key(row) {
121
+ const stored = row.api_key;
122
+ return {
123
+ id: row.id,
124
+ subject: row.subject,
125
+ provider: row.provider,
126
+ apiKey: this.box === null ? openWithoutKey(stored) : this.box.open(stored, keyPlace(row.id)),
127
+ };
128
+ }
129
+ /** Store a user's API key for a provider, replacing their earlier one for it. */
130
+ addKey(subject, provider, apiKey, now = new Date()) {
131
+ const existing = this.keys(subject).find((key) => key.provider === provider);
132
+ if (existing !== undefined) {
133
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [this.seal(apiKey, keyPlace(existing.id)), existing.id]);
134
+ return { ...existing, apiKey };
135
+ }
136
+ const id = `key_${randomUUID().replaceAll("-", "")}`;
137
+ this.db.run("INSERT INTO link_api_keys (id, subject, provider, api_key, created_at) VALUES (?, ?, ?, ?, ?)", [id, subject, provider, this.seal(apiKey, keyPlace(id)), now.getTime()]);
138
+ return { id, subject, provider, apiKey };
139
+ }
140
+ /** Delete a user's API key; false when they have none by that id. */
141
+ removeKey(subject, id) {
142
+ return this.db.run("DELETE FROM link_api_keys WHERE id = ? AND subject = ?", [id, subject]).changes > 0;
143
+ }
144
+ /**
145
+ * Take a deleted plan or key out of every live grant; a grant left with
146
+ * nothing is revoked as the user's doing.
147
+ */
148
+ dropCredential(credentialId, now = new Date()) {
149
+ this.db.transaction(() => {
150
+ const grants = this.db
151
+ .query("SELECT id, credential_ids FROM link_grants WHERE revoked_at IS NULL")
152
+ .all();
153
+ for (const grant of grants) {
154
+ const ids = parseIds(grant.credential_ids);
155
+ if (!ids.includes(credentialId))
156
+ continue;
157
+ const left = ids.filter((id) => id !== credentialId);
158
+ if (left.length === 0)
159
+ this.revoke(grant.id, "user", now);
160
+ else
161
+ this.db.run("UPDATE link_grants SET credential_ids = ? WHERE id = ?", [JSON.stringify(left), grant.id]);
162
+ }
163
+ })();
164
+ }
165
+ /** The API keys a user added, oldest first. */
166
+ keys(subject) {
167
+ return this.db
168
+ .query("SELECT * FROM link_api_keys WHERE subject = ? ORDER BY created_at, rowid")
169
+ .all(subject)
170
+ .map((row) => this.key(row));
171
+ }
172
+ /** The API keys with these ids, whoever added them. */
173
+ keysWithIds(ids) {
174
+ return this.db
175
+ .query("SELECT * FROM link_api_keys ORDER BY created_at, rowid")
176
+ .all()
177
+ .filter((row) => ids.has(row.id))
178
+ .map((row) => this.key(row));
179
+ }
180
+ /** A grant's budget; empty when it has none or is unknown. */
181
+ budget(grantId) {
182
+ const row = this.db.query("SELECT budget FROM link_grants WHERE id = ?").get(grantId);
183
+ return parseBudget(row?.budget ?? null);
184
+ }
185
+ /** Replace a live grant's budget; false when none is live by that id. */
186
+ setBudget(grantId, budget) {
187
+ return this.db.run("UPDATE link_grants SET budget = ? WHERE id = ? AND revoked_at IS NULL", [budget.length === 0 ? null : JSON.stringify(budget), grantId]).changes > 0;
188
+ }
189
+ /** Each of a grant's budget windows as it stands now (see runtime/link_budget.ts). */
190
+ budgetStandings(grantId, now = new Date()) {
191
+ const budget = this.budget(grantId);
192
+ if (budget.length === 0)
193
+ return [];
194
+ const uses = this.db
195
+ .query(`SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
196
+ FROM link_usage WHERE grant_id = ? AND received_at > ?`)
197
+ .all(grantId, now.getTime() - budgetLookbackMs(budget))
198
+ .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
199
+ return budgetStandings(budget, uses, now);
200
+ }
201
+ /** Record what one of a grant's requests used; a repeated request id is ignored. */
202
+ recordUsage(entry) {
203
+ this.db.run(`INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
204
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
205
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
206
+ entry.requestId,
207
+ entry.grantId,
208
+ entry.receivedAt.getTime(),
209
+ entry.model,
210
+ entry.thinking,
211
+ JSON.stringify(entry.tags),
212
+ entry.inputTokens,
213
+ entry.outputTokens,
214
+ entry.cacheReadTokens,
215
+ entry.cacheWriteTokens,
216
+ entry.status,
217
+ ]);
218
+ }
219
+ /** What a grant's requests used, filtered by tags and receive time. */
220
+ usage(grantId, query) {
221
+ const rows = query.requestId !== undefined
222
+ ? this.db
223
+ .query("SELECT * FROM link_usage WHERE grant_id = ? AND request_id = ?")
224
+ .all(grantId, query.requestId)
225
+ : this.db
226
+ .query(`SELECT * FROM link_usage WHERE grant_id = ? AND received_at >= ? AND received_at < ?`)
227
+ .all(grantId, query.since?.getTime() ?? 0, query.until?.getTime() ?? Number.MAX_SAFE_INTEGER);
228
+ const filters = Object.entries(query.tags);
229
+ return summarizeLinkUsage(rows
230
+ .map((row) => ({ row, tags: JSON.parse(row.tags) }))
231
+ .filter(({ tags }) => filters.every(([key, value]) => tags[key] === value))
232
+ .map(({ row, tags }) => ({
233
+ model: row.model,
234
+ thinking: row.thinking,
235
+ tag: query.groupByTag === undefined ? null : tags[query.groupByTag] ?? null,
236
+ failed: row.status === "provider_error" || row.status === "selector_error",
237
+ inputTokens: row.input_tokens,
238
+ outputTokens: row.output_tokens,
239
+ cacheReadTokens: row.cache_read_tokens,
240
+ cacheWriteTokens: row.cache_write_tokens,
241
+ })), query.groupByTag !== undefined);
242
+ }
243
+ /** Register an app; a confidential one gets a secret, returned this once. */
244
+ registerApp(name, redirectUris, confidential = false, now = new Date()) {
245
+ const clientId = `lnk_${randomUUID().replaceAll("-", "")}`;
246
+ const clientSecret = confidential ? secret(CLIENT_SECRET_PREFIX) : undefined;
247
+ this.db.run("INSERT INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, ?, ?, ?)", [clientId, name, JSON.stringify(redirectUris), clientSecret === undefined ? null : hash(clientSecret), now.getTime()]);
248
+ return { clientId, name, redirectUris, confidential, ...(clientSecret === undefined ? {} : { clientSecret }) };
249
+ }
250
+ app(clientId) {
251
+ const row = this.db.query("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
252
+ return row === null ? null : appFromRow(row);
253
+ }
254
+ /**
255
+ * Create a grant awaiting its code exchange and return the code. With
256
+ * `grantId` (update mode), change that live grant of the app's plans and
257
+ * budget in place instead: its tokens keep working, and the code redeems
258
+ * for more tokens of the same grant.
259
+ */
260
+ approve(request, now = new Date()) {
261
+ const app = this.app(request.clientId);
262
+ if (app === null || !app.redirectUris.includes(request.redirectUri)) {
263
+ throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
264
+ }
265
+ const code = secret(CODE_PREFIX);
266
+ const budget = request.budget === undefined || request.budget.length === 0 ? null : JSON.stringify(request.budget);
267
+ if (request.grantId !== undefined) {
268
+ const updated = this.db.run(`UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
269
+ code_expires_at = ?
270
+ WHERE id = ? AND client_id = ? AND revoked_at IS NULL`, [
271
+ JSON.stringify(request.credentialIds),
272
+ budget,
273
+ hash(code),
274
+ request.codeChallenge,
275
+ request.redirectUri,
276
+ now.getTime() + LINK_CODE_TTL_MS,
277
+ request.grantId,
278
+ request.clientId,
279
+ ]).changes;
280
+ if (updated === 0)
281
+ throw new HttpError(400, "That connection no longer exists.", "invalid_request");
282
+ return code;
283
+ }
284
+ this.db.run(`INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
285
+ code_expires_at, created_at, budget, subject)
286
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
287
+ `lgr_${randomUUID().replaceAll("-", "")}`,
288
+ request.clientId,
289
+ JSON.stringify(request.credentialIds),
290
+ hash(code),
291
+ request.codeChallenge,
292
+ request.redirectUri,
293
+ now.getTime() + LINK_CODE_TTL_MS,
294
+ now.getTime(),
295
+ budget,
296
+ request.subject ?? null,
297
+ ]);
298
+ return code;
299
+ }
300
+ /** Redeem a code once: the grant's first tokens. */
301
+ exchangeCode(request, now = new Date()) {
302
+ this.authenticateClient(request.clientId, request.clientSecret);
303
+ return this.db.transaction(() => {
304
+ const row = this.db
305
+ .query("SELECT * FROM link_grants WHERE code_hash = ?")
306
+ .get(hash(request.code));
307
+ if (row === null
308
+ || row.revoked_at !== null
309
+ || row.client_id !== request.clientId
310
+ || row.redirect_uri !== request.redirectUri
311
+ || row.code_expires_at === null
312
+ || row.code_expires_at <= now.getTime()
313
+ || row.code_challenge !== request.codeChallenge) {
314
+ throw invalidGrant("The authorization code is invalid, expired, or already used.");
315
+ }
316
+ this.db.run("UPDATE link_grants SET code_hash = NULL, code_challenge = NULL, code_expires_at = NULL WHERE id = ?", [row.id]);
317
+ return {
318
+ accessToken: this.issue(row.id, "access", now, now.getTime() + LINK_ACCESS_TOKEN_TTL_MS),
319
+ refreshToken: this.issue(row.id, "refresh", now, null),
320
+ expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000,
321
+ };
322
+ })();
323
+ }
324
+ /**
325
+ * A new access token for a grant. A public client's refresh token rotates;
326
+ * a confidential client keeps the one it presented.
327
+ */
328
+ refresh(request, now = new Date()) {
329
+ const app = this.authenticateClient(request.clientId, request.clientSecret);
330
+ const presented = hash(request.refreshToken);
331
+ // The refusal is thrown after the transaction, so a revoke in it holds.
332
+ const result = this.db.transaction(() => {
333
+ const row = this.db.query(TOKEN_WITH_GRANT).get(presented);
334
+ if (row === null || row.kind !== "refresh" || row.client_id !== request.clientId || row.revoked_at !== null) {
335
+ return "invalid";
336
+ }
337
+ if (row.rotated_at !== null) {
338
+ if (now.getTime() - row.rotated_at <= LINK_REFRESH_RACE_MS)
339
+ return "race";
340
+ // A rotated refresh token came back long after: it leaked.
341
+ this.revoke(row.grant_id, "reuse_detected", now);
342
+ return "invalid";
343
+ }
344
+ const accessToken = this.issue(row.grant_id, "access", now, now.getTime() + LINK_ACCESS_TOKEN_TTL_MS);
345
+ if (app.confidential) {
346
+ return { accessToken, refreshToken: request.refreshToken, expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000 };
347
+ }
348
+ this.db.run("UPDATE link_tokens SET rotated_at = ? WHERE token_hash = ?", [now.getTime(), presented]);
349
+ return {
350
+ accessToken,
351
+ refreshToken: this.issue(row.grant_id, "refresh", now, null),
352
+ expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000,
353
+ };
354
+ })();
355
+ if (result === "race") {
356
+ throw new HttpError(400, "This refresh token was just rotated by another request. Use the tokens that request received.", "refresh_race");
357
+ }
358
+ if (result === "invalid")
359
+ throw invalidGrant("The refresh token is invalid or revoked.");
360
+ return result;
361
+ }
362
+ /** Mint a child token from the grant's access token. */
363
+ exchangeToken(request, now = new Date()) {
364
+ this.authenticateClient(request.clientId, request.clientSecret);
365
+ const subject = this.authenticate(request.subjectToken, now);
366
+ if (subject?.status !== "active"
367
+ || subject.grant.pins !== undefined
368
+ || subject.grant.clientId !== request.clientId) {
369
+ throw invalidGrant("subject_token must be a live access token of this client's grant.");
370
+ }
371
+ const accessToken = this.issue(subject.grant.id, "child", now, now.getTime() + request.expiresIn * 1000, {
372
+ pins: JSON.stringify(request.models.map((entry) => ({ model: entry.model, thinking: entry.thinking ?? null }))),
373
+ tags: Object.keys(request.tags).length === 0 ? null : JSON.stringify(request.tags),
374
+ });
375
+ return { accessToken, expiresIn: request.expiresIn, grantId: subject.grant.id };
376
+ }
377
+ /** What a presented access or child token is, or null when it is neither. */
378
+ authenticate(token, now = new Date()) {
379
+ if (!token.startsWith(LINK_ACCESS_TOKEN_PREFIX) && !token.startsWith(LINK_CHILD_TOKEN_PREFIX))
380
+ return null;
381
+ const row = this.db.query(TOKEN_WITH_GRANT).get(hash(token));
382
+ if (row === null || row.kind === "refresh")
383
+ return null;
384
+ if (row.revoked_at !== null) {
385
+ return { status: "revoked", revokedBy: row.revoked_by, revokedAt: new Date(row.revoked_at).toISOString() };
386
+ }
387
+ if (row.expires_at === null || row.expires_at <= now.getTime())
388
+ return { status: "expired" };
389
+ const pins = row.kind === "child" ? childPins(row) : undefined;
390
+ // A child token that names no model serves nothing.
391
+ if (pins?.length === 0)
392
+ return null;
393
+ return {
394
+ status: "active",
395
+ grant: {
396
+ id: row.grant_id,
397
+ clientId: row.client_id,
398
+ credentialIds: new Set(parseIds(row.credential_ids)),
399
+ ...(pins === undefined ? {} : { pins }),
400
+ ...(row.tags === null ? {} : { tags: JSON.parse(row.tags) }),
401
+ },
402
+ };
403
+ }
404
+ /** Revoke the grant any of its tokens names, when the client owns it (RFC 7009). */
405
+ revokeToken(request, now = new Date()) {
406
+ this.authenticateClient(request.clientId, request.clientSecret);
407
+ const row = this.db.query(TOKEN_WITH_GRANT).get(hash(request.token));
408
+ if (row === null || row.client_id !== request.clientId)
409
+ return;
410
+ // A child token ends only itself: a sandbox holding one cannot end the grant.
411
+ if (row.kind === "child")
412
+ this.db.run("DELETE FROM link_tokens WHERE token_hash = ?", [hash(request.token)]);
413
+ else
414
+ this.revoke(row.grant_id, "app", now);
415
+ }
416
+ /** The subscriptions a grant may use; empty once it is revoked. */
417
+ credentialIds(grantId) {
418
+ const row = this.db
419
+ .query("SELECT * FROM link_grants WHERE id = ? AND revoked_at IS NULL")
420
+ .get(grantId);
421
+ return new Set(row === null ? [] : parseIds(row.credential_ids));
422
+ }
423
+ /** The user who approved a grant; null when it has none or is unknown. */
424
+ subject(grantId) {
425
+ return this.db
426
+ .query("SELECT subject FROM link_grants WHERE id = ?")
427
+ .get(grantId)?.subject ?? null;
428
+ }
429
+ /** Grants that are not revoked, oldest first. */
430
+ grants() {
431
+ return this.db
432
+ .query(`SELECT link_grants.*, link_apps.name AS app_name FROM link_grants
433
+ JOIN link_apps ON link_apps.client_id = link_grants.client_id
434
+ WHERE link_grants.revoked_at IS NULL ORDER BY link_grants.created_at, link_grants.id`)
435
+ .all()
436
+ .map((row) => ({
437
+ id: row.id,
438
+ clientId: row.client_id,
439
+ appName: row.app_name,
440
+ credentialIds: parseIds(row.credential_ids),
441
+ createdAt: new Date(row.created_at).toISOString(),
442
+ budget: parseBudget(row.budget),
443
+ }));
444
+ }
445
+ /**
446
+ * Revoke a grant: its code and refresh tokens go, and its access and child
447
+ * tokens stop working. False when none is active by that id.
448
+ */
449
+ revoke(grantId, by, now = new Date()) {
450
+ const result = this.db.run("UPDATE link_grants SET revoked_at = ?, revoked_by = ?, code_hash = NULL WHERE id = ? AND revoked_at IS NULL", [now.getTime(), by, grantId]);
451
+ if (result.changes === 0)
452
+ return false;
453
+ this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND kind = 'refresh'", [grantId]);
454
+ return true;
455
+ }
456
+ /**
457
+ * The app a client id names, once it has proven its secret when it has one.
458
+ * A confidential client must send its secret; a public one must not.
459
+ */
460
+ authenticateClient(clientId, clientSecret) {
461
+ const row = this.db.query("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
462
+ const proven = row !== null && (row.client_secret_hash === null
463
+ ? !clientSecret
464
+ : clientSecret !== undefined && sameHash(row.client_secret_hash, hash(clientSecret)));
465
+ if (row === null || !proven) {
466
+ throw new HttpError(401, "Unknown client, or a missing or wrong client secret.", "invalid_client");
467
+ }
468
+ return appFromRow(row);
469
+ }
470
+ issue(grantId, kind, now, expiresAt, child = null) {
471
+ const stale = now.getTime() - LINK_TOKEN_RETENTION_MS;
472
+ // Rotated refresh tokens stay while the grant lives (revoking it deletes
473
+ // them): presenting one again is how a stolen refresh token is caught.
474
+ this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
475
+ const token = secret(kind === "access" ? LINK_ACCESS_TOKEN_PREFIX : kind === "child" ? LINK_CHILD_TOKEN_PREFIX : REFRESH_TOKEN_PREFIX);
476
+ this.db.run(`INSERT INTO link_tokens (token_hash, grant_id, kind, expires_at, pins, tags, created_at)
477
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [hash(token), grantId, kind, expiresAt, child?.pins ?? null, child?.tags ?? null, now.getTime()]);
478
+ return token;
479
+ }
480
+ }
481
+ function summarizeLinkUsage(requests, groupByTag) {
482
+ const empty = () => ({
483
+ requests: 0,
484
+ errors: 0,
485
+ inputTokens: 0,
486
+ outputTokens: 0,
487
+ cacheReadTokens: 0,
488
+ cacheWriteTokens: 0,
489
+ });
490
+ const add = (totals, request) => {
491
+ totals.requests += 1;
492
+ totals.errors += request.failed ? 1 : 0;
493
+ totals.inputTokens += request.inputTokens;
494
+ totals.outputTokens += request.outputTokens;
495
+ totals.cacheReadTokens += request.cacheReadTokens;
496
+ totals.cacheWriteTokens += request.cacheWriteTokens;
497
+ };
498
+ const total = empty();
499
+ const byModel = new Map();
500
+ const byTag = new Map();
501
+ for (const request of requests) {
502
+ add(total, request);
503
+ if (groupByTag) {
504
+ let tagged = byTag.get(request.tag);
505
+ if (tagged === undefined) {
506
+ tagged = { value: request.tag, ...empty() };
507
+ byTag.set(request.tag, tagged);
508
+ }
509
+ add(tagged, request);
510
+ }
511
+ const model = request.model ?? "unknown";
512
+ const key = `${model}\u0000${request.thinking ?? ""}`;
513
+ let entry = byModel.get(key);
514
+ if (entry === undefined) {
515
+ entry = { model, thinking: request.thinking, ...empty() };
516
+ byModel.set(key, entry);
517
+ }
518
+ add(entry, request);
519
+ }
520
+ return {
521
+ ...total,
522
+ byModel: [...byModel.values()].sort((a, b) => b.requests - a.requests || a.model.localeCompare(b.model)),
523
+ ...(groupByTag
524
+ ? {
525
+ byTag: [...byTag.values()].sort((a, b) => b.requests - a.requests || (a.value ?? "").localeCompare(b.value ?? "")),
526
+ }
527
+ : {}),
528
+ };
529
+ }
530
+ function secret(prefix) {
531
+ return `${prefix}${randomBytes(32).toString("base64url")}`;
532
+ }
533
+ function hash(value) {
534
+ return createHash("sha256").update(value).digest("hex");
535
+ }
536
+ function sameHash(a, b) {
537
+ return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
538
+ }
539
+ function invalidGrant(message) {
540
+ return new HttpError(400, message, "invalid_grant");
541
+ }
542
+ function appFromRow(row) {
543
+ return {
544
+ clientId: row.client_id,
545
+ name: row.name,
546
+ redirectUris: JSON.parse(row.redirect_uris),
547
+ confidential: row.client_secret_hash !== null,
548
+ };
549
+ }
550
+ // A child token's models. One minted before `pins` existed kept its one model
551
+ // in `model` and `thinking`.
552
+ function childPins(row) {
553
+ if (row.pins !== null)
554
+ return JSON.parse(row.pins);
555
+ return row.model === null ? [] : [{ model: row.model, thinking: row.thinking }];
556
+ }
557
+ function parseIds(value) {
558
+ return JSON.parse(value);
559
+ }
560
+ // An entry without maxTokens (a share-of-plan limit from before token caps) is no limit.
561
+ function parseBudget(value) {
562
+ const entries = value === null ? [] : JSON.parse(value);
563
+ return entries.filter((entry) => typeof entry.maxTokens === "number");
564
+ }
@@ -5,9 +5,16 @@
5
5
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
6
6
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
7
7
  * serves when present, and otherwise the default router.
8
- * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, saved model lists,
9
- * and prefix-cache state (default `dari-gateway.db`). It holds subscription
10
- * tokens.
8
+ * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, Dari Link grants,
9
+ * saved model lists, and prefix-cache state (default `dari-gateway.db`). It
10
+ * holds subscription tokens.
11
+ * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
12
+ * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
13
+ * rotation). Unset, they are stored as they are, and the Dari Link approval
14
+ * page takes nobody's subscriptions or keys.
15
+ * - `DARI_LINK_SESSION_SECRET`: signs the cookie that remembers a Dari Link
16
+ * approval page's user. Unset, each process makes its own, so a restart
17
+ * forgets who connected which plans.
11
18
  * - `DARI_AUTO_ROUTING_API_KEY`: choose among a router's models with Dari
12
19
  * Auto Routing; without it, `dari/routing` serves the first listed model.
13
20
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
@@ -14,6 +14,8 @@ import { checkProviderKey } from "../providers/key_check.js";
14
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
15
15
  import { allRouterModels, loadGatewayConfig } from "./config.js";
16
16
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
17
+ import { LinkStore } from "./link_store.js";
18
+ import { secretBoxFromEnv } from "./secret_box.js";
17
19
  import { PrefixStore } from "./prefix_store.js";
18
20
  import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
19
21
  import { SessionPinStore } from "./session_pin_store.js";
@@ -27,9 +29,16 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
27
29
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
28
30
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
29
31
  * serves when present, and otherwise the default router.
30
- * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, saved model lists,
31
- * and prefix-cache state (default `dari-gateway.db`). It holds subscription
32
- * tokens.
32
+ * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, Dari Link grants,
33
+ * saved model lists, and prefix-cache state (default `dari-gateway.db`). It
34
+ * holds subscription tokens.
35
+ * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
36
+ * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
37
+ * rotation). Unset, they are stored as they are, and the Dari Link approval
38
+ * page takes nobody's subscriptions or keys.
39
+ * - `DARI_LINK_SESSION_SECRET`: signs the cookie that remembers a Dari Link
40
+ * approval page's user. Unset, each process makes its own, so a restart
41
+ * forgets who connected which plans.
33
42
  * - `DARI_AUTO_ROUTING_API_KEY`: choose among a router's models with Dari
34
43
  * Auto Routing; without it, `dari/routing` serves the first listed model.
35
44
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
@@ -50,10 +59,15 @@ export async function startSelfHostedGateway(env = process.env) {
50
59
  if (created)
51
60
  chmodSync(databasePath, 0o600);
52
61
  db.exec("PRAGMA journal_mode = WAL");
53
- const subscriptions = new SubscriptionStore(db);
62
+ const secrets = secretBoxFromEnv(env.DARI_GATEWAY_ENCRYPTION_KEY);
63
+ if (secrets === null) {
64
+ console.warn("dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them");
65
+ }
66
+ const subscriptions = new SubscriptionStore(db, secrets);
54
67
  const prefixes = new PrefixStore(db);
55
68
  const sessionPins = new SessionPinStore(db);
56
69
  const routerModels = new RouterModelStore(db);
70
+ const links = new LinkStore(db, secrets);
57
71
  // Pi's provider auth reads each provider's standard key variable, such as
58
72
  // OPENAI_API_KEY, from this environment only.
59
73
  const piModels = builtinModels({
@@ -66,6 +80,7 @@ export async function startSelfHostedGateway(env = process.env) {
66
80
  routerModels,
67
81
  gatewayKeys,
68
82
  subscriptions,
83
+ links,
69
84
  prefixes,
70
85
  sessionPins,
71
86
  providerApiKey,
@@ -5,8 +5,8 @@ import { type SelfHostedResolverDeps } from "./resolve.js";
5
5
  import { type SubscriptionStore } from "./subscriptions/index.js";
6
6
  /**
7
7
  * The self-hosted platform: routers from the config file, subscriptions,
8
- * prefix-cache state, and session pins in the gateway's SQLite database, and one content-free
9
- * log line per request.
8
+ * Dari Link grants, prefix-cache state, and session pins in the gateway's
9
+ * SQLite database, and one content-free log line per request.
10
10
  */
11
11
  export declare function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "prefixHits"> & {
12
12
  prefixes: PrefixStore;