@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
@@ -95,31 +95,26 @@ export type GatewayPlatform = {
95
95
  };
96
96
 
97
97
  /**
98
- * Dari Link storage and authorization. The gateway serves the OAuth protocol
99
- * (authorization code with PKCE S256) and validates its parameters; the
100
- * platform authenticates users and clients, stores apps and grants, and
101
- * issues tokens.
98
+ * Dari Link as the gateway's endpoints use it. A platform builds it with
99
+ * `linkPlatform` (link/service.ts) from its storage and its users, so the
100
+ * rules are the same everywhere.
102
101
  *
103
102
  * Methods throw HttpError(401) for a key that cannot act, HttpError(401,
104
103
  * `invalid_client`) for a confidential client without its secret, and
105
104
  * HttpError(400) with code `invalid_grant`, `refresh_race`, `invalid_client`,
106
105
  * or `invalid_request` for a request the protocol refuses.
107
106
  *
108
- * A link token is a gateway key for `resolveRouter`: the platform serves it
109
- * the default router on only the grant's subscriptions, never an API key or
110
- * credits, and sets `link_grant_id` and `link_models`. It fails the request
111
- * with 424 `subscription_exhausted` (and `resets_at`),
112
- * `subscription_client_mismatch`, or `model_not_granted` when no granted plan
113
- * can serve, and with 401 `link_token_expired` or `grant_revoked` (and
114
- * `revoked_by`) for a dead token. A revoked grant's tokens stop at once.
107
+ * A link token is a gateway key for `resolveRouter`: the platform checks it
108
+ * with `linkTokenGrant` (live, within its budget) and serves it the default
109
+ * router on only the grant's subscriptions, never an API key or credits, and
110
+ * sets `link_grant_id` and `link_models`. It fails the request with 424
111
+ * `subscription_exhausted` (and `resets_at`), `subscription_client_mismatch`,
112
+ * or `model_not_granted` when no granted plan can serve. A revoked grant's
113
+ * tokens stop at once.
115
114
  */
