@mupt-ai/dari-gateway 1.0.334 → 1.0.335
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.
- package/dist/activity/conversation_detail.js +4 -1
- package/dist/activity/conversations.js +2 -1
- package/dist/activity/http.d.ts +28 -3
- package/dist/activity/http.js +15 -10
- package/dist/activity/imports.d.ts +29 -0
- package/dist/activity/imports.js +230 -0
- package/dist/activity/pull_requests.d.ts +29 -0
- package/dist/activity/pull_requests.js +295 -0
- package/dist/activity/routes.d.ts +1 -1
- package/dist/activity/routes.js +7 -1
- package/dist/http/handler.d.ts +3 -2
- package/dist/http/handler.js +8 -2
- package/dist/ingress/git_events.d.ts +2 -0
- package/dist/ingress/git_events.js +143 -0
- package/dist/link/budget.d.ts +27 -2
- package/dist/link/budget.js +63 -1
- package/dist/link/endpoints.js +179 -36
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.js +11 -2
- package/dist/link/grants.d.ts +6 -5
- package/dist/link/grants.js +11 -9
- package/dist/link/service.d.ts +27 -6
- package/dist/link/service.js +145 -21
- package/dist/link/sqlite_store.d.ts +7 -2
- package/dist/link/sqlite_store.js +57 -6
- package/dist/platform/platform.d.ts +72 -3
- package/dist/protocol/input/router_model.d.ts +1 -0
- package/dist/protocol/input/router_model.js +6 -2
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +3 -0
- package/dist/self_host/activity_store.d.ts +15 -2
- package/dist/self_host/activity_store.js +60 -7
- package/dist/self_host/platform.js +6 -0
- package/dist/self_host/resolve.d.ts +4 -5
- package/dist/self_host/resolve.js +20 -22
- package/dist/telemetry/report.js +21 -2
- package/dist/telemetry/tools/git_events.d.ts +36 -0
- package/dist/telemetry/tools/git_events.js +109 -0
- package/dist/telemetry/tools/observations.d.ts +8 -1
- package/dist/telemetry/tools/observations.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +4 -1
- package/src/activity/conversations.ts +3 -2
- package/src/activity/http.ts +43 -12
- package/src/activity/imports.ts +278 -0
- package/src/activity/pull_requests.ts +342 -0
- package/src/activity/routes.ts +8 -2
- package/src/http/handler.ts +8 -2
- package/src/ingress/git_events.ts +145 -0
- package/src/link/budget.ts +80 -4
- package/src/link/endpoints.ts +171 -20
- package/src/link/errors.ts +12 -2
- package/src/link/grants.ts +22 -12
- package/src/link/service.ts +187 -24
- package/src/link/sqlite_store.ts +73 -10
- package/src/platform/platform.ts +57 -4
- package/src/protocol/input/router_model.ts +6 -2
- package/src/runtime/runtime_reporter.ts +5 -0
- package/src/self_host/activity_store.ts +79 -8
- package/src/self_host/platform.ts +6 -0
- package/src/self_host/resolve.ts +20 -25
- package/src/telemetry/report.ts +21 -2
- package/src/telemetry/tools/git_events.ts +125 -0
- package/src/telemetry/tools/observations.ts +1 -1
- package/src/types.ts +3 -0
package/src/link/service.ts
CHANGED
|
@@ -2,8 +2,13 @@
|
|
|
2
2
|
storage (`LinkStore`: the self-hosted gateway's SQLite database, hosted
|
|
3
3
|
Dari's control plane) and its users (`LinkUsers`: who a key or a page
|
|
4
4
|
visitor is, and where their plans and API keys live); `linkPlatform` makes
|
|
5
|
-
the rest: approving grants, managing them, budgets
|
|
6
|
-
(grants.ts).
|
|
5
|
+
the rest: approving grants, managing them, budgets and spend limits,
|
|
6
|
+
personal endpoints, and the token protocol (grants.ts).
|
|
7
|
+
|
|
8
|
+
A personal endpoint is a grant the user makes for themselves, on the plans
|
|
9
|
+
and keys they choose, called with a key that does not expire from any app
|
|
10
|
+
that takes the user's own key. Its grants belong to one built-in app,
|
|
11
|
+
`LINK_PERSONAL_CLIENT_ID`, which nothing can sign in to. */
|
|
7
12
|
|
|
8
13
|
import { randomUUID } from "node:crypto";
|
|
9
14
|
|
|
@@ -12,15 +17,26 @@ import type {
|
|
|
12
17
|
LinkBudget,
|
|
13
18
|
LinkBudgetStanding,
|
|
14
19
|
LinkConnect,
|
|
20
|
+
LinkGrant,
|
|
15
21
|
LinkKeyProvider,
|
|
22
|
+
LinkLimit,
|
|
23
|
+
LinkManagedGrant,
|
|
16
24
|
LinkPlanAdded,
|
|
17
25
|
LinkPlatform,
|
|
18
26
|
LinkSignIn,
|
|
27
|
+
LinkSpend,
|
|
19
28
|
LinkSubscription,
|
|
20
29
|
} from "../platform/platform.js";
|
|
21
30
|
import type { SubscriptionKind } from "../types.js";
|
|
22
|
-
import {
|
|
23
|
-
|
|
31
|
+
import {
|
|
32
|
+
type BudgetUse,
|
|
33
|
+
budgetStandings,
|
|
34
|
+
grantSpend,
|
|
35
|
+
nextMonthStart,
|
|
36
|
+
overBudgetUntil,
|
|
37
|
+
usesSince,
|
|
38
|
+
} from "./budget.js";
|
|
39
|
+
import { budgetExhausted, limitsReached, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
24
40
|
import {
|
|
25
41
|
type ActiveLinkGrant,
|
|
26
42
|
LINK_CLIENT_SECRET_PREFIX,
|
|
@@ -28,23 +44,31 @@ import {
|
|
|
28
44
|
LINK_CODE_TTL_MS,
|
|
29
45
|
type LinkAppRecord,
|
|
30
46
|
type LinkRepo,
|
|
47
|
+
type LinkTokenIssue,
|
|
31
48
|
linkGrants,
|
|
32
49
|
linkHash,
|
|
33
50
|
linkSecret,
|
|
51
|
+
LINK_TOKEN_RETENTION_MS,
|
|
52
|
+
TOKEN_PREFIX,
|
|
34
53
|
} from "./grants.js";
|
|
35
54
|
|
|
55
|
+
/** The built-in app every personal endpoint's grant belongs to. */
|
|
56
|
+
export const LINK_PERSONAL_CLIENT_ID = "lnk_personal";
|
|
57
|
+
|
|
36
58
|
type MaybePromise<T> = T | Promise<T>;
|
|
37
59
|
|
|
38
60
|
/** A live grant as stored. */
|
|
39
61
|
export type LinkGrantRecord = {
|
|
40
62
|
id: string;
|
|
41
63
|
clientId: string;
|
|
64
|
+
// The app's name, or a personal endpoint's own.
|
|
42
65
|
appName: string;
|
|
43
66
|
// The user who approved it; null for a grant from before users had one.
|
|
44
67
|
subject: string | null;
|
|
45
68
|
credentialIds: string[];
|
|
46
69
|
createdAt: string;
|
|
47
70
|
budget: LinkBudget[];
|
|
71
|
+
limits: LinkLimit[];
|
|
48
72
|
};
|
|
49
73
|
|
|
50
74
|
/** Storage for Dari Link: the token protocol's steps, and grants. */
|
|
@@ -70,9 +94,27 @@ export type LinkStore = LinkRepo & {
|
|
|
70
94
|
budget: LinkBudget[];
|
|
71
95
|
now: number;
|
|
72
96
|
}): MaybePromise<string | null>;
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Store a personal endpoint: a grant of `LINK_PERSONAL_CLIENT_ID` named
|
|
99
|
+
* `name`, live at once, with its key token, in one step. Its id.
|
|
100
|
+
*/
|
|
101
|
+
createEndpoint(request: {
|
|
102
|
+
subject: string;
|
|
103
|
+
name: string;
|
|
104
|
+
credentialIds: string[];
|
|
105
|
+
limits: LinkLimit[];
|
|
106
|
+
key: LinkTokenIssue;
|
|
107
|
+
now: number;
|
|
108
|
+
}): MaybePromise<string>;
|
|
109
|
+
/**
|
|
110
|
+
* Change a live grant's plans, budget, or limits, or an endpoint's name;
|
|
111
|
+
* false when none is live by that id.
|
|
112
|
+
*/
|
|
113
|
+
updateGrant(
|
|
114
|
+
grantId: string,
|
|
115
|
+
change: { credentialIds?: string[]; budget?: LinkBudget[]; limits?: LinkLimit[]; name?: string },
|
|
116
|
+
): MaybePromise<boolean>;
|
|
117
|
+
/** What each of a grant's requests received after `since` used and cost. */
|
|
76
118
|
budgetUses(grantId: string, since: number): MaybePromise<BudgetUse[]>;
|
|
77
119
|
};
|
|
78
120
|
|
|
@@ -119,18 +161,70 @@ export type LinkUsers = {
|
|
|
119
161
|
export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
120
162
|
const protocol = linkGrants(store);
|
|
121
163
|
|
|
122
|
-
const standings = async (grant: { id: string; budget: LinkBudget[] }, now = new Date()): Promise<LinkBudgetStanding[]> =>
|
|
123
|
-
(await linkBudgetStandings(store, grant, now)).map((standing) => ({
|
|
124
|
-
...standing,
|
|
125
|
-
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
126
|
-
}));
|
|
127
|
-
|
|
128
164
|
// A live grant of this user's; null for anyone else's.
|
|
129
165
|
const ownGrant = async (subject: string | null, grantId: string) => {
|
|
130
166
|
const grant = await store.grant(grantId);
|
|
131
167
|
return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
|
|
132
168
|
};
|
|
133
169
|
|
|
170
|
+
// A grant's budget windows and each granted plan or key's spend this month.
|
|
171
|
+
const standings = async (grant: LinkGrantRecord, now = new Date()): Promise<{
|
|
172
|
+
budget: LinkBudgetStanding[];
|
|
173
|
+
spend: LinkSpend[];
|
|
174
|
+
}> => {
|
|
175
|
+
const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
|
|
176
|
+
return {
|
|
177
|
+
budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
|
|
178
|
+
...standing,
|
|
179
|
+
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
180
|
+
})),
|
|
181
|
+
spend: grantSpend(grant.credentialIds, grant.limits, uses, now),
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const publicGrant = ({ subject: _, ...grant }: LinkGrantRecord): LinkGrant => ({
|
|
186
|
+
...grant,
|
|
187
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const managedGrant = async (grant: LinkGrantRecord): Promise<LinkManagedGrant> => ({
|
|
191
|
+
...publicGrant(grant),
|
|
192
|
+
spend: (await standings(grant)).spend,
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// Plans and keys the user can grant, and limits only on them.
|
|
196
|
+
const ownedCredentials = async (subject: string, credentialIds: readonly string[], limits: readonly LinkLimit[] = []) => {
|
|
197
|
+
const owned = new Set((await users.plans(subject)).map((plan) => plan.id));
|
|
198
|
+
if (credentialIds.length === 0 || !credentialIds.every((id) => owned.has(id))) {
|
|
199
|
+
throw new HttpError(400, "Choose one or more of your connected plans or API keys.", "invalid_request");
|
|
200
|
+
}
|
|
201
|
+
if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
|
|
202
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
203
|
+
}
|
|
204
|
+
return [...new Set(credentialIds)].sort();
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// The one user a key acts for: endpoints are personal, so an operator key
|
|
208
|
+
// that manages everyone cannot make one.
|
|
209
|
+
const endpointOwner = async (apiKey: string): Promise<string> => {
|
|
210
|
+
const subject = await users.manager(apiKey);
|
|
211
|
+
if (subject === null) {
|
|
212
|
+
throw new HttpError(403, "Use your personal key: an endpoint serves one user's plans.", "permission_denied");
|
|
213
|
+
}
|
|
214
|
+
return subject;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const ownEndpoint = async (subject: string | null, grantId: string) => {
|
|
218
|
+
const grant = await ownGrant(subject, grantId);
|
|
219
|
+
return grant !== null && grant.clientId === LINK_PERSONAL_CLIENT_ID ? grant : null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const newKey = (): { key: string; issue: LinkTokenIssue } => {
|
|
223
|
+
const key = linkSecret(TOKEN_PREFIX.key);
|
|
224
|
+
return { key, issue: { tokenHash: linkHash(key), kind: "key", expiresAt: null } };
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
|
|
134
228
|
const revoke = (grantId: string) => store.revokeGrant(grantId, "user", Date.now());
|
|
135
229
|
|
|
136
230
|
return {
|
|
@@ -198,8 +292,9 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
198
292
|
id: grant.id,
|
|
199
293
|
clientId: grant.clientId,
|
|
200
294
|
appName: grant.appName,
|
|
295
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
201
296
|
createdAt: grant.createdAt,
|
|
202
|
-
|
|
297
|
+
...(await standings(grant)),
|
|
203
298
|
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
204
299
|
usage,
|
|
205
300
|
};
|
|
@@ -211,6 +306,12 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
211
306
|
async setBudget(subject, grantId, budget) {
|
|
212
307
|
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
213
308
|
},
|
|
309
|
+
async setLimits(subject, grantId, limits) {
|
|
310
|
+
const grant = await ownGrant(subject, grantId);
|
|
311
|
+
if (grant === null) return false;
|
|
312
|
+
await ownedCredentials(subject, grant.credentialIds, limits);
|
|
313
|
+
return await store.updateGrant(grantId, { limits });
|
|
314
|
+
},
|
|
214
315
|
},
|
|
215
316
|
async registerApp({ apiKey, name, redirectUris, confidential }) {
|
|
216
317
|
if (apiKey === undefined && !users.openRegistration) {
|
|
@@ -240,8 +341,9 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
240
341
|
id: grant.id,
|
|
241
342
|
clientId: grant.clientId,
|
|
242
343
|
appName: grant.appName,
|
|
344
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
243
345
|
createdAt: grant.createdAt,
|
|
244
|
-
|
|
346
|
+
...(await standings(grant)),
|
|
245
347
|
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
246
348
|
};
|
|
247
349
|
},
|
|
@@ -253,7 +355,56 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
253
355
|
},
|
|
254
356
|
async grants(apiKey) {
|
|
255
357
|
const subject = await users.manager(apiKey);
|
|
256
|
-
return (await store.grants(subject)).map(
|
|
358
|
+
return await Promise.all((await store.grants(subject)).map(managedGrant));
|
|
359
|
+
},
|
|
360
|
+
async plans(apiKey) {
|
|
361
|
+
return await users.plans(await endpointOwner(apiKey));
|
|
362
|
+
},
|
|
363
|
+
async createEndpoint({ apiKey, name, credentialIds, limits }) {
|
|
364
|
+
const subject = await endpointOwner(apiKey);
|
|
365
|
+
const granted = await ownedCredentials(subject, credentialIds, limits);
|
|
366
|
+
const { key, issue } = newKey();
|
|
367
|
+
const grantId = await store.createEndpoint({
|
|
368
|
+
subject,
|
|
369
|
+
name: endpointName(name),
|
|
370
|
+
credentialIds: granted,
|
|
371
|
+
limits,
|
|
372
|
+
key: issue,
|
|
373
|
+
now: Date.now(),
|
|
374
|
+
});
|
|
375
|
+
const grant = await store.grant(grantId);
|
|
376
|
+
if (grant === null) throw new Error("A new endpoint's grant was not stored.");
|
|
377
|
+
return { grant: await managedGrant(grant), key };
|
|
378
|
+
},
|
|
379
|
+
async updateEndpoint({ apiKey, grantId, name, credentialIds }) {
|
|
380
|
+
const subject = await endpointOwner(apiKey);
|
|
381
|
+
const grant = await ownEndpoint(subject, grantId);
|
|
382
|
+
if (grant === null) return false;
|
|
383
|
+
const granted = credentialIds === undefined ? undefined : await ownedCredentials(subject, credentialIds);
|
|
384
|
+
return await store.updateGrant(grantId, {
|
|
385
|
+
...(name === undefined ? {} : { name: endpointName(name) }),
|
|
386
|
+
...(granted === undefined
|
|
387
|
+
? {}
|
|
388
|
+
// A plan or key the endpoint no longer shares keeps no limit.
|
|
389
|
+
: { credentialIds: granted, limits: grant.limits.filter((limit) => granted.includes(limit.credentialId)) }),
|
|
390
|
+
});
|
|
391
|
+
},
|
|
392
|
+
async issueEndpointKey({ apiKey, grantId }) {
|
|
393
|
+
const subject = await endpointOwner(apiKey);
|
|
394
|
+
if ((await ownEndpoint(subject, grantId)) === null) return null;
|
|
395
|
+
const { key, issue } = newKey();
|
|
396
|
+
const now = Date.now();
|
|
397
|
+
const result = await store.issueTokens({ grantId, tokens: [issue], now, forgetBefore: now - LINK_TOKEN_RETENTION_MS });
|
|
398
|
+
return result === "ok" ? key : null;
|
|
399
|
+
},
|
|
400
|
+
async setLimits({ apiKey, grantId, limits }) {
|
|
401
|
+
const subject = await users.manager(apiKey);
|
|
402
|
+
const grant = await ownGrant(subject, grantId);
|
|
403
|
+
if (grant === null) return false;
|
|
404
|
+
if (!limits.every((limit) => grant.credentialIds.includes(limit.credentialId))) {
|
|
405
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
406
|
+
}
|
|
407
|
+
return await store.updateGrant(grantId, { limits });
|
|
257
408
|
},
|
|
258
409
|
async setBudget({ apiKey, grantId, budget }) {
|
|
259
410
|
const subject = await users.manager(apiKey);
|
|
@@ -294,21 +445,33 @@ export function newLinkClientSecret(): { secret: string; hash: string } {
|
|
|
294
445
|
|
|
295
446
|
/**
|
|
296
447
|
* The grant a link token serves a request for: null when the key is no link
|
|
297
|
-
* token.
|
|
298
|
-
* gets
|
|
448
|
+
* token. Its plans and keys at their monthly spend limit are left out. Throws
|
|
449
|
+
* the 401 a dead token gets, and the 424 a grant at its budget, or with every
|
|
450
|
+
* plan and key at its limit, gets until it serves again.
|
|
299
451
|
*/
|
|
300
452
|
export async function linkTokenGrant(store: LinkStore, token: string, now = new Date()): Promise<ActiveLinkGrant | null> {
|
|
301
453
|
const auth = await linkGrants(store).authenticate(token, now);
|
|
302
454
|
if (auth === null) return null;
|
|
303
455
|
if (auth.status === "expired") throw linkTokenExpired();
|
|
304
456
|
if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
|
|
305
|
-
const
|
|
457
|
+
const { grant } = auth;
|
|
458
|
+
if (grant.budget.length === 0 && grant.limits.length === 0) return grant;
|
|
459
|
+
const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
|
|
460
|
+
const back = overBudgetUntil(budgetStandings(grant.budget, uses, now));
|
|
306
461
|
if (back !== undefined) throw linkUnavailableError(budgetExhausted(back));
|
|
307
|
-
|
|
462
|
+
const reached = new Set(
|
|
463
|
+
grantSpend(grant.credentialIds, grant.limits, uses, now).filter((entry) => entry.reached).map((entry) => entry.credentialId),
|
|
464
|
+
);
|
|
465
|
+
if (reached.size === 0) return grant;
|
|
466
|
+
const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.has(id)));
|
|
467
|
+
if (credentialIds.size === 0) throw linkUnavailableError(limitsReached(nextMonthStart(now)));
|
|
468
|
+
return { ...grant, credentialIds };
|
|
308
469
|
}
|
|
309
470
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
471
|
+
function endpointName(name: string): string {
|
|
472
|
+
const trimmed = name.trim();
|
|
473
|
+
if (trimmed.length === 0 || trimmed.length > 120) {
|
|
474
|
+
throw new HttpError(400, "Name the endpoint, in 120 characters or fewer.", "invalid_request");
|
|
475
|
+
}
|
|
476
|
+
return trimmed;
|
|
314
477
|
}
|
package/src/link/sqlite_store.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { Database } from "bun:sqlite";
|
|
|
8
8
|
import { randomUUID } from "node:crypto";
|
|
9
9
|
|
|
10
10
|
import { type SecretBox, openWithoutKey } from "../self_host/secret_box.js";
|
|
11
|
-
import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
|
|
11
|
+
import type { LinkBudget, LinkLimit, LinkUsageQuery } from "../platform/platform.js";
|
|
12
12
|
import type { BudgetUse, LinkTokenCounts } from "./budget.js";
|
|
13
13
|
import {
|
|
14
14
|
type LinkAppRecord,
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
type LinkTokenRecord,
|
|
20
20
|
type LinkUsageRecord,
|
|
21
21
|
} from "./grants.js";
|
|
22
|
-
import type
|
|
22
|
+
import { LINK_PERSONAL_CLIENT_ID, type LinkGrantRecord, type LinkStore } from "./service.js";
|
|
23
23
|
|
|
24
24
|
type AppRow = {
|
|
25
25
|
client_id: string;
|
|
@@ -34,6 +34,7 @@ type GrantRow = {
|
|
|
34
34
|
credential_ids: string;
|
|
35
35
|
created_at: number;
|
|
36
36
|
budget: string | null;
|
|
37
|
+
limits: string | null;
|
|
37
38
|
subject: string | null;
|
|
38
39
|
};
|
|
39
40
|
|
|
@@ -59,18 +60,19 @@ type TokenRow = {
|
|
|
59
60
|
client_id: string;
|
|
60
61
|
credential_ids: string;
|
|
61
62
|
budget: string | null;
|
|
63
|
+
limits: string | null;
|
|
62
64
|
revoked_at: number | null;
|
|
63
65
|
revoked_by: string | null;
|
|
64
66
|
};
|
|
65
67
|
|
|
66
68
|
const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
|
|
67
69
|
link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
|
|
68
|
-
link_grants.credential_ids, link_grants.budget, link_grants.revoked_at, link_grants.revoked_by
|
|
70
|
+
link_grants.credential_ids, link_grants.budget, link_grants.limits, link_grants.revoked_at, link_grants.revoked_by
|
|
69
71
|
FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
|
|
70
72
|
WHERE link_tokens.token_hash = ?`;
|
|
71
73
|
|
|
72
74
|
const LIVE_GRANTS = `SELECT link_grants.id, link_grants.client_id, link_grants.credential_ids, link_grants.created_at,
|
|
73
|
-
link_grants.budget, link_grants.subject, link_apps.name AS app_name
|
|
75
|
+
link_grants.budget, link_grants.limits, link_grants.subject, COALESCE(link_grants.name, link_apps.name) AS app_name
|
|
74
76
|
FROM link_grants JOIN link_apps ON link_apps.client_id = link_grants.client_id
|
|
75
77
|
WHERE link_grants.revoked_at IS NULL`;
|
|
76
78
|
|
|
@@ -127,8 +129,19 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
127
129
|
if (!grantColumns.some((column) => column.name === "subject")) db.run("ALTER TABLE link_grants ADD COLUMN subject TEXT");
|
|
128
130
|
const tokenColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_tokens)").all();
|
|
129
131
|
if (!tokenColumns.some((column) => column.name === "pins")) db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
|
|
132
|
+
// A personal endpoint's name, and each grant's monthly spend limits.
|
|
133
|
+
if (!grantColumns.some((column) => column.name === "name")) db.run("ALTER TABLE link_grants ADD COLUMN name TEXT");
|
|
134
|
+
if (!grantColumns.some((column) => column.name === "limits")) db.run("ALTER TABLE link_grants ADD COLUMN limits TEXT");
|
|
130
135
|
const usageColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_usage)").all();
|
|
131
136
|
if (!usageColumns.some((column) => column.name === "status")) db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
|
|
137
|
+
// What a request cost, and the plan or key that served it.
|
|
138
|
+
if (!usageColumns.some((column) => column.name === "cost_usd")) db.run("ALTER TABLE link_usage ADD COLUMN cost_usd REAL");
|
|
139
|
+
if (!usageColumns.some((column) => column.name === "credential_id")) db.run("ALTER TABLE link_usage ADD COLUMN credential_id TEXT");
|
|
140
|
+
// The app every personal endpoint's grant belongs to.
|
|
141
|
+
db.run(
|
|
142
|
+
"INSERT OR IGNORE INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, '[]', NULL, 0)",
|
|
143
|
+
[LINK_PERSONAL_CLIENT_ID, "Personal Endpoint"],
|
|
144
|
+
);
|
|
132
145
|
// API keys users added on the approval page: one per user and provider.
|
|
133
146
|
db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
|
|
134
147
|
id TEXT PRIMARY KEY,
|
|
@@ -210,20 +223,25 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
210
223
|
|
|
211
224
|
budgetUses(grantId: string, since: number): BudgetUse[] {
|
|
212
225
|
return this.db
|
|
213
|
-
.query<UsageTokenRow & { received_at: number }, [string, number]>(
|
|
214
|
-
`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
|
|
226
|
+
.query<UsageTokenRow & { received_at: number; cost_usd: number | null; credential_id: string | null }, [string, number]>(
|
|
227
|
+
`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd, credential_id
|
|
215
228
|
FROM link_usage WHERE grant_id = ? AND received_at > ?`,
|
|
216
229
|
)
|
|
217
230
|
.all(grantId, since)
|
|
218
|
-
.map((row) => ({
|
|
231
|
+
.map((row) => ({
|
|
232
|
+
at: new Date(row.received_at),
|
|
233
|
+
...tokenCounts(row),
|
|
234
|
+
costUsd: row.cost_usd ?? 0,
|
|
235
|
+
credentialId: row.credential_id,
|
|
236
|
+
}));
|
|
219
237
|
}
|
|
220
238
|
|
|
221
239
|
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
222
240
|
recordUsage(entry: LinkUsageEntry): void {
|
|
223
241
|
this.db.run(
|
|
224
242
|
`INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
|
|
225
|
-
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
|
|
226
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
243
|
+
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status, cost_usd, credential_id)
|
|
244
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
227
245
|
[
|
|
228
246
|
entry.requestId,
|
|
229
247
|
entry.grantId,
|
|
@@ -236,6 +254,8 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
236
254
|
entry.cacheReadTokens,
|
|
237
255
|
entry.cacheWriteTokens,
|
|
238
256
|
entry.status,
|
|
257
|
+
entry.costUsd,
|
|
258
|
+
entry.credentialId,
|
|
239
259
|
],
|
|
240
260
|
);
|
|
241
261
|
}
|
|
@@ -321,7 +341,31 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
321
341
|
return id;
|
|
322
342
|
}
|
|
323
343
|
|
|
324
|
-
|
|
344
|
+
createEndpoint(request: Parameters<LinkStore["createEndpoint"]>[0]): string {
|
|
345
|
+
const id = `lgr_${randomUUID().replaceAll("-", "")}`;
|
|
346
|
+
this.db.transaction(() => {
|
|
347
|
+
this.db.run(
|
|
348
|
+
`INSERT INTO link_grants (id, client_id, credential_ids, created_at, limits, subject, name)
|
|
349
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
350
|
+
[
|
|
351
|
+
id,
|
|
352
|
+
LINK_PERSONAL_CLIENT_ID,
|
|
353
|
+
JSON.stringify(request.credentialIds),
|
|
354
|
+
request.now,
|
|
355
|
+
request.limits.length === 0 ? null : JSON.stringify(request.limits),
|
|
356
|
+
request.subject,
|
|
357
|
+
request.name,
|
|
358
|
+
],
|
|
359
|
+
);
|
|
360
|
+
this.insertTokens(id, [request.key], request.now);
|
|
361
|
+
})();
|
|
362
|
+
return id;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
updateGrant(
|
|
366
|
+
grantId: string,
|
|
367
|
+
change: { credentialIds?: string[]; budget?: LinkBudget[]; limits?: LinkLimit[]; name?: string },
|
|
368
|
+
): boolean {
|
|
325
369
|
return this.db.transaction(() => {
|
|
326
370
|
const changed = this.grant(grantId) !== null;
|
|
327
371
|
if (changed && change.credentialIds !== undefined) {
|
|
@@ -333,6 +377,15 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
333
377
|
grantId,
|
|
334
378
|
]);
|
|
335
379
|
}
|
|
380
|
+
if (changed && change.limits !== undefined) {
|
|
381
|
+
this.db.run("UPDATE link_grants SET limits = ? WHERE id = ?", [
|
|
382
|
+
change.limits.length === 0 ? null : JSON.stringify(change.limits),
|
|
383
|
+
grantId,
|
|
384
|
+
]);
|
|
385
|
+
}
|
|
386
|
+
if (changed && change.name !== undefined) {
|
|
387
|
+
this.db.run("UPDATE link_grants SET name = ? WHERE id = ?", [change.name, grantId]);
|
|
388
|
+
}
|
|
336
389
|
return changed;
|
|
337
390
|
})();
|
|
338
391
|
}
|
|
@@ -382,6 +435,7 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
382
435
|
clientId: row.client_id,
|
|
383
436
|
credentialIds: parseIds(row.credential_ids),
|
|
384
437
|
budget: parseBudget(row.budget),
|
|
438
|
+
limits: parseLimits(row.limits),
|
|
385
439
|
revokedAt: row.revoked_at,
|
|
386
440
|
revokedBy: row.revoked_by,
|
|
387
441
|
usable: true,
|
|
@@ -464,6 +518,10 @@ export type LinkUsageEntry = {
|
|
|
464
518
|
cacheWriteTokens: number;
|
|
465
519
|
// The request's outcome, as the request record's `status`.
|
|
466
520
|
status: string;
|
|
521
|
+
// What it cost in US dollars (a plan's at API prices), and the plan or key
|
|
522
|
+
// that served it.
|
|
523
|
+
costUsd: number | null;
|
|
524
|
+
credentialId: string | null;
|
|
467
525
|
};
|
|
468
526
|
|
|
469
527
|
type UsageTokenRow = {
|
|
@@ -506,9 +564,14 @@ function grantRecord(row: GrantRow & { app_name: string }): LinkGrantRecord {
|
|
|
506
564
|
credentialIds: parseIds(row.credential_ids),
|
|
507
565
|
createdAt: new Date(row.created_at).toISOString(),
|
|
508
566
|
budget: parseBudget(row.budget),
|
|
567
|
+
limits: parseLimits(row.limits),
|
|
509
568
|
};
|
|
510
569
|
}
|
|
511
570
|
|
|
571
|
+
function parseLimits(value: string | null): LinkLimit[] {
|
|
572
|
+
return value === null ? [] : JSON.parse(value) as LinkLimit[];
|
|
573
|
+
}
|
|
574
|
+
|
|
512
575
|
function parseIds(value: string): string[] {
|
|
513
576
|
return JSON.parse(value) as string[];
|
|
514
577
|
}
|
package/src/platform/platform.ts
CHANGED
|
@@ -171,8 +171,35 @@ export type LinkPlatform = {
|
|
|
171
171
|
* is the client's (RFC 7009). Unknown tokens are ignored.
|
|
172
172
|
*/
|
|
173
173
|
revokeToken(request: LinkClient & { token: string }): Promise<void>;
|
|
174
|
-
/**
|
|
175
|
-
|
|
174
|
+
/**
|
|
175
|
+
* The user's grants that are not revoked, app connections and personal
|
|
176
|
+
* endpoints alike, each with every granted credential's spend this month.
|
|
177
|
+
* `apiKey` is a personal management key, or on hosted Dari the user's session.
|
|
178
|
+
*/
|
|
179
|
+
grants(apiKey: string): Promise<LinkManagedGrant[]>;
|
|
180
|
+
/** The plans and API keys the user can grant. */
|
|
181
|
+
plans(apiKey: string): Promise<LinkSubscription[]>;
|
|
182
|
+
/**
|
|
183
|
+
* A personal endpoint: a grant the user makes for themselves on their chosen
|
|
184
|
+
* plans and keys, and its key, returned this once, which an app that takes
|
|
185
|
+
* the user's own key calls with. Throws HttpError(400) for a plan or key the
|
|
186
|
+
* user does not have, or for bad limits.
|
|
187
|
+
*/
|
|
188
|
+
createEndpoint(request: {
|
|
189
|
+
apiKey: string;
|
|
190
|
+
name: string;
|
|
191
|
+
credentialIds: string[];
|
|
192
|
+
limits: LinkLimit[];
|
|
193
|
+
}): Promise<{ grant: LinkManagedGrant; key: string }>;
|
|
194
|
+
/** Rename one of the user's endpoints or change its plans; false when they have none by that id. */
|
|
195
|
+
updateEndpoint(request: { apiKey: string; grantId: string; name?: string; credentialIds?: string[] }): Promise<boolean>;
|
|
196
|
+
/** Another key for one of the user's endpoints, returned this once; null when they have none by that id. */
|
|
197
|
+
issueEndpointKey(request: { apiKey: string; grantId: string }): Promise<string | null>;
|
|
198
|
+
/**
|
|
199
|
+
* Replace one of the user's grants' monthly spend limits (empty removes
|
|
200
|
+
* them); false when the user has no grant by that id.
|
|
201
|
+
*/
|
|
202
|
+
setLimits(request: { apiKey: string; grantId: string; limits: LinkLimit[] }): Promise<boolean>;
|
|
176
203
|
/** Revoke one of the user's grants; false when it has none by that id. */
|
|
177
204
|
revokeGrant(request: { apiKey: string; grantId: string }): Promise<boolean>;
|
|
178
205
|
/**
|
|
@@ -241,6 +268,8 @@ export type LinkApprovalPage = {
|
|
|
241
268
|
disconnect(subject: string, grantId: string): Promise<boolean>;
|
|
242
269
|
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
243
270
|
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
271
|
+
/** Replace one of the user's grants' monthly spend limits; false when they have none by that id. */
|
|
272
|
+
setLimits(subject: string, grantId: string, limits: LinkLimit[]): Promise<boolean>;
|
|
244
273
|
};
|
|
245
274
|
|
|
246
275
|
/**
|
|
@@ -287,6 +316,22 @@ export type LinkConnect = {
|
|
|
287
316
|
*/
|
|
288
317
|
export type LinkBudget = { windowMinutes: number; maxTokens: number };
|
|
289
318
|
|
|
319
|
+
/**
|
|
320
|
+
* The most a grant may spend on one of its plans or API keys in a calendar
|
|
321
|
+
* month (UTC), in US dollars. A plan's spend is what its requests would have
|
|
322
|
+
* cost at API prices. See link/budget.ts.
|
|
323
|
+
*/
|
|
324
|
+
export type LinkLimit = { credentialId: string; monthlyUsd: number };
|
|
325
|
+
|
|
326
|
+
/** A granted plan or key's spend this month, and its limit when it has one. */
|
|
327
|
+
export type LinkSpend = {
|
|
328
|
+
credentialId: string;
|
|
329
|
+
spentUsd: number;
|
|
330
|
+
monthlyUsd: number | null;
|
|
331
|
+
// At its limit: the grant leaves it out until the month ends.
|
|
332
|
+
reached: boolean;
|
|
333
|
+
};
|
|
334
|
+
|
|
290
335
|
/** A budget window as it stands for a grant. */
|
|
291
336
|
export type LinkBudgetStanding = {
|
|
292
337
|
windowMinutes: number;
|
|
@@ -384,12 +429,19 @@ export type LinkChildToken = {
|
|
|
384
429
|
export type LinkGrant = {
|
|
385
430
|
id: string;
|
|
386
431
|
clientId: string;
|
|
432
|
+
// The app's name, or a personal endpoint's own.
|
|
387
433
|
appName: string;
|
|
434
|
+
// A grant the user made for themselves, called with a key (see `createEndpoint`).
|
|
435
|
+
endpoint: boolean;
|
|
388
436
|
credentialIds: string[];
|
|
389
437
|
createdAt: string;
|
|
390
438
|
budget: LinkBudget[];
|
|
439
|
+
limits: LinkLimit[];
|
|
391
440
|
};
|
|
392
441
|
|
|
442
|
+
/** A grant as its user manages it. */
|
|
443
|
+
export type LinkManagedGrant = LinkGrant & { spend: LinkSpend[] };
|
|
444
|
+
|
|
393
445
|
/** A grant as its app sees it: the granted subscriptions themselves. */
|
|
394
446
|
export type LinkUsageQuery = {
|
|
395
447
|
accessToken: string;
|
|
@@ -426,8 +478,9 @@ export type LinkUsage = LinkUsageTotals & {
|
|
|
426
478
|
completeThrough: string | null;
|
|
427
479
|
};
|
|
428
480
|
|
|
429
|
-
export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget"> & {
|
|
481
|
+
export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget" | "limits"> & {
|
|
430
482
|
budget: LinkBudgetStanding[];
|
|
483
|
+
spend: LinkSpend[];
|
|
431
484
|
subscriptions: LinkSubscription[];
|
|
432
485
|
};
|
|
433
486
|
|
|
@@ -536,7 +589,7 @@ export type RequestRecord = {
|
|
|
536
589
|
tags: RequestTags;
|
|
537
590
|
// Set for a Dari Link token's request: its grant, and the thinking the
|
|
538
591
|
// provider was sent (as X-Dari-Thinking-Level reports it).
|
|
539
|
-
link?: { grantId: string; thinking: string | null };
|
|
592
|
+
link?: { grantId: string; thinking: string | null; costUsd: number | null; credentialId: string | null };
|
|
540
593
|
// The router's non-secret routing settings, for embedders that compare or
|
|
541
594
|
// replay routing decisions.
|
|
542
595
|
router: RequestRecordRouter;
|
|
@@ -49,12 +49,16 @@ export function explicitModelSlug(modelId: string): string {
|
|
|
49
49
|
return EXPLICIT_MODEL_PREFIX + modelId;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
// A Dari Link token's access and
|
|
52
|
+
// A Dari Link token's access, child, and endpoint key tokens, which every
|
|
53
|
+
// platform issues.
|
|
53
54
|
export const LINK_ACCESS_TOKEN_PREFIX = "dlk_at_";
|
|
54
55
|
export const LINK_CHILD_TOKEN_PREFIX = "dlk_ct_";
|
|
56
|
+
export const LINK_KEY_TOKEN_PREFIX = "dlk_key_";
|
|
55
57
|
|
|
56
58
|
export function isLinkToken(token: string): boolean {
|
|
57
|
-
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX)
|
|
59
|
+
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX)
|
|
60
|
+
|| token.startsWith(LINK_CHILD_TOKEN_PREFIX)
|
|
61
|
+
|| token.startsWith(LINK_KEY_TOKEN_PREFIX);
|
|
58
62
|
}
|
|
59
63
|
|
|
60
64
|
/* A Dari Link token is served exactly the model it names, so every name but
|
|
@@ -9,6 +9,8 @@ export type ReportedProviderExecution = {
|
|
|
9
9
|
providerKeySource: ProviderKeySource;
|
|
10
10
|
// The thinking the provider was sent, as X-Dari-Thinking-Level reports it.
|
|
11
11
|
thinkingLevel?: string;
|
|
12
|
+
// The user's subscription that served it.
|
|
13
|
+
subscriptionCredentialId?: string;
|
|
12
14
|
};
|
|
13
15
|
|
|
14
16
|
export function reportedExecution(
|
|
@@ -19,6 +21,9 @@ export function reportedExecution(
|
|
|
19
21
|
model: execution.model,
|
|
20
22
|
providerKeySource: execution.providerKeySource,
|
|
21
23
|
...(execution.thinkingLevel === undefined ? {} : { thinkingLevel: execution.thinkingLevel }),
|
|
24
|
+
...(execution.subscriptionCredentialId === undefined
|
|
25
|
+
? {}
|
|
26
|
+
: { subscriptionCredentialId: execution.subscriptionCredentialId }),
|
|
22
27
|
};
|
|
23
28
|
}
|
|
24
29
|
|