@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.
- package/README.md +17 -20
- package/dist/http/handler.js +1 -1
- package/dist/ingress/anthropic_messages.js +1 -1
- package/dist/ingress/models.js +1 -1
- package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
- package/dist/{link_client.js → link/client.js} +5 -6
- package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
- package/dist/{ingress/link.js → link/endpoints.js} +158 -62
- package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
- package/dist/link/grants.d.ts +151 -0
- package/dist/link/grants.js +275 -0
- package/dist/link/key_providers.d.ts +6 -0
- package/dist/link/key_providers.js +21 -0
- package/dist/link/self_hosted.d.ts +3 -0
- package/dist/link/self_hosted.js +166 -0
- package/dist/link/service.d.ts +85 -0
- package/dist/link/service.js +187 -0
- package/dist/link/sqlite_store.d.ts +74 -0
- package/dist/link/sqlite_store.js +381 -0
- package/dist/models/canonical_models.json +19 -0
- package/dist/platform/platform.d.ts +42 -47
- package/dist/runtime/explicit_model.js +1 -1
- package/dist/runtime/prepare_routed_completion.js +1 -1
- package/dist/self_host/main.js +2 -2
- package/dist/self_host/platform.js +4 -249
- package/dist/self_host/resolve.d.ts +2 -2
- package/dist/self_host/resolve.js +3 -19
- package/dist/self_host/stub_gateway.js +3 -3
- package/dist/self_host/subscriptions/http.js +2 -2
- package/dist/telemetry/report.js +1 -1
- package/package.json +2 -2
- package/src/http/handler.ts +1 -1
- package/src/ingress/anthropic_messages.ts +1 -1
- package/src/ingress/models.ts +1 -1
- package/src/{link_client.ts → link/client.ts} +11 -14
- package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
- package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
- package/src/link/grants.ts +436 -0
- package/src/link/key_providers.ts +25 -0
- package/src/link/self_hosted.ts +186 -0
- package/src/link/service.ts +281 -0
- package/src/link/sqlite_store.ts +512 -0
- package/src/models/canonical_models.json +19 -0
- package/src/platform/platform.ts +39 -45
- package/src/runtime/explicit_model.ts +1 -1
- package/src/runtime/prepare_routed_completion.ts +1 -1
- package/src/self_host/main.ts +2 -2
- package/src/self_host/platform.ts +5 -267
- package/src/self_host/resolve.ts +6 -21
- package/src/self_host/stub_gateway.ts +3 -3
- package/src/self_host/subscriptions/http.ts +2 -2
- package/src/telemetry/report.ts +1 -1
- package/dist/self_host/link_store.d.ts +0 -167
- package/dist/self_host/link_store.js +0 -564
- package/src/self_host/link_store.ts +0 -782
- /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
- /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
- /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
- /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
- /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
- /package/dist/{models/link_errors.js → link/errors.js} +0 -0
- /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
- /package/dist/{ingress/link_font.js → link/font.js} +0 -0
- /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
- /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
- /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
- /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
- /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
- /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
|
@@ -1,564 +0,0 @@
|
|
|
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
|
-
}
|