@mupt-ai/dari-gateway 1.0.321 → 1.0.322

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.
@@ -134,13 +134,15 @@ export type LinkRepo = {
134
134
  /**
135
135
  * Store tokens for a grant, all or none. With `rotate`, also mark that
136
136
  * refresh token rotated: `race` when another request already did. `revoked`
137
- * when the grant is no longer live.
137
+ * when the grant is no longer live. The grant's tokens that expired, or were
138
+ * rotated (except refresh tokens), before `forgetBefore` go.
138
139
  */
139
140
  issueTokens(request: {
140
141
  grantId: string;
141
142
  tokens: LinkTokenIssue[];
142
143
  rotate?: string;
143
144
  now: number;
145
+ forgetBefore: number;
144
146
  }): MaybePromise<"ok" | "race" | "revoked">;
145
147
  /** Delete one token. */
146
148
  deleteToken(tokenHash: string): MaybePromise<void>;
@@ -182,6 +184,9 @@ export function linkGrants(repo: LinkRepo) {
182
184
  tokens: kinds.map((entry, index) => ({ ...entry, tokenHash: linkHash(tokens[index]!) })),
183
185
  ...(rotate === undefined ? {} : { rotate }),
184
186
  now: now.getTime(),
187
+ // Rotated refresh tokens stay while the grant lives (revoking it deletes
188
+ // them): presenting one again is how a stolen refresh token is caught.
189
+ forgetBefore: now.getTime() - LINK_TOKEN_RETENTION_MS,
185
190
  });
186
191
  if (result === "race") {
187
192
  throw new HttpError(
@@ -23,3 +23,8 @@ export const LINK_KEY_PROVIDERS: readonly LinkKeyProvider[] = [
23
23
  .map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
24
24
  ...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway)!.label })),
25
25
  ];
26
+
27
+ /** What a provider is called where a user's key for it is shown: "OpenRouter". */
28
+ export function linkKeyProviderName(provider: string): string {
29
+ return LINK_KEY_PROVIDERS.find((candidate) => candidate.id === provider)?.name ?? provider;
30
+ }
@@ -21,7 +21,7 @@ import {
21
21
  type SubscriptionCredential,
22
22
  } from "../self_host/subscriptions/index.js";
23
23
  import { linkCompleteThrough } from "./in_flight.js";
24
- import { LINK_KEY_PROVIDERS } from "./key_providers.js";
24
+ import { LINK_KEY_PROVIDERS, linkKeyProviderName } from "./key_providers.js";
25
25
  import { linkPlatform } from "./service.js";
26
26
  import type { LinkApiKey } from "./sqlite_store.js";
27
27
 
