@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
@@ -0,0 +1,187 @@
1
+ /* Dari Link's rules, once, for every platform. A platform supplies its
2
+ storage (`LinkStore`: the self-hosted gateway's SQLite database, hosted
3
+ Dari's control plane) and its users (`LinkUsers`: who a key or a page
4
+ visitor is, and where their plans and API keys live); `linkPlatform` makes
5
+ the rest: approving grants, managing them, budgets, and the token protocol
6
+ (grants.ts). */
7
+ import { randomUUID } from "node:crypto";
8
+ import { HttpError } from "../http/errors.js";
9
+ import { budgetLookbackMs, budgetStandings, overBudgetUntil } from "./budget.js";
10
+ import { budgetExhausted, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
11
+ import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, } from "./grants.js";
12
+ export function linkPlatform(store, users) {
13
+ const protocol = linkGrants(store);
14
+ const standings = async (grant, now = new Date()) => (await linkBudgetStandings(store, grant, now)).map((standing) => ({
15
+ ...standing,
16
+ resetsAt: standing.resetsAt?.toISOString() ?? null,
17
+ }));
18
+ // A live grant of this user's; null for anyone else's.
19
+ const ownGrant = async (subject, grantId) => {
20
+ const grant = await store.grant(grantId);
21
+ return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
22
+ };
23
+ const revoke = (grantId) => store.revokeGrant(grantId, "user", Date.now());
24
+ return {
25
+ httpRedirectHosts: users.httpRedirectHosts ?? [],
26
+ approval: {
27
+ sessionSecret: () => users.sessionSecret(),
28
+ connectable: users.connectable,
29
+ keyProviders: users.keyProviders,
30
+ subscriptions: (subject) => users.plans(subject),
31
+ async addKey(subject, provider, apiKey) {
32
+ if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
33
+ throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
34
+ }
35
+ return await users.addKey(subject, provider, apiKey);
36
+ },
37
+ startConnect: (kind) => users.startConnect(kind),
38
+ completeConnect: (subject, session, response) => users.completeConnect(subject, session, response),
39
+ async remove(subject, credentialId) {
40
+ if (!(await users.plans(subject)).some((plan) => plan.id === credentialId))
41
+ return false;
42
+ // Every app loses it first, and a grant left with nothing ends, so a
43
+ // failure part way never leaves a grant on a deleted plan.
44
+ for (const grant of await store.grants(subject)) {
45
+ if (!grant.credentialIds.includes(credentialId))
46
+ continue;
47
+ const left = grant.credentialIds.filter((id) => id !== credentialId);
48
+ if (left.length === 0)
49
+ await revoke(grant.id);
50
+ else
51
+ await store.updateGrant(grant.id, { credentialIds: left });
52
+ }
53
+ return await users.removePlan(subject, credentialId);
54
+ },
55
+ async grant(subject, grantId, clientId) {
56
+ const grant = await ownGrant(subject, grantId);
57
+ return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget };
58
+ },
59
+ async approve(request) {
60
+ const owned = new Set((await users.plans(request.subject)).map((plan) => plan.id));
61
+ if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => owned.has(id))) {
62
+ throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
63
+ }
64
+ const app = await store.appRecord(request.clientId);
65
+ if (app === null || !app.redirectUris.includes(request.redirectUri)) {
66
+ throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
67
+ }
68
+ const code = linkSecret(LINK_CODE_PREFIX);
69
+ const now = Date.now();
70
+ const grantId = await store.saveGrant({
71
+ ...(request.grantId === undefined ? {} : { grantId: request.grantId }),
72
+ subject: request.subject,
73
+ clientId: request.clientId,
74
+ redirectUri: request.redirectUri,
75
+ codeHash: linkHash(code),
76
+ codeChallenge: request.codeChallenge,
77
+ codeExpiresAt: now + LINK_CODE_TTL_MS,
78
+ credentialIds: [...new Set(request.credentialIds)].sort(),
79
+ budget: request.budget,
80
+ now,
81
+ });
82
+ if (grantId === null)
83
+ throw new HttpError(400, "That connection no longer exists.", "invalid_request");
84
+ return { code };
85
+ },
86
+ async connections(subject) {
87
+ return await Promise.all((await store.grants(subject)).map(async (grant) => {
88
+ const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
89
+ return {
90
+ id: grant.id,
91
+ clientId: grant.clientId,
92
+ appName: grant.appName,
93
+ createdAt: grant.createdAt,
94
+ budget: await standings(grant),
95
+ subscriptions: await users.plansWithIds(grant.credentialIds),
96
+ usage,
97
+ };
98
+ }));
99
+ },
100
+ async disconnect(subject, grantId) {
101
+ return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
102
+ },
103
+ async setBudget(subject, grantId, budget) {
104
+ return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
105
+ },
106
+ },
107
+ async registerApp({ apiKey, name, redirectUris, confidential }) {
108
+ const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
109
+ const app = {
110
+ clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
111
+ name,
112
+ redirectUris,
113
+ confidential: clientSecret !== undefined,
114
+ };
115
+ await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
116
+ return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
117
+ },
118
+ async app(clientId) {
119
+ const record = await store.appRecord(clientId);
120
+ if (record === null)
121
+ return null;
122
+ const { clientSecretHash: _, ...app } = record;
123
+ return app;
124
+ },
125
+ exchangeCode: (request) => protocol.exchangeCode(request),
126
+ refresh: (request) => protocol.refresh(request),
127
+ exchangeToken: (request) => protocol.exchangeToken(request),
128
+ revokeToken: (request) => protocol.revokeToken(request),
129
+ async grant(accessToken) {
130
+ const { id } = await protocol.parentGrant(accessToken);
131
+ const grant = await store.grant(id);
132
+ // Revoked since the token was read.
133
+ if (grant === null)
134
+ throw linkGrantRevoked(null, null);
135
+ return {
136
+ id: grant.id,
137
+ clientId: grant.clientId,
138
+ appName: grant.appName,
139
+ createdAt: grant.createdAt,
140
+ budget: await standings(grant),
141
+ subscriptions: await users.plansWithIds(grant.credentialIds),
142
+ };
143
+ },
144
+ async usage({ accessToken, ...query }) {
145
+ const { id } = await protocol.parentGrant(accessToken);
146
+ // Read before the rows, so a request recorded in between is counted.
147
+ const completeThrough = users.completeThrough(id);
148
+ return { ...(await protocol.usage(id, query)), completeThrough };
149
+ },
150
+ async grants(apiKey) {
151
+ const subject = await users.manager(apiKey);
152
+ return (await store.grants(subject)).map(({ subject: _, ...grant }) => grant);
153
+ },
154
+ async setBudget({ apiKey, grantId, budget }) {
155
+ const subject = await users.manager(apiKey);
156
+ return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
157
+ },
158
+ async revokeGrant({ apiKey, grantId }) {
159
+ const subject = await users.manager(apiKey);
160
+ return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
161
+ },
162
+ };
163
+ }
164
+ /**
165
+ * The grant a link token serves a request for: null when the key is no link
166
+ * token. Throws the 401 a dead token gets, and the 424 a grant at its budget
167
+ * gets until its window rolls on.
168
+ */
169
+ export async function linkTokenGrant(store, token, now = new Date()) {
170
+ const auth = await linkGrants(store).authenticate(token, now);
171
+ if (auth === null)
172
+ return null;
173
+ if (auth.status === "expired")
174
+ throw linkTokenExpired();
175
+ if (auth.status === "revoked")
176
+ throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
177
+ const back = overBudgetUntil(await linkBudgetStandings(store, auth.grant, now));
178
+ if (back !== undefined)
179
+ throw linkUnavailableError(budgetExhausted(back));
180
+ return auth.grant;
181
+ }
182
+ async function linkBudgetStandings(store, grant, now) {
183
+ if (grant.budget.length === 0)
184
+ return [];
185
+ const uses = await store.budgetUses(grant.id, now.getTime() - budgetLookbackMs(grant.budget));
186
+ return budgetStandings(grant.budget, uses, now);
187
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The self-hosted gateway's Dari Link storage, in SQLite: registered apps, the
3
+ * grants users approve for them, each grant's tokens and usage, and the API
4
+ * keys users add. A grant names the subscriptions it may use. The rules over
5
+ * these tables are link/service.ts and link/grants.ts.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import { type SecretBox } from "../self_host/secret_box.js";
9
+ import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
10
+ import type { BudgetUse } from "./budget.js";
11
+ import { type LinkAppRecord, type LinkRevoker, type LinkTokenIssue, type LinkTokenRecord, type LinkUsageRecord } from "./grants.js";
12
+ import type { LinkGrantRecord, LinkStore } from "./service.js";
13
+ /** An API key a user added on the approval page, for one model provider or gateway. */
14
+ export type LinkApiKey = {
15
+ id: string;
16
+ subject: string;
17
+ provider: string;
18
+ apiKey: string;
19
+ };
20
+ export declare class SqliteLinkStore implements LinkStore {
21
+ private readonly db;
22
+ private readonly box;
23
+ constructor(db: Database, box?: SecretBox | null);
24
+ private encryptStored;
25
+ private seal;
26
+ private key;
27
+ /** Store a user's API key for a provider, replacing their earlier one for it. */
28
+ addKey(subject: string, provider: string, apiKey: string, now?: Date): LinkApiKey;
29
+ /** Delete a user's API key; false when they have none by that id. */
30
+ removeKey(subject: string, id: string): boolean;
31
+ /** The API keys a user added, oldest first. */
32
+ keys(subject: string): LinkApiKey[];
33
+ /** The API keys with these ids, whoever added them. */
34
+ keysWithIds(ids: ReadonlySet<string>): LinkApiKey[];
35
+ budgetUses(grantId: string, since: number): BudgetUse[];
36
+ /** Record what one of a grant's requests used; a repeated request id is ignored. */
37
+ recordUsage(entry: LinkUsageEntry): void;
38
+ usageRecords(grantId: string, query: Pick<LinkUsageQuery, "since" | "until" | "requestId">): LinkUsageRecord[];
39
+ addApp(app: LinkAppRecord, now?: Date): void;
40
+ appRecord(clientId: string): LinkAppRecord | null;
41
+ saveGrant(request: Parameters<LinkStore["saveGrant"]>[0]): string | null;
42
+ updateGrant(grantId: string, change: {
43
+ credentialIds?: string[];
44
+ budget?: LinkBudget[];
45
+ }): boolean;
46
+ grants(subject: string | null): LinkGrantRecord[];
47
+ grant(grantId: string): LinkGrantRecord | null;
48
+ redeemCode(request: Parameters<LinkStore["redeemCode"]>[0]): string | null;
49
+ tokenRecord(tokenHash: string): LinkTokenRecord | null;
50
+ issueTokens(request: {
51
+ grantId: string;
52
+ tokens: LinkTokenIssue[];
53
+ rotate?: string;
54
+ now: number;
55
+ }): "ok" | "race" | "revoked";
56
+ private insertTokens;
57
+ deleteToken(tokenHash: string): void;
58
+ /** The subscriptions a grant may use; empty once it is revoked. */
59
+ credentialIds(grantId: string): ReadonlySet<string>;
60
+ revokeGrant(grantId: string, by: LinkRevoker, now?: number): boolean;
61
+ }
62
+ export type LinkUsageEntry = {
63
+ requestId: string;
64
+ grantId: string;
65
+ receivedAt: Date;
66
+ model: string | null;
67
+ thinking: string | null;
68
+ tags: Record<string, string>;
69
+ inputTokens: number;
70
+ outputTokens: number;
71
+ cacheReadTokens: number;
72
+ cacheWriteTokens: number;
73
+ status: string;
74
+ };
@@ -0,0 +1,381 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { openWithoutKey } from "../self_host/secret_box.js";
3
+ import { LINK_TOKEN_RETENTION_MS, } from "./grants.js";
4
+ // Where a stored API key belongs, which its encryption is bound to.
5
+ function keyPlace(id) {
6
+ return `link_api_keys:${id}:api_key`;
7
+ }
8
+ const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
9
+ link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
10
+ link_grants.credential_ids, link_grants.budget, link_grants.revoked_at, link_grants.revoked_by
11
+ FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
12
+ WHERE link_tokens.token_hash = ?`;
13
+ const LIVE_GRANTS = `SELECT link_grants.id, link_grants.client_id, link_grants.credential_ids, link_grants.created_at,
14
+ link_grants.budget, link_grants.subject, link_apps.name AS app_name
15
+ FROM link_grants JOIN link_apps ON link_apps.client_id = link_grants.client_id
16
+ WHERE link_grants.revoked_at IS NULL`;
17
+ export class SqliteLinkStore {
18
+ db;
19
+ box;
20
+ constructor(db, box = null) {
21
+ this.db = db;
22
+ this.box = box;
23
+ db.run(`CREATE TABLE IF NOT EXISTS link_apps (
24
+ client_id TEXT PRIMARY KEY,
25
+ name TEXT NOT NULL,
26
+ redirect_uris TEXT NOT NULL,
27
+ client_secret_hash TEXT,
28
+ created_at INTEGER NOT NULL
29
+ )`);
30
+ db.run(`CREATE TABLE IF NOT EXISTS link_grants (
31
+ id TEXT PRIMARY KEY,
32
+ client_id TEXT NOT NULL REFERENCES link_apps (client_id),
33
+ credential_ids TEXT NOT NULL,
34
+ code_hash TEXT UNIQUE,
35
+ code_challenge TEXT,
36
+ redirect_uri TEXT,
37
+ code_expires_at INTEGER,
38
+ created_at INTEGER NOT NULL,
39
+ revoked_at INTEGER,
40
+ revoked_by TEXT
41
+ )`);
42
+ db.run(`CREATE TABLE IF NOT EXISTS link_tokens (
43
+ token_hash TEXT PRIMARY KEY,
44
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
45
+ kind TEXT NOT NULL,
46
+ expires_at INTEGER,
47
+ rotated_at INTEGER,
48
+ model TEXT,
49
+ thinking TEXT,
50
+ tags TEXT,
51
+ created_at INTEGER NOT NULL
52
+ )`);
53
+ db.run("CREATE INDEX IF NOT EXISTS link_tokens_grant_id ON link_tokens (grant_id)");
54
+ db.run(`CREATE TABLE IF NOT EXISTS link_usage (
55
+ request_id TEXT PRIMARY KEY,
56
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
57
+ received_at INTEGER NOT NULL,
58
+ model TEXT,
59
+ thinking TEXT,
60
+ tags TEXT NOT NULL,
61
+ input_tokens INTEGER NOT NULL,
62
+ output_tokens INTEGER NOT NULL,
63
+ cache_read_tokens INTEGER NOT NULL,
64
+ cache_write_tokens INTEGER NOT NULL
65
+ )`);
66
+ db.run("CREATE INDEX IF NOT EXISTS link_usage_grant_received ON link_usage (grant_id, received_at)");
67
+ // Added after link_grants shipped: a gateway database from before gains it.
68
+ const grantColumns = db.query("PRAGMA table_info(link_grants)").all();
69
+ if (!grantColumns.some((column) => column.name === "budget"))
70
+ db.run("ALTER TABLE link_grants ADD COLUMN budget TEXT");
71
+ // The user who approved the grant on the approval page.
72
+ if (!grantColumns.some((column) => column.name === "subject"))
73
+ db.run("ALTER TABLE link_grants ADD COLUMN subject TEXT");
74
+ const tokenColumns = db.query("PRAGMA table_info(link_tokens)").all();
75
+ if (!tokenColumns.some((column) => column.name === "pins"))
76
+ db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
77
+ const usageColumns = db.query("PRAGMA table_info(link_usage)").all();
78
+ if (!usageColumns.some((column) => column.name === "status"))
79
+ db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
80
+ // API keys users added on the approval page: one per user and provider.
81
+ db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
82
+ id TEXT PRIMARY KEY,
83
+ subject TEXT NOT NULL,
84
+ provider TEXT NOT NULL,
85
+ api_key TEXT NOT NULL,
86
+ created_at INTEGER NOT NULL,
87
+ UNIQUE (subject, provider)
88
+ )`);
89
+ this.encryptStored();
90
+ }
91
+ // Seal API keys stored before encryption was turned on, or under a key
92
+ // that no longer encrypts.
93
+ encryptStored() {
94
+ const box = this.box;
95
+ if (box === null)
96
+ return;
97
+ this.db.transaction(() => {
98
+ for (const row of this.db.query("SELECT * FROM link_api_keys").all()) {
99
+ if (box.current(row.api_key))
100
+ continue;
101
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [
102
+ box.seal(box.adopt(row.api_key, keyPlace(row.id)), keyPlace(row.id)),
103
+ row.id,
104
+ ]);
105
+ }
106
+ })();
107
+ }
108
+ seal(value, place) {
109
+ return this.box === null ? value : this.box.seal(value, place);
110
+ }
111
+ key(row) {
112
+ const stored = row.api_key;
113
+ return {
114
+ id: row.id,
115
+ subject: row.subject,
116
+ provider: row.provider,
117
+ apiKey: this.box === null ? openWithoutKey(stored) : this.box.open(stored, keyPlace(row.id)),
118
+ };
119
+ }
120
+ /** Store a user's API key for a provider, replacing their earlier one for it. */
121
+ addKey(subject, provider, apiKey, now = new Date()) {
122
+ const existing = this.keys(subject).find((key) => key.provider === provider);
123
+ if (existing !== undefined) {
124
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [this.seal(apiKey, keyPlace(existing.id)), existing.id]);
125
+ return { ...existing, apiKey };
126
+ }
127
+ const id = `key_${randomUUID().replaceAll("-", "")}`;
128
+ 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()]);
129
+ return { id, subject, provider, apiKey };
130
+ }
131
+ /** Delete a user's API key; false when they have none by that id. */
132
+ removeKey(subject, id) {
133
+ return this.db.run("DELETE FROM link_api_keys WHERE id = ? AND subject = ?", [id, subject]).changes > 0;
134
+ }
135
+ /** The API keys a user added, oldest first. */
136
+ keys(subject) {
137
+ return this.db
138
+ .query("SELECT * FROM link_api_keys WHERE subject = ? ORDER BY created_at, rowid")
139
+ .all(subject)
140
+ .map((row) => this.key(row));
141
+ }
142
+ /** The API keys with these ids, whoever added them. */
143
+ keysWithIds(ids) {
144
+ return this.db
145
+ .query("SELECT * FROM link_api_keys ORDER BY created_at, rowid")
146
+ .all()
147
+ .filter((row) => ids.has(row.id))
148
+ .map((row) => this.key(row));
149
+ }
150
+ budgetUses(grantId, since) {
151
+ return this.db
152
+ .query(`SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
153
+ FROM link_usage WHERE grant_id = ? AND received_at > ?`)
154
+ .all(grantId, since)
155
+ .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
156
+ }
157
+ /** Record what one of a grant's requests used; a repeated request id is ignored. */
158
+ recordUsage(entry) {
159
+ this.db.run(`INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
160
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
161
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
162
+ entry.requestId,
163
+ entry.grantId,
164
+ entry.receivedAt.getTime(),
165
+ entry.model,
166
+ entry.thinking,
167
+ JSON.stringify(entry.tags),
168
+ entry.inputTokens,
169
+ entry.outputTokens,
170
+ entry.cacheReadTokens,
171
+ entry.cacheWriteTokens,
172
+ entry.status,
173
+ ]);
174
+ }
175
+ usageRecords(grantId, query) {
176
+ const rows = query.requestId !== undefined
177
+ ? this.db
178
+ .query("SELECT * FROM link_usage WHERE grant_id = ? AND request_id = ?")
179
+ .all(grantId, query.requestId)
180
+ : this.db
181
+ .query(`SELECT * FROM link_usage WHERE grant_id = ? AND received_at >= ? AND received_at < ?`)
182
+ .all(grantId, query.since?.getTime() ?? 0, query.until?.getTime() ?? Number.MAX_SAFE_INTEGER);
183
+ return rows.map((row) => ({
184
+ status: row.status,
185
+ model: row.model,
186
+ thinking: row.thinking,
187
+ tags: JSON.parse(row.tags),
188
+ inputTokens: row.input_tokens,
189
+ outputTokens: row.output_tokens,
190
+ cacheReadTokens: row.cache_read_tokens,
191
+ cacheWriteTokens: row.cache_write_tokens,
192
+ }));
193
+ }
194
+ addApp(app, now = new Date()) {
195
+ this.db.run("INSERT INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, ?, ?, ?)", [app.clientId, app.name, JSON.stringify(app.redirectUris), app.clientSecretHash, now.getTime()]);
196
+ }
197
+ appRecord(clientId) {
198
+ const row = this.db.query("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
199
+ return row === null
200
+ ? null
201
+ : {
202
+ clientId: row.client_id,
203
+ name: row.name,
204
+ redirectUris: JSON.parse(row.redirect_uris),
205
+ confidential: row.client_secret_hash !== null,
206
+ clientSecretHash: row.client_secret_hash,
207
+ };
208
+ }
209
+ saveGrant(request) {
210
+ const budget = request.budget.length === 0 ? null : JSON.stringify(request.budget);
211
+ if (request.grantId !== undefined) {
212
+ const updated = this.db.run(`UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
213
+ code_expires_at = ?
214
+ WHERE id = ? AND client_id = ? AND subject = ? AND revoked_at IS NULL`, [
215
+ JSON.stringify(request.credentialIds),
216
+ budget,
217
+ request.codeHash,
218
+ request.codeChallenge,
219
+ request.redirectUri,
220
+ request.codeExpiresAt,
221
+ request.grantId,
222
+ request.clientId,
223
+ request.subject,
224
+ ]).changes;
225
+ return updated === 0 ? null : request.grantId;
226
+ }
227
+ const id = `lgr_${randomUUID().replaceAll("-", "")}`;
228
+ this.db.run(`INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
229
+ code_expires_at, created_at, budget, subject)
230
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
231
+ id,
232
+ request.clientId,
233
+ JSON.stringify(request.credentialIds),
234
+ request.codeHash,
235
+ request.codeChallenge,
236
+ request.redirectUri,
237
+ request.codeExpiresAt,
238
+ request.now,
239
+ budget,
240
+ request.subject,
241
+ ]);
242
+ return id;
243
+ }
244
+ updateGrant(grantId, change) {
245
+ return this.db.transaction(() => {
246
+ const changed = this.grant(grantId) !== null;
247
+ if (changed && change.credentialIds !== undefined) {
248
+ this.db.run("UPDATE link_grants SET credential_ids = ? WHERE id = ?", [JSON.stringify(change.credentialIds), grantId]);
249
+ }
250
+ if (changed && change.budget !== undefined) {
251
+ this.db.run("UPDATE link_grants SET budget = ? WHERE id = ?", [
252
+ change.budget.length === 0 ? null : JSON.stringify(change.budget),
253
+ grantId,
254
+ ]);
255
+ }
256
+ return changed;
257
+ })();
258
+ }
259
+ grants(subject) {
260
+ const order = " ORDER BY link_grants.created_at, link_grants.id";
261
+ const rows = subject === null
262
+ ? this.db.query(LIVE_GRANTS + order).all()
263
+ : this.db.query(`${LIVE_GRANTS} AND link_grants.subject = ?${order}`).all(subject);
264
+ return rows.map(grantRecord);
265
+ }
266
+ grant(grantId) {
267
+ const row = this.db.query(`${LIVE_GRANTS} AND link_grants.id = ?`).get(grantId);
268
+ return row === null ? null : grantRecord(row);
269
+ }
270
+ redeemCode(request) {
271
+ return this.db.transaction(() => {
272
+ const row = this.db
273
+ .query(`SELECT id FROM link_grants WHERE code_hash = ? AND client_id = ? AND redirect_uri = ? AND code_challenge = ?
274
+ AND code_expires_at > ? AND revoked_at IS NULL`)
275
+ .get(request.codeHash, request.clientId, request.redirectUri, request.codeChallenge, request.now);
276
+ if (row === null)
277
+ return null;
278
+ this.db.run("UPDATE link_grants SET code_hash = NULL, code_challenge = NULL, code_expires_at = NULL WHERE id = ?", [row.id]);
279
+ this.insertTokens(row.id, request.tokens, request.now);
280
+ return row.id;
281
+ })();
282
+ }
283
+ tokenRecord(tokenHash) {
284
+ const row = this.db.query(TOKEN_WITH_GRANT).get(tokenHash);
285
+ return row === null
286
+ ? null
287
+ : {
288
+ kind: row.kind,
289
+ expiresAt: row.expires_at,
290
+ rotatedAt: row.rotated_at,
291
+ pins: childPins(row),
292
+ tags: row.tags === null ? null : JSON.parse(row.tags),
293
+ grantId: row.grant_id,
294
+ clientId: row.client_id,
295
+ credentialIds: parseIds(row.credential_ids),
296
+ budget: parseBudget(row.budget),
297
+ revokedAt: row.revoked_at,
298
+ revokedBy: row.revoked_by,
299
+ usable: true,
300
+ };
301
+ }
302
+ issueTokens(request) {
303
+ return this.db.transaction(() => {
304
+ const live = this.db
305
+ .query("SELECT id FROM link_grants WHERE id = ? AND revoked_at IS NULL")
306
+ .get(request.grantId);
307
+ if (live === null)
308
+ return "revoked";
309
+ if (request.rotate !== undefined) {
310
+ const rotated = this.db.run("UPDATE link_tokens SET rotated_at = ? WHERE token_hash = ? AND rotated_at IS NULL", [request.now, request.rotate]).changes;
311
+ if (rotated === 0)
312
+ return "race";
313
+ }
314
+ const stale = request.now - LINK_TOKEN_RETENTION_MS;
315
+ // Rotated refresh tokens stay while the grant lives (revoking it deletes
316
+ // them): presenting one again is how a stolen refresh token is caught.
317
+ this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
318
+ this.insertTokens(request.grantId, request.tokens, request.now);
319
+ return "ok";
320
+ })();
321
+ }
322
+ insertTokens(grantId, tokens, now) {
323
+ for (const token of tokens) {
324
+ this.db.run(`INSERT INTO link_tokens (token_hash, grant_id, kind, expires_at, pins, tags, created_at)
325
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
326
+ token.tokenHash,
327
+ grantId,
328
+ token.kind,
329
+ token.expiresAt,
330
+ token.pins === undefined ? null : JSON.stringify(token.pins),
331
+ token.tags === undefined ? null : JSON.stringify(token.tags),
332
+ now,
333
+ ]);
334
+ }
335
+ }
336
+ deleteToken(tokenHash) {
337
+ this.db.run("DELETE FROM link_tokens WHERE token_hash = ?", [tokenHash]);
338
+ }
339
+ /** The subscriptions a grant may use; empty once it is revoked. */
340
+ credentialIds(grantId) {
341
+ const row = this.db
342
+ .query("SELECT * FROM link_grants WHERE id = ? AND revoked_at IS NULL")
343
+ .get(grantId);
344
+ return new Set(row === null ? [] : parseIds(row.credential_ids));
345
+ }
346
+ revokeGrant(grantId, by, now = Date.now()) {
347
+ const result = this.db.run("UPDATE link_grants SET revoked_at = ?, revoked_by = ?, code_hash = NULL WHERE id = ? AND revoked_at IS NULL", [now, by, grantId]);
348
+ if (result.changes === 0)
349
+ return false;
350
+ this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND kind = 'refresh'", [grantId]);
351
+ return true;
352
+ }
353
+ }
354
+ // A child token's models. One minted before `pins` existed kept its one model
355
+ // in `model` and `thinking`.
356
+ function childPins(row) {
357
+ if (row.kind !== "child")
358
+ return null;
359
+ if (row.pins !== null)
360
+ return JSON.parse(row.pins);
361
+ return row.model === null ? [] : [{ model: row.model, thinking: row.thinking }];
362
+ }
363
+ function grantRecord(row) {
364
+ return {
365
+ id: row.id,
366
+ clientId: row.client_id,
367
+ appName: row.app_name,
368
+ subject: row.subject,
369
+ credentialIds: parseIds(row.credential_ids),
370
+ createdAt: new Date(row.created_at).toISOString(),
371
+ budget: parseBudget(row.budget),
372
+ };
373
+ }
374
+ function parseIds(value) {
375
+ return JSON.parse(value);
376
+ }
377
+ // An entry without maxTokens (a share-of-plan limit from before token caps) is no limit.
378
+ function parseBudget(value) {
379
+ const entries = value === null ? [] : JSON.parse(value);
380
+ return entries.filter((entry) => typeof entry.maxTokens === "number");
381
+ }
@@ -231,6 +231,16 @@
231
231
  "max"
232
232
  ]
233
233
  },
234
+ {
235
+ "id": "meta/muse-spark-open",
236
+ "name": "Muse Spark Open",
237
+ "thinking_levels": [
238
+ "low",
239
+ "medium",
240
+ "high",
241
+ "xhigh"
242
+ ]
243
+ },
234
244
  {
235
245
  "id": "meta/muse-spark-1.2",
236
246
  "name": "Muse Spark 1.2",
@@ -251,6 +261,15 @@
251
261
  "max"
252
262
  ]
253
263
  },
264
+ {
265
+ "id": "moonshotai/Kimi-K3.1-Pro",
266
+ "name": "Kimi K3.1 Pro",
267
+ "thinking_levels": [
268
+ "low",
269
+ "high",
270
+ "max"
271
+ ]
272
+ },
254
273
  {
255
274
  "id": "zai-org/GLM-5.3",
256
275
  "name": "GLM 5.3",