@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,281 @@
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
+
8
+ import { randomUUID } from "node:crypto";
9
+
10
+ import { HttpError } from "../http/errors.js";
11
+ import type {
12
+ LinkApp,
13
+ LinkBudget,
14
+ LinkBudgetStanding,
15
+ LinkConnect,
16
+ LinkKeyProvider,
17
+ LinkPlanAdded,
18
+ LinkPlatform,
19
+ LinkSubscription,
20
+ } from "../platform/platform.js";
21
+ import type { SubscriptionKind } from "../types.js";
22
+ import { type BudgetUse, budgetLookbackMs, budgetStandings, overBudgetUntil } from "./budget.js";
23
+ import { budgetExhausted, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
24
+ import {
25
+ type ActiveLinkGrant,
26
+ LINK_CLIENT_SECRET_PREFIX,
27
+ LINK_CODE_PREFIX,
28
+ LINK_CODE_TTL_MS,
29
+ type LinkAppRecord,
30
+ type LinkRepo,
31
+ linkGrants,
32
+ linkHash,
33
+ linkSecret,
34
+ } from "./grants.js";
35
+
36
+ type MaybePromise<T> = T | Promise<T>;
37
+
38
+ /** A live grant as stored. */
39
+ export type LinkGrantRecord = {
40
+ id: string;
41
+ clientId: string;
42
+ appName: string;
43
+ // The user who approved it; null for a grant from before users had one.
44
+ subject: string | null;
45
+ credentialIds: string[];
46
+ createdAt: string;
47
+ budget: LinkBudget[];
48
+ };
49
+
50
+ /** Storage for Dari Link: the token protocol's steps, and grants. */
51
+ export type LinkStore = LinkRepo & {
52
+ /** Live grants of one user, or of everyone (null), oldest first. */
53
+ grants(subject: string | null): MaybePromise<LinkGrantRecord[]>;
54
+ /** A live grant; null when none is live by that id. */
55
+ grant(grantId: string): MaybePromise<LinkGrantRecord | null>;
56
+ /**
57
+ * Store a grant awaiting its code exchange, and return its id. With
58
+ * `grantId`, give that live grant of this user and app new plans, budget,
59
+ * and code instead; null when there is none.
60
+ */
61
+ saveGrant(request: {
62
+ grantId?: string;
63
+ subject: string;
64
+ clientId: string;
65
+ redirectUri: string;
66
+ codeHash: string;
67
+ codeChallenge: string;
68
+ codeExpiresAt: number;
69
+ credentialIds: string[];
70
+ budget: LinkBudget[];
71
+ now: number;
72
+ }): MaybePromise<string | null>;
73
+ /** Change a live grant's plans or budget; false when none is live by that id. */
74
+ updateGrant(grantId: string, change: { credentialIds?: string[]; budget?: LinkBudget[] }): MaybePromise<boolean>;
75
+ /** The tokens each of a grant's requests received after `since` used. */
76
+ budgetUses(grantId: string, since: number): MaybePromise<BudgetUse[]>;
77
+ };
78
+
79
+ /** A platform's users: who a key is, and where their plans and keys live. */
80
+ export type LinkUsers = {
81
+ /** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
82
+ sessionSecret(): string;
83
+ connectable: readonly SubscriptionKind[];
84
+ keyProviders: readonly LinkKeyProvider[];
85
+ /** See `LinkPlatform.httpRedirectHosts`. */
86
+ httpRedirectHosts?: readonly string[];
87
+ /**
88
+ * Store a registered app; with `apiKey`, owned by whoever that key is.
89
+ * Throws HttpError(401 or 403) for a key that may not register apps.
90
+ */
91
+ registerApp(app: LinkAppRecord, apiKey: string | undefined): Promise<void>;
92
+ /**
93
+ * Whose grants a management key manages: one user, or everyone (null).
94
+ * Throws HttpError(401 or 403) for a key that manages none.
95
+ */
96
+ manager(apiKey: string): Promise<string | null>;
97
+ /** When a grant's usage is complete through; null when the platform cannot tell. */
98
+ completeThrough(grantId: string): string | null;
99
+ /** A user's plans and API keys, oldest first. */
100
+ plans(subject: string): Promise<LinkSubscription[]>;
101
+ /** The plans and API keys with these ids, whoever added them. */
102
+ plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
103
+ /** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
104
+ addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
105
+ startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
106
+ completeConnect(subject: string | null, session: string, authorizationResponse: string): Promise<LinkPlanAdded | null>;
107
+ /** Delete one of the user's plans or keys; false when they have none by that id. */
108
+ removePlan(subject: string, credentialId: string): Promise<boolean>;
109
+ };
110
+
111
+ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
112
+ const protocol = linkGrants(store);
113
+
114
+ const standings = async (grant: { id: string; budget: LinkBudget[] }, now = new Date()): Promise<LinkBudgetStanding[]> =>
115
+ (await linkBudgetStandings(store, grant, now)).map((standing) => ({
116
+ ...standing,
117
+ resetsAt: standing.resetsAt?.toISOString() ?? null,
118
+ }));
119
+
120
+ // A live grant of this user's; null for anyone else's.
121
+ const ownGrant = async (subject: string | null, grantId: string) => {
122
+ const grant = await store.grant(grantId);
123
+ return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
124
+ };
125
+
126
+ const revoke = (grantId: string) => store.revokeGrant(grantId, "user", Date.now());
127
+
128
+ return {
129
+ httpRedirectHosts: users.httpRedirectHosts ?? [],
130
+ approval: {
131
+ sessionSecret: () => users.sessionSecret(),
132
+ connectable: users.connectable,
133
+ keyProviders: users.keyProviders,
134
+ subscriptions: (subject) => users.plans(subject),
135
+ async addKey(subject, provider, apiKey) {
136
+ if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
137
+ throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
138
+ }
139
+ return await users.addKey(subject, provider, apiKey);
140
+ },
141
+ startConnect: (kind) => users.startConnect(kind),
142
+ completeConnect: (subject, session, response) => users.completeConnect(subject, session, response),
143
+ async remove(subject, credentialId) {
144
+ if (!(await users.plans(subject)).some((plan) => plan.id === credentialId)) return false;
145
+ // Every app loses it first, and a grant left with nothing ends, so a
146
+ // failure part way never leaves a grant on a deleted plan.
147
+ for (const grant of await store.grants(subject)) {
148
+ if (!grant.credentialIds.includes(credentialId)) continue;
149
+ const left = grant.credentialIds.filter((id) => id !== credentialId);
150
+ if (left.length === 0) await revoke(grant.id);
151
+ else await store.updateGrant(grant.id, { credentialIds: left });
152
+ }
153
+ return await users.removePlan(subject, credentialId);
154
+ },
155
+ async grant(subject, grantId, clientId) {
156
+ const grant = await ownGrant(subject, grantId);
157
+ return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget };
158
+ },
159
+ async approve(request) {
160
+ const owned = new Set((await users.plans(request.subject)).map((plan) => plan.id));
161
+ if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => owned.has(id))) {
162
+ throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
163
+ }
164
+ const app = await store.appRecord(request.clientId);
165
+ if (app === null || !app.redirectUris.includes(request.redirectUri)) {
166
+ throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
167
+ }
168
+ const code = linkSecret(LINK_CODE_PREFIX);
169
+ const now = Date.now();
170
+ const grantId = await store.saveGrant({
171
+ ...(request.grantId === undefined ? {} : { grantId: request.grantId }),
172
+ subject: request.subject,
173
+ clientId: request.clientId,
174
+ redirectUri: request.redirectUri,
175
+ codeHash: linkHash(code),
176
+ codeChallenge: request.codeChallenge,
177
+ codeExpiresAt: now + LINK_CODE_TTL_MS,
178
+ credentialIds: [...new Set(request.credentialIds)].sort(),
179
+ budget: request.budget,
180
+ now,
181
+ });
182
+ if (grantId === null) throw new HttpError(400, "That connection no longer exists.", "invalid_request");
183
+ return { code };
184
+ },
185
+ async connections(subject) {
186
+ return await Promise.all((await store.grants(subject)).map(async (grant) => {
187
+ const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
188
+ return {
189
+ id: grant.id,
190
+ clientId: grant.clientId,
191
+ appName: grant.appName,
192
+ createdAt: grant.createdAt,
193
+ budget: await standings(grant),
194
+ subscriptions: await users.plansWithIds(grant.credentialIds),
195
+ usage,
196
+ };
197
+ }));
198
+ },
199
+ async disconnect(subject, grantId) {
200
+ return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
201
+ },
202
+ async setBudget(subject, grantId, budget) {
203
+ return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
204
+ },
205
+ },
206
+ async registerApp({ apiKey, name, redirectUris, confidential }) {
207
+ const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
208
+ const app: LinkApp = {
209
+ clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
210
+ name,
211
+ redirectUris,
212
+ confidential: clientSecret !== undefined,
213
+ };
214
+ await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
215
+ return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
216
+ },
217
+ async app(clientId) {
218
+ const record = await store.appRecord(clientId);
219
+ if (record === null) return null;
220
+ const { clientSecretHash: _, ...app } = record;
221
+ return app;
222
+ },
223
+ exchangeCode: (request) => protocol.exchangeCode(request),
224
+ refresh: (request) => protocol.refresh(request),
225
+ exchangeToken: (request) => protocol.exchangeToken(request),
226
+ revokeToken: (request) => protocol.revokeToken(request),
227
+ async grant(accessToken) {
228
+ const { id } = await protocol.parentGrant(accessToken);
229
+ const grant = await store.grant(id);
230
+ // Revoked since the token was read.
231
+ if (grant === null) throw linkGrantRevoked(null, null);
232
+ return {
233
+ id: grant.id,
234
+ clientId: grant.clientId,
235
+ appName: grant.appName,
236
+ createdAt: grant.createdAt,
237
+ budget: await standings(grant),
238
+ subscriptions: await users.plansWithIds(grant.credentialIds),
239
+ };
240
+ },
241
+ async usage({ accessToken, ...query }) {
242
+ const { id } = await protocol.parentGrant(accessToken);
243
+ // Read before the rows, so a request recorded in between is counted.
244
+ const completeThrough = users.completeThrough(id);
245
+ return { ...(await protocol.usage(id, query)), completeThrough };
246
+ },
247
+ async grants(apiKey) {
248
+ const subject = await users.manager(apiKey);
249
+ return (await store.grants(subject)).map(({ subject: _, ...grant }) => grant);
250
+ },
251
+ async setBudget({ apiKey, grantId, budget }) {
252
+ const subject = await users.manager(apiKey);
253
+ return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
254
+ },
255
+ async revokeGrant({ apiKey, grantId }) {
256
+ const subject = await users.manager(apiKey);
257
+ return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
258
+ },
259
+ };
260
+ }
261
+
262
+ /**
263
+ * The grant a link token serves a request for: null when the key is no link
264
+ * token. Throws the 401 a dead token gets, and the 424 a grant at its budget
265
+ * gets until its window rolls on.
266
+ */
267
+ export async function linkTokenGrant(store: LinkStore, token: string, now = new Date()): Promise<ActiveLinkGrant | null> {
268
+ const auth = await linkGrants(store).authenticate(token, now);
269
+ if (auth === null) return null;
270
+ if (auth.status === "expired") throw linkTokenExpired();
271
+ if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
272
+ const back = overBudgetUntil(await linkBudgetStandings(store, auth.grant, now));
273
+ if (back !== undefined) throw linkUnavailableError(budgetExhausted(back));
274
+ return auth.grant;
275
+ }
276
+
277
+ async function linkBudgetStandings(store: LinkStore, grant: { id: string; budget: LinkBudget[] }, now: Date) {
278
+ if (grant.budget.length === 0) return [];
279
+ const uses = await store.budgetUses(grant.id, now.getTime() - budgetLookbackMs(grant.budget));
280
+ return budgetStandings(grant.budget, uses, now);
281
+ }