@@ -160,7 +160,7 @@ function linkKey(key: LinkApiKey): LinkSubscription {
160
160
  id: key.id,
161
161
  provider: "api_key",
162
162
  apiKeyProvider: key.provider,
163
- name: LINK_KEY_PROVIDERS.find((provider) => provider.id === key.provider)?.name ?? key.provider,
163
+ name: linkKeyProviderName(key.provider),
164
164
  label: `Key ending ${key.apiKey.slice(-4)}`,
165
165
  accountEmail: null,
166
166
  unavailableUntil: null,
@@ -9,13 +9,13 @@ import { randomUUID } from "node:crypto";
9
9
 
10
10
  import { HttpError } from "../http/errors.js";
11
11
  import type {
12
- LinkApp,
13
12
  LinkBudget,
14
13
  LinkBudgetStanding,
15
14
  LinkConnect,
16
15
  LinkKeyProvider,
17
16
  LinkPlanAdded,
18
17
  LinkPlatform,
18
+ LinkSignIn,
19
19
  LinkSubscription,
20
20
  } from "../platform/platform.js";
21
21
  import type { SubscriptionKind } from "../types.js";
@@ -80,6 +80,8 @@ export type LinkStore = LinkRepo & {
80
80
  export type LinkUsers = {
81
81
  /** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
82
82
  sessionSecret(): string;
83
+ /** See `LinkApprovalPage.signIn`. */
84
+ signIn?: LinkSignIn;
83
85
  connectable: readonly SubscriptionKind[];
84
86
  keyProviders: readonly LinkKeyProvider[];
85
87
  /** See `LinkPlatform.httpRedirectHosts`. */
@@ -135,6 +137,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
135
137
  httpRedirectHosts: users.httpRedirectHosts ?? [],
136
138
  approval: {
137
139
  sessionSecret: () => users.sessionSecret(),
140
+ ...(users.signIn === undefined ? {} : { signIn: users.signIn }),
138
141
  connectable: users.connectable,
139
142
  keyProviders: users.keyProviders,
140
143
  subscriptions: (subject) => users.plans(subject),
@@ -213,14 +216,9 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
213
216
  if (apiKey === undefined && !users.openRegistration) {
214
217
  throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
215
218
  }
216
- const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
217
- const app: LinkApp = {
218
- clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
219
- name,
220
- redirectUris,
221
- confidential: clientSecret !== undefined,
222
- };
223
- await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
219
+ const { record, clientSecret } = newLinkApp({ name, redirectUris, confidential: confidential === true });
220
+ await users.registerApp(record, apiKey);
221
+ const { clientSecretHash: _, ...app } = record;
224
222
  return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
225
223
  },
226
224
  async app(clientId) {
@@ -268,6 +266,32 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
268
266
  };
269
267
  }
270
268
 
269
+ /**
270
+ * A new app: its client id, and for a confidential one a client secret,
271
+ * returned this once, of which only the hash is kept. Every app is made here,
272
+ * whichever way it registers (hosted Dari's console included).
273
+ */
274
+ export function newLinkApp(request: { name: string; redirectUris: string[]; confidential: boolean }): {
275
+ record: LinkAppRecord;
276
+ clientSecret?: string;
277
+ } {
278
+ const secret = request.confidential ? newLinkClientSecret() : null;
279
+ const record: LinkAppRecord = {
280
+ clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
281
+ name: request.name,
282
+ redirectUris: request.redirectUris,
283
+ confidential: secret !== null,
284
+ clientSecretHash: secret?.hash ?? null,
285
+ };
286
+ return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
287
+ }
288
+
289
+ /** A confidential app's client secret, and the hash that is kept of it. */
290
+ export function newLinkClientSecret(): { secret: string; hash: string } {
291
+ const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
292
+ return { secret, hash: linkHash(secret) };
293
+ }
294
+
271
295
  /**
272
296
  * The grant a link token serves a request for: null when the key is no link
273
297
  * token. Throws the 401 a dead token gets, and the 424 a grant at its budget
@@ -9,9 +9,8 @@ import { randomUUID } from "node:crypto";
9
9
 
10
10
  import { type SecretBox, openWithoutKey } from "../self_host/secret_box.js";
11
11
  import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
12
- import type { BudgetUse } from "./budget.js";
12
+ import type { BudgetUse, LinkTokenCounts } from "./budget.js";
13
13
  import {
14
- LINK_TOKEN_RETENTION_MS,
15
14
  type LinkAppRecord,
16
15
  type LinkPin,
17
16
  type LinkRevoker,
@@ -211,12 +210,12 @@ export class SqliteLinkStore implements LinkStore {
211
210
 
212
211
  budgetUses(grantId: string, since: number): BudgetUse[] {
213
212
  return this.db
214
- .query<{ received_at: number; tokens: number }, [string, number]>(
215
- `SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
213
+ .query<UsageTokenRow & { received_at: number }, [string, number]>(
214
+ `SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
216
215
  FROM link_usage WHERE grant_id = ? AND received_at > ?`,
217
216
  )
218
217
  .all(grantId, since)
219
- .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
218
+ .map((row) => ({ at: new Date(row.received_at), ...tokenCounts(row) }));
220
219
  }
221
220
 
222
221
  /** Record what one of a grant's requests used; a repeated request id is ignored. */
@@ -256,10 +255,7 @@ export class SqliteLinkStore implements LinkStore {
256
255
  model: row.model,
257
256
  thinking: row.thinking,
258
257
  tags: JSON.parse(row.tags) as Record<string, string>,
259
- inputTokens: row.input_tokens,
260
- outputTokens: row.output_tokens,
261
- cacheReadTokens: row.cache_read_tokens,
262
- cacheWriteTokens: row.cache_write_tokens,
258
+ ...tokenCounts(row),
263
259
  }));