116
115
  export type LinkPlatform = {
117
- /**
118
- * How a user approves a grant. A platform with its own signed-in web app
119
- * names its consent page, and the gateway sends the authorization request
120
- * there; otherwise the gateway serves the approval page itself.
121
- */
122
- approval: LinkConsentPage | LinkApprovalPage;
116
+ /** What the gateway's approval and connections pages need. */
117
+ approval: LinkApprovalPage;
123
118
  /**
124
119
  * Hosts, besides loopback, an app may register an http (not https) redirect
125
120
  * URI on: exact names, or `*.suffix` for any subdomain. For private dev hosts
@@ -181,27 +176,15 @@ export type LinkPlatform = {
181
176
  };
182
177
 
183
178
  /**
184
- * A consent page the platform serves to its signed-in users. The gateway
185
- * validates the authorization request and redirects to `consentUrl` with the
186
- * request's query; the page creates the grant and returns the code to the app.
187
- */
188
- export type LinkConsentPage = {
189
- consentUrl: string;
190
- // Where signed-in users see and manage the apps they connected; a grant's
191
- // own entry adds `grant=<id>` to its query.
192
- connectedAppsUrl: string;
193
- };
194
-
195
- /**
196
- * What the gateway's own approval page needs from the platform. The page
197
- * needs no account: a user connects a plan by signing in to its provider, and
198
- * the gateway remembers them in a signed cookie as an opaque subject, so their
199
- * plans are there the next time an app asks.
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.
200
183
  */
201
184
  export type LinkApprovalPage = {
202
185
  /**
203
- * The secret that signs the approval page's cookies. Throws
204
- * HttpError(503, `link_not_configured`) when the platform has none.
186
+ * The secret that signs the pages' cookies. Throws HttpError(503,
187
+ * `link_not_configured`) when the platform has none.
205
188
  */
206
189
  sessionSecret(): string;
207
190
  /** The kinds of plan a user can connect on the page, in the order offered. */
@@ -210,20 +193,22 @@ export type LinkApprovalPage = {
210
193
  keyProviders: readonly LinkKeyProvider[];
211
194
  /**
212
195
  * Add the user's API key for one of `keyProviders`, replacing their earlier
213
- * key for it. Throws HttpError(400) for a key the provider refuses.
196
+ * key for it; without a subject, the key makes a new user. Throws
197
+ * HttpError(400) for a key the provider refuses.
214
198
  */
215
- addKey(subject: string, provider: string, apiKey: string): Promise<{ credentialId: string }>;
199
+ addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
216
200
  /** The plans this user connected and the API keys they added, which an approval chooses among. */
217
201
  subscriptions(subject: string): Promise<LinkSubscription[]>;
218
202
  /** Start the provider's sign-in for a plan of this kind. */
219
- startConnect(subject: string, kind: SubscriptionKind): Promise<LinkConnect>;
203
+ startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
220
204
  /**
221
205
  * Finish a sign-in `startConnect` began: with the code the provider showed
222
206
  * the user, or for a provider that shows the user a code to enter, with
223
- * nothing. Null while the provider still waits on the user. Throws
224
- * HttpError(400) for a code the provider refuses or a sign-in that ended.
207
+ * nothing. Without a subject, the plan makes a new user. Null while the
208
+ * provider still waits on the user. Throws HttpError(400) for a code the
209
+ * provider refuses or a sign-in that ended.
225
210
  */
226
- completeConnect(subject: string, session: string, authorizationResponse: string): Promise<{ credentialId: string } | null>;
211
+ completeConnect(subject: string | null, session: string, authorizationResponse: string): Promise<LinkPlanAdded | null>;
227
212
  /**
228
213
  * Forget one of the user's plans or API keys: its stored tokens or key are
229
214
  * deleted, every app loses it, and a grant left with nothing is revoked.
@@ -237,8 +222,20 @@ export type LinkApprovalPage = {
237
222
  grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget"> | null>;
238
223
  /** Create a grant on the chosen subscriptions and return its one-time code. */
239
224
  approve(request: LinkApproval): Promise<{ code: string }>;
225
+ /** The user's live grants, oldest first, as the connections page shows them. */
226
+ connections(subject: string): Promise<LinkConnection[]>;
227
+ /** The user ends one of their grants; false when they have none by that id. */
228
+ disconnect(subject: string, grantId: string): Promise<boolean>;
229
+ /** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
230
+ setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
240
231
  };
241
232
 
233
+ /** A plan or API key the user added, and who they are now. */
234
+ export type LinkPlanAdded = { subject: string; credentialId: string };
235
+
236
+ /** One of a user's grants on the connections page. */
237
+ export type LinkConnection = LinkGrantDetail & { usage: LinkUsageTotals };
238
+
242
239
  /** A model provider or gateway whose API key a user can add on the approval page. */
243
240
  export type LinkKeyProvider = { id: string; name: string };
244
241
 
@@ -255,7 +252,7 @@ export type LinkConnect = {
255
252
 
256
253
  /**
257
254
  * The most tokens a grant's app may use in a rolling window, across all of
258
- * the grant's plans and API keys. See runtime/link_budget.ts for how tokens
255
+ * the grant's plans and API keys. See link/budget.ts for how tokens
259
256
  * are counted.
260
257
  */
261
258
  export type LinkBudget = { windowMinutes: number; maxTokens: number };
@@ -401,9 +398,6 @@ export type LinkUsage = LinkUsageTotals & {
401
398
  export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget"> & {
402
399
  budget: LinkBudgetStanding[];
403
400
  subscriptions: LinkSubscription[];
404
- // The account that approved the grant; null where accounts have no
405
- // identity, as on a self-hosted gateway.
406
- user: { email: string | null; name: string | null } | null;
407
401
  };
408
402
 
409
403
  export type ResolveRouterRequest = {
@@ -1,7 +1,7 @@
1
1
  import type { RoutingCandidate, RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
2
2
 
3
3
  import { HttpError } from "../http/errors.js";
4
- import { modelNotServed } from "../models/link_errors.js";
4
+ import { modelNotServed } from "../link/errors.js";
5
5
  import { explicitModelId } from "../protocol/input/router_model.js";
6
6
  import type { RoutedDecision } from "../strategies/route_decision.js";
7
7
  import type { PreparedRoutedCompletion } from "./prepare_routed_completion.js";
@@ -19,7 +19,7 @@ import { RequestReporter, type ReportedCandidatePruning } from "../telemetry/rep
19
19
  import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
20
20
  import type { ClientHarness, ProviderCredential, ResolvedRouter, RouterRole } from "../types.js";
21
21
  import { requestTags } from "./request_tags.js";
22
- import { linkGrantAccess } from "./link_grant_access.js";
22
+ import { linkGrantAccess } from "../link/grant_access.js";
23
23
  import { rolePrompt, withRoleModel } from "./role_model.js";
24
24
  import { strictProviderAccess } from "./strict_provider_access.js";
25
25
  import type { RoutedRuntimeReporter } from "./runtime_reporter.js";
@@ -16,7 +16,7 @@ import { checkProviderKey } from "../providers/key_check.js";
16
16
  import { CANONICAL_MODELS } from "../models/canonical.js";
17
17
  import { allRouterModels, loadGatewayConfig, type GatewayConfig, type RouterConfig } from "./config.js";
18
18
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
19
- import { LinkStore } from "./link_store.js";
19
+ import { SqliteLinkStore } from "../link/sqlite_store.js";
20
20
  import { secretBoxFromEnv } from "./secret_box.js";
21
21
  import { PrefixStore } from "./prefix_store.js";
22
22
  import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
@@ -72,7 +72,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
72
72
  const prefixes = new PrefixStore(db);
73
73
  const sessionPins = new SessionPinStore(db);
74
74
  const routerModels = new RouterModelStore(db);
75
- const links = new LinkStore(db, secrets);
75
+ const links = new SqliteLinkStore(db, secrets);
76
76
  // Pi's provider auth reads each provider's standard key variable, such as
77
77
  // OPENAI_API_KEY, from this environment only.
78
78
  const piModels = builtinModels({
@@ -1,34 +1,11 @@
1
- import { randomBytes } from "node:crypto";
2
-
3
- import { errorCode, HttpError } from "../http/errors.js";
4
- import { linkGrantRevoked, linkTokenExpired } from "../models/link_errors.js";
1
+ import { errorCode } from "../http/errors.js";
2
+ import { selfHostedLink } from "../link/self_hosted.js";
3
+ import type { GatewayPlatform } from "../platform/platform.js";
5
4
  import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
6
- import { getBuiltinProviders } from "@mupt-ai/pi-ai/providers/all";
7
- import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
8
-
9
- import { CANONICAL_MODELS } from "../models/canonical.js";
10
- import { LINK_KEY_GATEWAYS, gatewayFor } from "../models/gateways.js";
11
- import type { GatewayPlatform, LinkKeyProvider, LinkPlatform, LinkSubscription } from "../platform/platform.js";
12
- import { checkProviderKey } from "../providers/key_check.js";
13
- import { linkCompleteThrough } from "../runtime/link_in_flight.js";
14
- import type { LinkApiKey } from "./link_store.js";
15
5
  import type { PrefixStore } from "./prefix_store.js";
16
6
  import type { SessionPinStore } from "./session_pin_store.js";
17
- import { gatewayKeyIndex, resolveSelfHostedRouter, type SelfHostedResolverDeps } from "./resolve.js";
18
- import {
19
- CODEX_APPROVAL_PENDING,
20
- META_APPROVAL_PENDING,
21
- OPENCODE_APPROVAL_PENDING,
22
- SUBSCRIPTION_PROVIDERS,
23
- SubscriptionOAuthInputError,
24
- SubscriptionOAuthProviderError,
25
- completeOAuth,
26
- currentUsage,
27
- freshAccessToken,
28
- startOAuth,
29
- type SubscriptionCredential,
30
- type SubscriptionStore,
31
- } from "./subscriptions/index.js";
7
+ import { resolveSelfHostedRouter, type SelfHostedResolverDeps } from "./resolve.js";
8
+ import { freshAccessToken, type SubscriptionStore } from "./subscriptions/index.js";
32
9
 
33
10
  /**
34
11
  * The self-hosted platform: routers from the config file, subscriptions,
@@ -138,242 +115,3 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
138
115
  link: selfHostedLink(deps),
139
116
  };
140
117
  }
141
-
142
- const PROVIDER_NAMES: Record<string, string> = {
143
- anthropic: "Anthropic",
144
- openai: "OpenAI",
145
- meta: "Meta",
146
- moonshotai: "Moonshot AI",
147
- xai: "xAI",
148
- };
149
-
150
- // Whose API key a user can add on the approval page: each provider with
151
- // catalog models this gateway can call with a key, then the gateways.
152
- const LINK_KEY_PROVIDERS: readonly LinkKeyProvider[] = [
153
- ...[...new Set(CANONICAL_MODELS.map((model) => providerForModel(model.id)))]
154
- .filter((provider) => (getBuiltinProviders() as readonly string[]).includes(provider))
155
- .map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
156
- ...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway)!.label })),
157
- ];
158
-
159
- // A user of the approval page connects their own plans there, which serve
160
- // only the grants they approve; a gateway key manages every grant, and apps
161
- // register with one or openly.
162
- function selfHostedLink(
163
- deps: Pick<SelfHostedResolverDeps, "gatewayKeys" | "subscriptions" | "links" | "env" | "config" | "fetch">,
164
- ): LinkPlatform {
165
- // A provider the operator points at its own endpoint takes users' keys only
166
- // when that endpoint takes a key too: one without (a proxy that adds its own
167
- // credential) would serve anyone's "key" on the operator's account.
168
- const keyProviders = LINK_KEY_PROVIDERS.filter((provider) => {
169
- const endpoint = deps.config.providers[provider.id];
170
- return endpoint === undefined || endpoint.apiKeyEnv !== undefined;
171
- });
172
- const requireGatewayKey = (apiKey: string) => {
173
- if (gatewayKeyIndex(deps.gatewayKeys, apiKey) === null) {
174
- throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
175
- }
176
- };
177
- // The cookie that remembers an approval page's user is signed with
178
- // DARI_LINK_SESSION_SECRET; without it a process signs with a secret of its
179
- // own, and a restart forgets who connected which plans.
180
- const sessionSecret = deps.env.DARI_LINK_SESSION_SECRET?.trim() || randomBytes(32).toString("base64url");
181
- const granted = (credentialIds: ReadonlySet<string>) => [
182
- ...deps.subscriptions.withIds(credentialIds).map(linkSubscription),
183
- ...deps.links.keysWithIds(credentialIds).map(linkKey),
184
- ];
185
- // The live grant a grant's own access token names; a child token cannot
186
- // read its grant or its usage.
187
- const parentGrantId = (accessToken: string): string => {
188
- const auth = deps.links.authenticate(accessToken);
189
- if (auth === null) throw new HttpError(401, "Missing or invalid Dari Link access token.", "authentication_error");
190
- if (auth.status === "expired") throw linkTokenExpired();
191
- if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
192
- if (auth.grant.pins !== undefined) {
193
- throw new HttpError(403, "A child token cannot read its grant or its usage.", "permission_denied");
194
- }
195
- return auth.grant.id;
196
- };
197
- // Other people's subscriptions and keys are taken only by a gateway that
198
- // encrypts what it stores.
199
- const requireEncryption = () => {
200
- if (!deps.subscriptions.encrypted) {
201
- throw new HttpError(
202
- 503,
203
- "This gateway cannot keep subscriptions safely yet. Its operator must set DARI_GATEWAY_ENCRYPTION_KEY.",
204
- "link_not_configured",
205
- );
206
- }
207
- };
208
- return {
209
- httpRedirectHosts: deps.config.link?.allowHttpRedirectHosts ?? [],
210
- approval: {
211
- sessionSecret: () => sessionSecret,
212
- connectable: SUBSCRIPTION_PROVIDERS,
213
- keyProviders,
214
- async subscriptions(subject) {
215
- return [...deps.subscriptions.owned(subject).map(linkSubscription), ...deps.links.keys(subject).map(linkKey)];
216
- },
217
- async addKey(subject, provider, apiKey) {
218
- requireEncryption();
219
- const known = keyProviders.find((candidate) => candidate.id === provider);
220
- if (known === undefined) throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
221
- const check = await checkProviderKey({
222
- provider,
223
- key: apiKey,
224
- ...(deps.config.providers[provider] ? { endpoint: deps.config.providers[provider] } : {}),
225
- fetch: deps.fetch as typeof fetch,
226
- });
227
- if (check.result === "rejected") {
228
- throw new HttpError(400, `${known.name} did not accept that key. Check it and try again.`, "invalid_request");
229
- }
230
- return { credentialId: deps.links.addKey(subject, provider, apiKey).id };
231
- },
232
- async startConnect(subject, kind) {
233
- requireEncryption();
234
- let authorization;
235
- try {
236
- authorization = await startOAuth(kind, { fetch: deps.fetch });
237
- } catch (error) {
238
- if (error instanceof SubscriptionOAuthProviderError) {
239
- throw new HttpError(502, "The provider did not start a sign-in.", "provider_error");
240
- }
241
- throw error;
242
- }
243
- const session = deps.subscriptions.createSession({
244
- provider: kind,
245
- flow: authorization.flow,
246
- credentialName: null,
247
- owner: subject,
248
- expiresAt: authorization.expiresAt,
249
- });
250
- return { session: session.token, authorizationUrl: authorization.authorizationUrl, userCode: authorization.userCode };
251
- },
252
- async completeConnect(subject, token, authorizationResponse) {
253
- const session = deps.subscriptions.getSession(token);
254
- if (session === null || session.owner !== subject || session.expiresAt <= new Date()) {
255
- throw new HttpError(400, "That sign-in ended. Start again.", "invalid_request");
256
- }
257
- let tokens;
258
- try {
259
- tokens = await completeOAuth(session.provider, session.flow, authorizationResponse, { fetch: deps.fetch });
260
- } catch (error) {
261
- if (error instanceof SubscriptionOAuthInputError) {
262
- if ([CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING].includes(error.message)) return null;
263
- throw new HttpError(400, error.message, "invalid_request");
264
- }
265
- if (error instanceof SubscriptionOAuthProviderError) {
266
- throw new HttpError(400, "The provider did not accept that sign-in. Try again.", "invalid_request");
267
- }
268
- throw error;
269
- }
270
- deps.subscriptions.deleteSession(token);
271
- return { credentialId: deps.subscriptions.connect(tokens, null, new Date(), subject)!.id };
272
- },
273
- async remove(subject, credentialId) {
274
- const plan = deps.subscriptions.owned(subject).find((credential) => credential.id === credentialId);
275
- const removed = plan !== undefined
276
- ? deps.subscriptions.disconnect(plan.name, subject) !== null
277
- : deps.links.removeKey(subject, credentialId);
278
- if (removed) deps.links.dropCredential(credentialId);
279
- return removed;
280
- },
281
- async grant(subject, grantId, clientId) {
282
- const grant = deps.links.grants().find((candidate) => candidate.id === grantId && candidate.clientId === clientId);
283
- if (grant === undefined || deps.links.subject(grantId) !== subject) return null;
284
- return { credentialIds: grant.credentialIds, budget: grant.budget };
285
- },
286
- async approve(request) {
287
- const connected = new Set([
288
- ...deps.subscriptions.owned(request.subject).map((credential) => credential.id),
289
- ...deps.links.keys(request.subject).map((key) => key.id),
290
- ]);
291
- if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => connected.has(id))) {
292
- throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
293
- }
294
- return { code: deps.links.approve(request) };
295
- },
296
- },
297
- async registerApp({ apiKey, name, redirectUris, confidential }) {
298
- if (apiKey !== undefined) requireGatewayKey(apiKey);
299
- return deps.links.registerApp(name, redirectUris, confidential === true);
300
- },
301
- async app(clientId) {
302
- return deps.links.app(clientId);
303
- },
304
- async exchangeCode(request) {
305
- return deps.links.exchangeCode(request);
306
- },
307
- async refresh(request) {
308
- return deps.links.refresh(request);
309
- },
310
- async exchangeToken(request) {
311
- return deps.links.exchangeToken(request);
312
- },
313
- async grant(accessToken) {
314
- const grantId = parentGrantId(accessToken);
315
- const grant = deps.links.grants().find((candidate) => candidate.id === grantId)!;
316
- const { credentialIds, budget: _, ...rest } = grant;
317
- const budget = deps.links.budgetStandings(grant.id).map((standing) => ({
318
- ...standing,
319
- resetsAt: standing.resetsAt?.toISOString() ?? null,
320
- }));
321
- // The approval page knows its users only as opaque subjects.
322
- return { ...rest, budget, subscriptions: granted(new Set(credentialIds)), user: null };
323
- },
324
- async usage({ accessToken, ...query }) {
325
- const grantId = parentGrantId(accessToken);
326
- // Read before the rows, so a request recorded in between is counted.
327
- const completeThrough = linkCompleteThrough(grantId).toISOString();
328
- return { ...deps.links.usage(grantId, query), completeThrough };
329
- },
330
- async revokeToken(request) {
331
- deps.links.revokeToken(request);
332
- },
333
- async grants(apiKey) {
334
- requireGatewayKey(apiKey);
335
- return deps.links.grants();
336
- },
337
- async setBudget({ apiKey, grantId, budget }) {
338
- requireGatewayKey(apiKey);
339
- return deps.links.setBudget(grantId, budget);
340
- },
341
- async revokeGrant({ apiKey, grantId }) {
342
- requireGatewayKey(apiKey);
343
- return deps.links.revoke(grantId, "user");
344
- },
345
- };
346
- }
347
-
348
- // An API key as the approval page and the app see it: never the key itself.
349
- function linkKey(key: LinkApiKey): LinkSubscription {
350
- return {
351
- id: key.id,
352
- provider: "api_key",
353
- apiKeyProvider: key.provider,
354
- name: LINK_KEY_PROVIDERS.find((provider) => provider.id === key.provider)?.name ?? key.provider,
355
- label: `Key ending ${key.apiKey.slice(-4)}`,
356
- accountEmail: null,
357
- unavailableUntil: null,
358
- usage: [],
359
- };
360
- }
361
-
362
- function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
363
- const now = new Date();
364
- return {
365
- id: credential.id,
366
- provider: credential.provider,
367
- name: credential.name,
368
- label: credential.label,
369
- accountEmail: credential.accountEmail,
370
- unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
371
- ? credential.unavailableUntil.toISOString()
372
- : null,
373
- usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
374
- minutes: window.minutes,
375
- utilization: window.utilization,
376
- resetsAt: window.resetsAt.toISOString(),
377
- })),
378
- };
379
- }
@@ -14,15 +14,11 @@ import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from
14
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
15
15
  import { gatewayFor } from "../models/gateways.js";
16
16
  import {
17
- budgetExhausted,
18
- linkGrantRevoked,
19
17
  linkGrantUnavailableError,
20
- linkTokenExpired,
21
- linkUnavailableError,
22
18
  modelNotServed,
23
19
  plansExhausted,
24
20
  plansForAnotherClient,
25
- } from "../models/link_errors.js";
21
+ } from "../link/errors.js";
26
22
  import { registeredModelPrice } from "../providers/pi.js";
27
23
  import type { LinkUnavailable, ProviderKeySource, ResolvedRouter } from "../types.js";
28
24
  import {
@@ -32,8 +28,9 @@ import {
32
28
  type RouterConfig,
33
29
  type RouterModelConfig,
34
30
  } from "./config.js";
35
- import type { ActiveLinkGrant, LinkStore } from "./link_store.js";
36
- import { overBudgetUntil } from "../runtime/link_budget.js";
31
+ import type { ActiveLinkGrant } from "../link/grants.js";
32
+ import type { SqliteLinkStore } from "../link/sqlite_store.js";
33
+ import { linkTokenGrant } from "../link/service.js";
37
34
  import type { RouterModelStore } from "./router_models.js";
38
35
  import {
39
36
  activeModelHolds,
@@ -55,7 +52,7 @@ export type SelfHostedResolverDeps = {
55
52
  routerModels: RouterModelStore;
56
53
  gatewayKeys: readonly string[];
57
54
  subscriptions: SubscriptionStore;
58
- links: LinkStore;
55
+ links: SqliteLinkStore;
59
56
  prefixHits: (args: {
60
57
  routerId: string;
61
58
  prefixHashes: readonly string[];
@@ -94,18 +91,13 @@ export async function resolveSelfHostedRouter(
94
91
  request: ResolveRouterRequest,
95
92
  ): Promise<ResolvedRouter> {
96
93
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
97
- const grant = keyIndex === null ? activeLinkGrant(deps.links, request.apiKey) : null;
94
+ const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
98
95
  if (keyIndex === null && grant === null) {
99
96
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
100
97
  }
101
98
  if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
102
99
  throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
103
100
  }
104
- if (grant !== null) {
105
- // A grant at its token budget serves nothing until its window rolls on.
106
- const back = overBudgetUntil(deps.links.budgetStandings(grant.id));
107
- if (back !== undefined) throw linkUnavailableError(budgetExhausted(back));
108
- }
109
101
  const configured = deps.config.routers[request.routerId];
110
102
  if (configured === undefined) {
111
103
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
@@ -270,13 +262,6 @@ export async function resolveSelfHostedRouter(
270
262
 
271
263
  // The grant a live link token belongs to, or null for a token that is not
272
264
  // one. A dead token is refused with the reason.
273
- function activeLinkGrant(links: LinkStore, token: string): ActiveLinkGrant | null {
274
- const auth = links.authenticate(token);
275
- if (auth === null) return null;
276
- if (auth.status === "expired") throw linkTokenExpired();
277
- if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
278
- return auth.grant;
279
- }
280
265
 
281
266
  /**
282
267
  * The models a grant's request may be served: a child token's one model, or
@@ -51,9 +51,9 @@ import { join } from "node:path";
51
51
  import { fileURLToPath } from "node:url";
52
52
  import { zstdDecompressSync } from "node:zlib";
53
53
 
54
- import { linkUserCookie } from "../ingress/link.js";
54
+ import { linkUserCookie } from "../link/endpoints.js";
55
55
  import type { SubscriptionKind } from "../types.js";
56
- import { LinkStore } from "./link_store.js";
56
+ import { SqliteLinkStore } from "../link/sqlite_store.js";
57
57
  import { secretBoxFromEnv } from "./secret_box.js";
58
58
  import { SubscriptionStore } from "./subscriptions/index.js";
59
59
 
@@ -246,7 +246,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
246
246
  }, null, new Date(), options.owner === "gateway" ? null : STUB_USER)!.id;
247
247
  });
248
248
  const keys = options.keys ?? [];
249
- const links = new LinkStore(new Database(dbPath), secrets);
249
+ const links = new SqliteLinkStore(new Database(dbPath), secrets);
250
250
  const keyIds = keys.map((key) => links.addKey(STUB_USER, key, `stub-key-${key}`).id);
251
251
  const stubUrl = `http://127.0.0.1:${provider.port}`;
252
252
  const configPath = join(dir, "dari-gateway.yaml");
@@ -91,7 +91,7 @@ export async function handleSubscriptionRequest(
91
91
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
92
92
  }
93
93
  if (action === "/auto-reset" && request.method === "POST") {
94
- throw new HttpError(400, "Spending banked Codex resets is not supported by this gateway.");
94
+ throw new HttpError(400, "Spending banked limit resets is not supported by this gateway.");
95
95
  }
96
96
  return null;
97
97
  } catch (error) {
@@ -214,7 +214,7 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
214
214
  // The share of its tightest window the plan last reported used, while
215
215
  // that window has not reset; null when it reports none.
216
216
  usage: usageBody(credential, now),
217
- // Spending banked Codex resets is hosted-only.
217
+ // Spending banked limit resets is hosted-only.
218
218
  auto_redeem_resets: false,
219
219
  };
220
220
  }
@@ -4,7 +4,7 @@
4
4
  // write so the immediate next turn can see next_model. Reporting failures are
5
5
  // always logged and swallowed.
6
6
 
7
- import { linkRequestRecorded, linkRequestStarted } from "../runtime/link_in_flight.js";
7
+ import { linkRequestRecorded, linkRequestStarted } from "../link/in_flight.js";
8
8
  import {
9
9
  selectPrefixHit,
10
10
  type CandidateCostEstimate,