@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,436 @@
1
+ /* The Dari Link token protocol, once, for every platform: redeeming a code,
2
+ refreshing, minting child tokens, telling what a presented token is,
3
+ revoking, and totalling usage. A platform supplies only storage (`LinkRepo`):
4
+ the self-hosted gateway its SQLite database, hosted Dari its control plane.
5
+
6
+ Every token is its own row holding only the token's SHA-256:
7
+
8
+ - an access token lasts an hour, whatever is issued after it;
9
+ - a refresh token does not expire. A public client's rotates on use:
10
+ presenting the rotated one again within a minute is refused as a lost
11
+ race, and later reuse revokes the grant. A confidential client, which
12
+ also proves its secret, keeps its own;
13
+ - a child token serves only its models, for up to twelve hours, and cannot
14
+ refresh, mint, or read the grant.
15
+
16
+ Revoking the grant stops them all at once. */
17
+
18
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
19
+
20
+ import { HttpError } from "../http/errors.js";
21
+ import { linkGrantRevoked, linkTokenExpired } from "./errors.js";
22
+ import type {
23
+ LinkApp,
24
+ LinkBudget,
25
+ LinkChildToken,
26
+ LinkClient,
27
+ LinkCodeExchange,
28
+ LinkTokenExchange,
29
+ LinkTokens,
30
+ LinkUsage,
31
+ LinkUsageQuery,
32
+ LinkUsageTotals,
33
+ } from "../platform/platform.js";
34
+ import { LINK_ACCESS_TOKEN_PREFIX, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
35
+
36
+ export const LINK_ACCESS_TOKEN_TTL_MS = 60 * 60_000;
37
+ export const LINK_CODE_TTL_MS = 10 * 60_000;
38
+ // A rotated refresh token presented again this soon lost a race with its own
39
+ // rotation (two instances, or a retry after a lost response); later, it leaked.
40
+ export const LINK_REFRESH_RACE_MS = 60_000;
41
+ // Expired tokens are kept this long so they are told apart from unknown ones.
42
+ export const LINK_TOKEN_RETENTION_MS = 24 * 60 * 60_000;
43
+
44
+ // Prefixes keep link tokens apart from gateway keys and from each other.
45
+ export const LINK_REFRESH_TOKEN_PREFIX = "dlk_rt_";
46
+ export const LINK_CODE_PREFIX = "dlk_code_";
47
+ export const LINK_CLIENT_SECRET_PREFIX = "dlk_cs_";
48
+
49
+ export type LinkRevoker = "user" | "app" | "reuse_detected";
50
+ export type LinkTokenKind = "access" | "refresh" | "child";
51
+ export type LinkPin = { model: string; thinking: string | null };
52
+
53
+ export type ActiveLinkGrant = {
54
+ id: string;
55
+ clientId: string;
56
+ credentialIds: ReadonlySet<string>;
57
+ budget: LinkBudget[];
58
+ // Set for a child token: the models it serves, each with its pinned thinking.
59
+ pins?: LinkPin[];
60
+ tags?: Record<string, string>;
61
+ };
62
+
63
+ /** What a presented link token is; null when it is not one the platform issued. */
64
+ export type LinkTokenAuth =
65
+ | { status: "active"; grant: ActiveLinkGrant }
66
+ | { status: "expired" }
67
+ | { status: "revoked"; revokedBy: string | null; revokedAt: string | null };
68
+
69
+ /** A registered app as stored: with the hash of a confidential client's secret. */
70
+ export type LinkAppRecord = LinkApp & { clientSecretHash: string | null };
71
+
72
+ /** A stored token with the grant it belongs to. Times are epoch milliseconds. */
73
+ export type LinkTokenRecord = {
74
+ kind: LinkTokenKind;
75
+ expiresAt: number | null;
76
+ rotatedAt: number | null;
77
+ pins: LinkPin[] | null;
78
+ tags: Record<string, string> | null;
79
+ grantId: string;
80
+ clientId: string;
81
+ credentialIds: string[];
82
+ // The grant's budget.
83
+ budget: LinkBudget[];
84
+ revokedAt: number | null;
85
+ revokedBy: string | null;
86
+ // False when the platform no longer serves the grant for a reason of its
87
+ // own (hosted: its user left the organization); its tokens then read as
88
+ // unknown.
89
+ usable: boolean;
90
+ };
91
+
92
+ /** A token to store: its hash, never the token. */
93
+ export type LinkTokenIssue = {
94
+ tokenHash: string;
95
+ kind: LinkTokenKind;
96
+ expiresAt: number | null;
97
+ pins?: LinkPin[];
98
+ tags?: Record<string, string>;
99
+ };
100
+
101
+ /** One request's usage as stored. */
102
+ export type LinkUsageRecord = Omit<LinkUsageTotals, "requests" | "errors"> & {
103
+ // The request's outcome, as the request record's `status`.
104
+ status: string | null;
105
+ model: string | null;
106
+ thinking: string | null;
107
+ tags: Record<string, string>;
108
+ };
109
+
110
+ type MaybePromise<T> = T | Promise<T>;
111
+
112
+ /**
113
+ * Storage for the token protocol. Each method is one atomic step; the rules
114
+ * that decide between them are `linkGrants`'s.
115
+ */
116
+ export type LinkRepo = {
117
+ /** The app a client id names; null for an unknown or disabled one. */
118
+ appRecord(clientId: string): MaybePromise<LinkAppRecord | null>;
119
+ /**
120
+ * Consume a live grant's unexpired code when the client, redirect URI, and
121
+ * PKCE challenge are the ones it was issued for, and store its first tokens
122
+ * in the same step: the grant's id, once.
123
+ */
124
+ redeemCode(request: {
125
+ codeHash: string;
126
+ clientId: string;
127
+ redirectUri: string;
128
+ codeChallenge: string;
129
+ tokens: LinkTokenIssue[];
130
+ now: number;
131
+ }): MaybePromise<string | null>;
132
+ /** The token with this hash and its grant; null when there is none. */
133
+ tokenRecord(tokenHash: string): MaybePromise<LinkTokenRecord | null>;
134
+ /**
135
+ * Store tokens for a grant, all or none. With `rotate`, also mark that
136
+ * refresh token rotated: `race` when another request already did. `revoked`
137
+ * when the grant is no longer live.
138
+ */
139
+ issueTokens(request: {
140
+ grantId: string;
141
+ tokens: LinkTokenIssue[];
142
+ rotate?: string;
143
+ now: number;
144
+ }): MaybePromise<"ok" | "race" | "revoked">;
145
+ /** Delete one token. */
146
+ deleteToken(tokenHash: string): MaybePromise<void>;
147
+ /**
148
+ * Revoke a grant: its code and refresh tokens go, and its access and child
149
+ * tokens stop working. False when none is live by that id.
150
+ */
151
+ revokeGrant(grantId: string, by: LinkRevoker, now: number): MaybePromise<boolean>;
152
+ /** A grant's requests, received in the time range or the one by that id. */
153
+ usageRecords(
154
+ grantId: string,
155
+ query: Pick<LinkUsageQuery, "since" | "until" | "requestId">,
156
+ ): MaybePromise<LinkUsageRecord[]>;
157
+ };
158
+
159
+ /** The token protocol over a platform's storage. `now` is for tests. */
160
+ export function linkGrants(repo: LinkRepo) {
161
+ const client = async ({ clientId, clientSecret }: LinkClient): Promise<LinkAppRecord> => {
162
+ const app = await repo.appRecord(clientId);
163
+ // A confidential client must send its secret; a public one must not.
164
+ const proven = app !== null && (app.clientSecretHash === null
165
+ ? !clientSecret
166
+ : clientSecret !== undefined && sameText(app.clientSecretHash, linkHash(clientSecret)));
167
+ if (app === null || !proven) {
168
+ throw new HttpError(401, "Unknown client, or a missing or wrong client secret.", "invalid_client");
169
+ }
170
+ return app;
171
+ };
172
+
173
+ const issue = async (
174
+ grantId: string,
175
+ kinds: Array<Omit<LinkTokenIssue, "tokenHash">>,
176
+ now: Date,
177
+ rotate?: string,
178
+ ): Promise<string[]> => {
179
+ const tokens = kinds.map((entry) => linkSecret(TOKEN_PREFIX[entry.kind]));
180
+ const result = await repo.issueTokens({
181
+ grantId,
182
+ tokens: kinds.map((entry, index) => ({ ...entry, tokenHash: linkHash(tokens[index]!) })),
183
+ ...(rotate === undefined ? {} : { rotate }),
184
+ now: now.getTime(),
185
+ });
186
+ if (result === "race") {
187
+ throw new HttpError(
188
+ 400,
189
+ "This refresh token was just rotated by another request. Use the tokens that request received.",
190
+ "refresh_race",
191
+ );
192
+ }
193
+ if (result === "revoked") throw invalidGrant("The refresh token is invalid or revoked.");
194
+ return tokens;
195
+ };
196
+
197
+ const access = (now: Date): Omit<LinkTokenIssue, "tokenHash"> => ({
198
+ kind: "access",
199
+ expiresAt: now.getTime() + LINK_ACCESS_TOKEN_TTL_MS,
200
+ });
201
+
202
+ const authenticate = async (token: string, now = new Date()): Promise<LinkTokenAuth | null> => {
203
+ if (!isLinkToken(token)) return null;
204
+ return linkTokenAuth(await repo.tokenRecord(linkHash(token)), now);
205
+ };
206
+
207
+ return {
208
+ /** What a presented access or child token is, or null when it is neither. */
209
+ authenticate,
210
+
211
+ /** Redeem a code once: the grant's first tokens. */
212
+ async exchangeCode(request: LinkCodeExchange, now = new Date()): Promise<LinkTokens> {
213
+ await client(request);
214
+ // The code is spent only with its tokens stored, so a failed step can be retried.
215
+ const accessToken = linkSecret(TOKEN_PREFIX.access);
216
+ const refreshToken = linkSecret(TOKEN_PREFIX.refresh);
217
+ const grantId = await repo.redeemCode({
218
+ codeHash: linkHash(request.code),
219
+ clientId: request.clientId,
220
+ redirectUri: request.redirectUri,
221
+ codeChallenge: request.codeChallenge,
222
+ tokens: [
223
+ { ...access(now), tokenHash: linkHash(accessToken) },
224
+ { kind: "refresh", expiresAt: null, tokenHash: linkHash(refreshToken) },
225
+ ],
226
+ now: now.getTime(),
227
+ });
228
+ if (grantId === null) throw invalidGrant("The authorization code is invalid, expired, or already used.");
229
+ return { accessToken, refreshToken, expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000 };
230
+ },
231
+
232
+ /**
233
+ * A new access token for a grant. A public client's refresh token rotates;
234
+ * a confidential client keeps the one it presented.
235
+ */
236
+ async refresh(request: LinkClient & { refreshToken: string }, now = new Date()): Promise<LinkTokens> {
237
+ const app = await client(request);
238
+ const presented = linkHash(request.refreshToken);
239
+ const record = await repo.tokenRecord(presented);
240
+ if (record === null || record.kind !== "refresh" || record.clientId !== request.clientId || record.revokedAt !== null) {
241
+ throw invalidGrant("The refresh token is invalid or revoked.");
242
+ }
243
+ if (record.rotatedAt !== null) {
244
+ if (now.getTime() - record.rotatedAt > LINK_REFRESH_RACE_MS) {
245
+ // A rotated refresh token came back long after: it leaked.
246
+ await repo.revokeGrant(record.grantId, "reuse_detected", now.getTime());
247
+ throw invalidGrant("The refresh token is invalid or revoked.");
248
+ }
249
+ throw new HttpError(
250
+ 400,
251
+ "This refresh token was just rotated by another request. Use the tokens that request received.",
252
+ "refresh_race",
253
+ );
254
+ }
255
+ if (app.confidential) {
256
+ const [accessToken] = await issue(record.grantId, [access(now)], now);
257
+ return { accessToken: accessToken!, refreshToken: request.refreshToken, expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000 };
258
+ }
259
+ const [accessToken, refreshToken] = await issue(
260
+ record.grantId,
261
+ [access(now), { kind: "refresh", expiresAt: null }],
262
+ now,
263
+ presented,
264
+ );
265
+ return { accessToken: accessToken!, refreshToken: refreshToken!, expiresIn: LINK_ACCESS_TOKEN_TTL_MS / 1000 };
266
+ },
267
+
268
+ /** Mint a child token from the grant's access token (RFC 8693). */
269
+ async exchangeToken(request: LinkTokenExchange, now = new Date()): Promise<LinkChildToken> {
270
+ await client(request);
271
+ const subject = await authenticate(request.subjectToken, now);
272
+ if (subject?.status !== "active" || subject.grant.pins !== undefined || subject.grant.clientId !== request.clientId) {
273
+ throw invalidGrant("subject_token must be a live access token of this client's grant.");
274
+ }
275
+ const [accessToken] = await issue(
276
+ subject.grant.id,
277
+ [{
278
+ kind: "child",
279
+ expiresAt: now.getTime() + request.expiresIn * 1000,
280
+ pins: request.models.map((entry) => ({ model: entry.model, thinking: entry.thinking ?? null })),
281
+ ...(Object.keys(request.tags).length === 0 ? {} : { tags: request.tags }),
282
+ }],
283
+ now,
284
+ );
285
+ return { accessToken: accessToken!, expiresIn: request.expiresIn, grantId: subject.grant.id };
286
+ },
287
+
288
+ /** Revoke the grant any of its tokens names, when the client owns it (RFC 7009). */
289
+ async revokeToken(request: LinkClient & { token: string }, now = new Date()): Promise<void> {
290
+ await client(request);
291
+ const tokenHash = linkHash(request.token);
292
+ const record = await repo.tokenRecord(tokenHash);
293
+ if (record === null || record.clientId !== request.clientId) return;
294
+ // A child token ends only itself: a sandbox holding one cannot end the grant.
295
+ if (record.kind === "child") await repo.deleteToken(tokenHash);
296
+ else await repo.revokeGrant(record.grantId, "app", now.getTime());
297
+ },
298
+
299
+ /**
300
+ * The live grant a grant's own access token names. Throws the 401 a dead
301
+ * token gets, and 403 for a child token, which cannot read its grant or
302
+ * its usage.
303
+ */
304
+ async parentGrant(accessToken: string, now = new Date()): Promise<ActiveLinkGrant> {
305
+ const auth = await authenticate(accessToken, now);
306
+ if (auth === null) throw new HttpError(401, "Missing or invalid Dari Link access token.", "authentication_error");
307
+ if (auth.status === "expired") throw linkTokenExpired();
308
+ if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
309
+ if (auth.grant.pins !== undefined) {
310
+ throw new HttpError(403, "A child token cannot read its grant or its usage.", "permission_denied");
311
+ }
312
+ return auth.grant;
313
+ },
314
+
315
+ /** What a grant's requests used, filtered by tags and receive time. */
316
+ async usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Promise<Omit<LinkUsage, "completeThrough">> {
317
+ return summarizeLinkUsage(await repo.usageRecords(grantId, query), query.tags, query.groupByTag);
318
+ },
319
+ };
320
+ }
321
+
322
+ export type LinkGrants = ReturnType<typeof linkGrants>;
323
+
324
+ const TOKEN_PREFIX: Record<LinkTokenKind, string> = {
325
+ access: LINK_ACCESS_TOKEN_PREFIX,
326
+ child: LINK_CHILD_TOKEN_PREFIX,
327
+ refresh: LINK_REFRESH_TOKEN_PREFIX,
328
+ };
329
+
330
+ /** Whether a presented key is shaped like an access or child token. */
331
+ export function isLinkToken(token: string): boolean {
332
+ return token.startsWith(LINK_ACCESS_TOKEN_PREFIX) || token.startsWith(LINK_CHILD_TOKEN_PREFIX);
333
+ }
334
+
335
+ /** What a stored access or child token is now; null when it serves nothing. */
336
+ export function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null {
337
+ if (record === null || record.kind === "refresh") return null;
338
+ if (record.revokedAt !== null) {
339
+ return { status: "revoked", revokedBy: record.revokedBy, revokedAt: new Date(record.revokedAt).toISOString() };
340
+ }
341
+ if (record.expiresAt === null || record.expiresAt <= now.getTime()) return { status: "expired" };
342
+ if (!record.usable) return null;
343
+ const pins = record.kind === "child" ? record.pins ?? [] : undefined;
344
+ // A child token that names no model serves nothing.
345
+ if (pins?.length === 0) return null;
346
+ return {
347
+ status: "active",
348
+ grant: {
349
+ id: record.grantId,
350
+ clientId: record.clientId,
351
+ credentialIds: new Set(record.credentialIds),
352
+ budget: record.budget,
353
+ ...(pins === undefined ? {} : { pins }),
354
+ ...(record.tags === null ? {} : { tags: record.tags }),
355
+ },
356
+ };
357
+ }
358
+
359
+ /** Totals of a grant's requests carrying every given tag, by model and optionally by one tag's values. */
360
+ export function summarizeLinkUsage(
361
+ records: readonly LinkUsageRecord[],
362
+ tags: Record<string, string>,
363
+ groupByTag?: string,
364
+ ): Omit<LinkUsage, "completeThrough"> {
365
+ const empty = (): LinkUsageTotals => ({
366
+ requests: 0,
367
+ errors: 0,
368
+ inputTokens: 0,
369
+ outputTokens: 0,
370
+ cacheReadTokens: 0,
371
+ cacheWriteTokens: 0,
372
+ });
373
+ const add = (totals: LinkUsageTotals, record: LinkUsageRecord) => {
374
+ totals.requests += 1;
375
+ // A request the provider or Dari failed; an aborted one is the client's choice.
376
+ totals.errors += record.status === "provider_error" || record.status === "selector_error" ? 1 : 0;
377
+ totals.inputTokens += record.inputTokens;
378
+ totals.outputTokens += record.outputTokens;
379
+ totals.cacheReadTokens += record.cacheReadTokens;
380
+ totals.cacheWriteTokens += record.cacheWriteTokens;
381
+ };
382
+ const filters = Object.entries(tags);
383
+ const total = empty();
384
+ const byModel = new Map<string, LinkUsage["byModel"][number]>();
385
+ const byTag = new Map<string | null, NonNullable<LinkUsage["byTag"]>[number]>();
386
+ for (const record of records) {
387
+ if (!filters.every(([key, value]) => record.tags[key] === value)) continue;
388
+ add(total, record);
389
+ if (groupByTag !== undefined) {
390
+ const value = record.tags[groupByTag] ?? null;
391
+ let tagged = byTag.get(value);
392
+ if (tagged === undefined) {
393
+ tagged = { value, ...empty() };
394
+ byTag.set(value, tagged);
395
+ }
396
+ add(tagged, record);
397
+ }
398
+ const model = record.model ?? "unknown";
399
+ const key = `${model}\u0000${record.thinking ?? ""}`;
400
+ let entry = byModel.get(key);
401
+ if (entry === undefined) {
402
+ entry = { model, thinking: record.thinking, ...empty() };
403
+ byModel.set(key, entry);
404
+ }
405
+ add(entry, record);
406
+ }
407
+ return {
408
+ ...total,
409
+ byModel: [...byModel.values()].sort((a, b) => b.requests - a.requests || a.model.localeCompare(b.model)),
410
+ ...(groupByTag === undefined
411
+ ? {}
412
+ : {
413
+ byTag: [...byTag.values()].sort(
414
+ (a, b) => b.requests - a.requests || (a.value ?? "").localeCompare(b.value ?? ""),
415
+ ),
416
+ }),
417
+ };
418
+ }
419
+
420
+ /** A new secret: a code, a token, or a client secret. */
421
+ export function linkSecret(prefix: string): string {
422
+ return `${prefix}${randomBytes(32).toString("base64url")}`;
423
+ }
424
+
425
+ /** How a secret is stored. */
426
+ export function linkHash(value: string): string {
427
+ return createHash("sha256").update(value).digest("hex");
428
+ }
429
+
430
+ function sameText(a: string, b: string): boolean {
431
+ return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
432
+ }
433
+
434
+ function invalidGrant(message: string): HttpError {
435
+ return new HttpError(400, message, "invalid_grant");
436
+ }
@@ -0,0 +1,25 @@
1
+ import { getBuiltinProviders } from "@mupt-ai/pi-ai/providers/all";
2
+ import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
3
+
4
+ import { CANONICAL_MODELS } from "../models/canonical.js";
5
+ import { LINK_KEY_GATEWAYS, gatewayFor } from "../models/gateways.js";
6
+ import type { LinkKeyProvider } from "../platform/platform.js";
7
+
8
+ const PROVIDER_NAMES: Record<string, string> = {
9
+ anthropic: "Anthropic",
10
+ openai: "OpenAI",
11
+ meta: "Meta",
12
+ moonshotai: "Moonshot AI",
13
+ xai: "xAI",
14
+ };
15
+
16
+ /**
17
+ * Whose API key a user can add on the approval page: each provider with
18
+ * catalog models the gateway can call with a key, then the gateways.
19
+ */
20
+ export const LINK_KEY_PROVIDERS: readonly LinkKeyProvider[] = [
21
+ ...[...new Set(CANONICAL_MODELS.map((model) => providerForModel(model.id)))]
22
+ .filter((provider) => (getBuiltinProviders() as readonly string[]).includes(provider))
23
+ .map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
24
+ ...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway)!.label })),
25
+ ];
@@ -0,0 +1,186 @@
1
+ /* Dari Link on the self-hosted gateway: users are subjects the approval page
2
+ remembers in a signed cookie, their plans are the gateway's own subscription
3
+ store and the API keys they add, and a gateway key manages every grant. */
4
+
5
+ import { randomBytes, randomUUID } from "node:crypto";
6
+
7
+ import { HttpError } from "../http/errors.js";
8
+ import type { LinkPlatform, LinkSubscription } from "../platform/platform.js";
9
+ import { checkProviderKey } from "../providers/key_check.js";
10
+ import { gatewayKeyIndex, type SelfHostedResolverDeps } from "../self_host/resolve.js";
11
+ import {
12
+ CODEX_APPROVAL_PENDING,
13
+ META_APPROVAL_PENDING,
14
+ OPENCODE_APPROVAL_PENDING,
15
+ SUBSCRIPTION_PROVIDERS,
16
+ SubscriptionOAuthInputError,
17
+ SubscriptionOAuthProviderError,
18
+ completeOAuth,
19
+ currentUsage,
20
+ startOAuth,
21
+ type SubscriptionCredential,
22
+ } from "../self_host/subscriptions/index.js";
23
+ import { linkCompleteThrough } from "./in_flight.js";
24
+ import { LINK_KEY_PROVIDERS } from "./key_providers.js";
25
+ import { linkPlatform } from "./service.js";
26
+ import type { LinkApiKey } from "./sqlite_store.js";
27
+
28
+ // A user of the approval page connects their own plans there, which serve
29
+ // only the grants they approve; a gateway key manages every grant, and apps
30
+ // register with one or openly.
31
+ export function selfHostedLink(
32
+ deps: Pick<SelfHostedResolverDeps, "gatewayKeys" | "subscriptions" | "links" | "env" | "config" | "fetch">,
33
+ ): LinkPlatform {
34
+ // A provider the operator points at its own endpoint takes users' keys only
35
+ // when that endpoint takes a key too: one without (a proxy that adds its own
36
+ // credential) would serve anyone's "key" on the operator's account.
37
+ const keyProviders = LINK_KEY_PROVIDERS.filter((provider) => {
38
+ const endpoint = deps.config.providers[provider.id];
39
+ return endpoint === undefined || endpoint.apiKeyEnv !== undefined;
40
+ });
41
+ const requireGatewayKey = (apiKey: string) => {
42
+ if (gatewayKeyIndex(deps.gatewayKeys, apiKey) === null) {
43
+ throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
44
+ }
45
+ };
46
+ // The cookie that remembers an approval page's user is signed with
47
+ // DARI_LINK_SESSION_SECRET; without it a process signs with a secret of its
48
+ // own, and a restart forgets who connected which plans.
49
+ const sessionSecret = deps.env.DARI_LINK_SESSION_SECRET?.trim() || randomBytes(32).toString("base64url");
50
+ // Other people's subscriptions and keys are taken only by a gateway that
51
+ // encrypts what it stores.
52
+ const requireEncryption = () => {
53
+ if (!deps.subscriptions.encrypted) {
54
+ throw new HttpError(
55
+ 503,
56
+ "This gateway cannot keep subscriptions safely yet. Its operator must set DARI_GATEWAY_ENCRYPTION_KEY.",
57
+ "link_not_configured",
58
+ );
59
+ }
60
+ };
61
+ const newSubject = () => `lu_${randomUUID().replaceAll("-", "")}`;
62
+ return linkPlatform(deps.links, {
63
+ httpRedirectHosts: deps.config.link?.allowHttpRedirectHosts ?? [],
64
+ sessionSecret: () => sessionSecret,
65
+ connectable: SUBSCRIPTION_PROVIDERS,
66
+ keyProviders,
67
+ async registerApp(app, apiKey) {
68
+ if (apiKey !== undefined) requireGatewayKey(apiKey);
69
+ deps.links.addApp(app);
70
+ },
71
+ async manager(apiKey) {
72
+ requireGatewayKey(apiKey);
73
+ return null;
74
+ },
75
+ completeThrough: (grantId) => linkCompleteThrough(grantId).toISOString(),
76
+ async plans(subject) {
77
+ return [...deps.subscriptions.owned(subject).map(linkSubscription), ...deps.links.keys(subject).map(linkKey)];
78
+ },
79
+ async plansWithIds(ids) {
80
+ const wanted = new Set(ids);
81
+ return [
82
+ ...deps.subscriptions.withIds(wanted).map(linkSubscription),
83
+ ...deps.links.keysWithIds(wanted).map(linkKey),
84
+ ];
85
+ },
86
+ async addKey(subject, provider, apiKey) {
87
+ requireEncryption();
88
+ const name = keyProviders.find((candidate) => candidate.id === provider)!.name;
89
+ const check = await checkProviderKey({
90
+ provider,
91
+ key: apiKey,
92
+ ...(deps.config.providers[provider] ? { endpoint: deps.config.providers[provider] } : {}),
93
+ fetch: deps.fetch as typeof fetch,
94
+ });
95
+ if (check.result === "rejected") {
96
+ throw new HttpError(400, `${name} did not accept that key. Check it and try again.`, "invalid_request");
97
+ }
98
+ const owner = subject ?? newSubject();
99
+ return { subject: owner, credentialId: deps.links.addKey(owner, provider, apiKey).id };
100
+ },
101
+ async startConnect(kind) {
102
+ requireEncryption();
103
+ let authorization;
104
+ try {
105
+ authorization = await startOAuth(kind, { fetch: deps.fetch });
106
+ } catch (error) {
107
+ if (error instanceof SubscriptionOAuthProviderError) {
108
+ throw new HttpError(502, "The provider did not start a sign-in.", "provider_error");
109
+ }
110
+ throw error;
111
+ }
112
+ // A Link sign-in's owner is set; one with none is the gateway owner's.
113
+ // A user without one yet becomes this subject when it completes.
114
+ const session = deps.subscriptions.createSession({
115
+ provider: kind,
116
+ flow: authorization.flow,
117
+ credentialName: null,
118
+ owner: newSubject(),
119
+ expiresAt: authorization.expiresAt,
120
+ });
121
+ return { session: session.token, authorizationUrl: authorization.authorizationUrl, userCode: authorization.userCode };
122
+ },
123
+ async completeConnect(subject, token, authorizationResponse) {
124
+ const session = deps.subscriptions.getSession(token);
125
+ if (session === null || session.owner === null || session.expiresAt <= new Date()) {
126
+ throw new HttpError(400, "That sign-in ended. Start again.", "invalid_request");
127
+ }
128
+ let tokens;
129
+ try {
130
+ tokens = await completeOAuth(session.provider, session.flow, authorizationResponse, { fetch: deps.fetch });
131
+ } catch (error) {
132
+ if (error instanceof SubscriptionOAuthInputError) {
133
+ if ([CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING].includes(error.message)) return null;
134
+ throw new HttpError(400, error.message, "invalid_request");
135
+ }
136
+ if (error instanceof SubscriptionOAuthProviderError) {
137
+ throw new HttpError(400, "The provider did not accept that sign-in. Try again.", "invalid_request");
138
+ }
139
+ throw error;
140
+ }
141
+ const owner = subject ?? session.owner;
142
+ const credentialId = deps.subscriptions.connect(tokens, null, new Date(), owner)!.id;
143
+ deps.subscriptions.deleteSession(token);
144
+ return { subject: owner, credentialId };
145
+ },
146
+ async removePlan(subject, credentialId) {
147
+ const plan = deps.subscriptions.owned(subject).find((credential) => credential.id === credentialId);
148
+ return plan !== undefined
149
+ ? deps.subscriptions.disconnect(plan.name, subject) !== null
150
+ : deps.links.removeKey(subject, credentialId);
151
+ },
152
+ });
153
+ }
154
+
155
+ // An API key as the approval page and the app see it: never the key itself.
156
+ function linkKey(key: LinkApiKey): LinkSubscription {
157
+ return {
158
+ id: key.id,
159
+ provider: "api_key",
160
+ apiKeyProvider: key.provider,
161
+ name: LINK_KEY_PROVIDERS.find((provider) => provider.id === key.provider)?.name ?? key.provider,
162
+ label: `Key ending ${key.apiKey.slice(-4)}`,
163
+ accountEmail: null,
164
+ unavailableUntil: null,
165
+ usage: [],
166
+ };
167
+ }
168
+
169
+ function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
170
+ const now = new Date();
171
+ return {
172
+ id: credential.id,
173
+ provider: credential.provider,
174
+ name: credential.name,
175
+ label: credential.label,
176
+ accountEmail: credential.accountEmail,
177
+ unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
178
+ ? credential.unavailableUntil.toISOString()
179
+ : null,
180
+ usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
181
+ minutes: window.minutes,
182
+ utilization: window.utilization,
183
+ resetsAt: window.resetsAt.toISOString(),
184
+ })),
185
+ };
186
+ }