264
260
  }
265
261
 
@@ -392,7 +388,7 @@ export class SqliteLinkStore implements LinkStore {
392
388
  };
393
389
  }
394
390
 
395
- issueTokens(request: { grantId: string; tokens: LinkTokenIssue[]; rotate?: string; now: number }): "ok" | "race" | "revoked" {
391
+ issueTokens(request: { grantId: string; tokens: LinkTokenIssue[]; rotate?: string; now: number; forgetBefore: number }): "ok" | "race" | "revoked" {
396
392
  return this.db.transaction((): "ok" | "race" | "revoked" => {
397
393
  const live = this.db
398
394
  .query<{ id: string }, [string]>("SELECT id FROM link_grants WHERE id = ? AND revoked_at IS NULL")
@@ -405,10 +401,10 @@ export class SqliteLinkStore implements LinkStore {
405
401
  ).changes;
406
402
  if (rotated === 0) return "race";
407
403
  }
408
- const stale = request.now - LINK_TOKEN_RETENTION_MS;
409
- // Rotated refresh tokens stay while the grant lives (revoking it deletes
410
- // them): presenting one again is how a stolen refresh token is caught.
411
- this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
404
+ this.db.run(
405
+ "DELETE FROM link_tokens WHERE grant_id = ? AND (expires_at < ? OR (rotated_at < ? AND kind != 'refresh'))",
406
+ [request.grantId, request.forgetBefore, request.forgetBefore],
407
+ );
412
408
  this.insertTokens(request.grantId, request.tokens, request.now);
413
409
  return "ok";
414
410
  })();
@@ -470,17 +466,29 @@ export type LinkUsageEntry = {
470
466
  status: string;
471
467
  };
472
468
 
473
- type UsageRow = {
474
- status: string | null;
475
- model: string | null;
476
- thinking: string | null;
477
- tags: string;
469
+ type UsageTokenRow = {
478
470
  input_tokens: number;
479
471
  output_tokens: number;
480
472
  cache_read_tokens: number;
481
473
  cache_write_tokens: number;
482
474
  };
483
475
 
476
+ type UsageRow = UsageTokenRow & {
477
+ status: string | null;
478
+ model: string | null;
479
+ thinking: string | null;
480
+ tags: string;
481
+ };
482
+
483
+ function tokenCounts(row: UsageTokenRow): LinkTokenCounts {
484
+ return {
485
+ inputTokens: row.input_tokens,
486
+ outputTokens: row.output_tokens,
487
+ cacheReadTokens: row.cache_read_tokens,
488
+ cacheWriteTokens: row.cache_write_tokens,
489
+ };
490
+ }
491
+
484
492
  // A child token's models. One minted before `pins` existed kept its one model
485
493
  // in `model` and `thinking`.
486
494
  function childPins(row: TokenRow): LinkPin[] | null {
@@ -176,10 +176,11 @@ export type LinkPlatform = {
176
176
  };
177
177
 
178
178
  /**
179
- * What the gateway's approval and connections pages need. The pages need no
180
- * account: a user connects a plan by signing in to its provider, and the
181
- * gateway remembers them in a signed cookie as a subject, so their plans are
182
- * there the next time an app asks and they manage their connections there.
179
+ * What the gateway's approval and connections pages need. The gateway
180
+ * remembers the user in a signed cookie as a subject, so their plans are there
181
+ * the next time an app asks and they manage their connections there. With
182
+ * `signIn` the subject is the account they signed in with; without it the
183
+ * pages need no account, and a user's first plan makes their subject.
183
184
  */
184
185
  export type LinkApprovalPage = {
185
186
  /**
@@ -187,6 +188,11 @@ export type LinkApprovalPage = {
187
188
  * `link_not_configured`) when the platform has none.
188
189
  */
189
190
  sessionSecret(): string;
191
+ /**
192
+ * Set on a platform whose users have accounts: the page then acts only for
193
+ * a user who signed in with one, so their plans follow them to any browser.
194
+ */
195
+ signIn?: LinkSignIn;
190
196
  /** The kinds of plan a user can connect on the page, in the order offered. */
191
197
  connectable: readonly SubscriptionKind[];
192
198
  /** The providers and gateways a user can add an API key for, in the order offered. */
@@ -230,6 +236,18 @@ export type LinkApprovalPage = {
230
236
  setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
231
237
  };
232
238
 
239
+ /**
240
+ * The platform's own sign-in. The page sends the user to `url()` with `state`
241
+ * and `next`; the platform signs them in and returns them to
242
+ * `/v1/link/session` with the same `next` and a ticket for that state.
243
+ */
244
+ export type LinkSignIn = {
245
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
246
+ url(): string;
247
+ /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
248
+ redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
249
+ };
250
+
233
251
  /** A plan or API key the user added, and who they are now. */
234
252
  export type LinkPlanAdded = { subject: string; credentialId: string };
235
253
 
@@ -10,15 +10,10 @@ import {
10
10
  import { HttpError } from "../http/errors.js";
11
11
  import type { ResolveRouterRequest } from "../platform/platform.js";
12
12
  import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
13
- import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
13
+ import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
14
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
15
15
  import { gatewayFor } from "../models/gateways.js";
16
- import {
17
- linkGrantUnavailableError,
18
- modelNotServed,
19
- plansExhausted,
20
- plansForAnotherClient,
21
- } from "../link/errors.js";
16
+ import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
22
17
  import { registeredModelPrice } from "../providers/pi.js";
23
18
  import type { LinkUnavailable, ProviderCredential as SuppliedProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
24
19
  import {
@@ -152,9 +147,15 @@ export async function resolveSelfHostedRouter(
152
147
  // A model-specific hold tries the pool's other plans before removing the
153
148
  // model. Its provider's active plan and conversation pin stay unchanged.
154
149
  const modelCredentials: Record<string, SuppliedProviderCredential> = {};
150
+ // A provider the request wanted that no granted plan served.
155
151
  const linkUnavailable = grant === null
156
152
  ? {}
157
- : grantUnavailable(granted, credentials, request.clientHarness, now);
153
+ : providersUnavailable(
154
+ granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })),
155
+ [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider),
156
+ request.clientHarness,
157
+ now,
158
+ );
158
159
  const models = [];
159
160
  for (const model of listed) {
160
161
  const credential = credentials.get(providerForModel(model.id));
@@ -185,11 +186,7 @@ export async function resolveSelfHostedRouter(
185
186
  // A grant with a gateway key serves the gateway's models by name, listed or not.
186
187
  const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
187
188
  if (models.length === 0 && !gatewayKeyed) {
188
- if (grant !== null) {
189
- throw grant.pins?.length === 1
190
- ? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0]!.model)
191
- : linkGrantUnavailableError(linkUnavailable);
192
- }
189
+ if (grant !== null) throw linkNothingServed(linkUnavailable, grant.pins);
193
190
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
194
191
  throw unavailableRouterError(request.routerId, exhausted, missing);
195
192
  }
@@ -312,40 +309,6 @@ function grantModels(
312
309
  return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
313
310
  }
314
311
 
315
- /**
316
- * Why each provider with a granted plan serves nothing now: its plans serve
317
- * only another client, or are all at their usage limits.
318
- */
319
- function grantUnavailable(
320
- granted: readonly SubscriptionCredential[],
321
- credentials: ReadonlyMap<string, ProviderCredential | null>,
322
- clientHarness: ResolveRouterRequest["clientHarness"],
323
- now: Date,
324
- ): Record<string, LinkUnavailable> {
325
- const unavailable: Record<string, LinkUnavailable> = {};
326
- for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
327
- // Only a provider the request wanted and no plan served.
328
- if (credentials.get(provider) !== null) continue;
329
- const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
330
- const usable = plans.filter((credential) => {
331
- const client = subscriptionClient(credential.provider);
332
- return client === undefined || client === clientHarness;
333
- });
334
- if (usable.length === 0) {
335
- unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
336
- continue;
337
- }
338
- const held = usable.flatMap((credential) =>
339
- credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []
340
- );
341
- unavailable[provider] = plansExhausted(
342
- usable.map((credential) => credential.provider),
343
- held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null,
344
- );
345
- }
346
- return unavailable;
347
- }
348
-
349
312
  // Configured endpoints read their own key variable, or send a placeholder
350
313
  // when they take none; known providers use their standard variable.
351
314
  export async function configuredProviderApiKey(