@mupt-ai/dari-gateway 1.0.333 → 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/dist/link/endpoints.js
CHANGED
|
@@ -19,11 +19,23 @@
|
|
|
19
19
|
- GET /v1/link/grant the grant a link access token belongs to
|
|
20
20
|
- GET /v1/link/usage what the grant's requests used, by tag and time
|
|
21
21
|
- POST /v1/link/apps register an app (bearer: the user's key)
|
|
22
|
-
- GET /v1/link/grants the user's grants
|
|
22
|
+
- GET /v1/link/grants the user's grants, each granted plan and
|
|
23
|
+
key's spend this month with it
|
|
23
24
|
- DELETE /v1/link/grants/{id} the user revokes a grant and its tokens
|
|
24
25
|
- PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
|
|
25
26
|
budget: the most tokens the app may use per
|
|
26
27
|
five hours and per week
|
|
28
|
+
- PUT /v1/link/grants/{id}/limits the user sets the most the grant may
|
|
29
|
+
spend on each of its plans and keys a month
|
|
30
|
+
- GET /v1/link/plans the plans and keys the user can grant
|
|
31
|
+
- POST /v1/link/endpoints the user makes a personal endpoint: a grant
|
|
32
|
+
for themselves, and its key, which an app
|
|
33
|
+
that takes their own key calls with
|
|
34
|
+
- PUT /v1/link/grants/{id} rename an endpoint or change its plans
|
|
35
|
+
- POST /v1/link/grants/{id}/keys another key for an endpoint
|
|
36
|
+
|
|
37
|
+
The user's own routes take their personal key, or on hosted Dari their
|
|
38
|
+
signed-in session, as the bearer.
|
|
27
39
|
- GET /v1/link/session where a platform's sign-in returns the user
|
|
28
40
|
- GET /v1/link/connections the page where the approval page's user sees
|
|
29
41
|
the apps they connected, sets each one's
|
|
@@ -52,7 +64,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
52
64
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
53
65
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
54
66
|
import { gatewayFor } from "../models/gateways.js";
|
|
55
|
-
import { budgetBody, linkTokens, validBudget } from "./budget.js";
|
|
67
|
+
import { budgetBody, limitsBody, linkTokens, spendBody, validBudget, validLimits } from "./budget.js";
|
|
56
68
|
import { catalogModelFor } from "./grant_access.js";
|
|
57
69
|
import { requestTags } from "../runtime/request_tags.js";
|
|
58
70
|
import { parseJsonRequest } from "../ingress/json.js";
|
|
@@ -69,6 +81,9 @@ const MAX_REGISTRATION_BYTES = 8_192;
|
|
|
69
81
|
const MAX_REGISTRATIONS_PER_MINUTE = 20;
|
|
70
82
|
const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
|
|
71
83
|
const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
|
|
84
|
+
const GRANT_LIMITS_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/limits$/;
|
|
85
|
+
const GRANT_KEYS_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/keys$/;
|
|
86
|
+
const MAX_ENDPOINT_CREDENTIALS = 50;
|
|
72
87
|
const MAX_TAG_KEY_CHARS = 64;
|
|
73
88
|
// Who the approval page's user is. Without accounts the cookie is who they
|
|
74
89
|
// are, so it lasts a year from their last plan; with accounts, a month from
|
|
@@ -186,47 +201,154 @@ export async function handleLinkRequest(request, platform) {
|
|
|
186
201
|
if (pathname === "/v1/link/apps" && request.method === "POST") {
|
|
187
202
|
return await registerApp(link, request);
|
|
188
203
|
}
|
|
189
|
-
if (pathname
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
app_name: grant.appName,
|
|
196
|
-
credential_ids: grant.credentialIds,
|
|
197
|
-
created_at: grant.createdAt,
|
|
198
|
-
budget: budgetBody(grant.budget),
|
|
199
|
-
})),
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
const budgetRoute = GRANT_BUDGET_ROUTE.exec(pathname);
|
|
203
|
-
if (budgetRoute !== null && request.method === "PUT") {
|
|
204
|
-
const grantId = decodeURIComponent(budgetRoute[1]);
|
|
205
|
-
const body = await parseJsonRequest(request);
|
|
206
|
-
const budget = validBudget(body?.budget);
|
|
207
|
-
if (budget === null) {
|
|
208
|
-
throw new HttpError(400, "budget must be a list of {window_minutes, max_tokens} with distinct window_minutes of 300 or 10080 and max_tokens a positive whole number; [] removes it.", "invalid_request_error", "budget");
|
|
209
|
-
}
|
|
210
|
-
if (!(await link.setBudget({ apiKey: bearerToken(request.headers), grantId, budget }))) {
|
|
211
|
-
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
212
|
-
}
|
|
213
|
-
return Response.json({ id: grantId, budget: budgetBody(budget) });
|
|
214
|
-
}
|
|
215
|
-
const grantRoute = GRANT_ROUTE.exec(pathname);
|
|
216
|
-
if (grantRoute !== null && request.method === "DELETE") {
|
|
217
|
-
const grantId = decodeURIComponent(grantRoute[1]);
|
|
218
|
-
if (!(await link.revokeGrant({ apiKey: bearerToken(request.headers), grantId }))) {
|
|
219
|
-
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
220
|
-
}
|
|
221
|
-
return Response.json({ id: grantId, revoked: true });
|
|
204
|
+
if (isManagementPath(pathname)) {
|
|
205
|
+
if (request.method === "OPTIONS")
|
|
206
|
+
return withManagementCors(new Response(null, { status: 204 }));
|
|
207
|
+
const response = await manage(link, request, pathname);
|
|
208
|
+
if (response !== null)
|
|
209
|
+
return withManagementCors(response);
|
|
222
210
|
}
|
|
223
211
|
return errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
224
212
|
}
|
|
225
213
|
catch (error) {
|
|
226
214
|
const response = linkErrorResponse(error);
|
|
215
|
+
if (isManagementPath(pathname))
|
|
216
|
+
return withManagementCors(response);
|
|
227
217
|
return CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname) ? withCors(response) : response;
|
|
228
218
|
}
|
|
229
219
|
}
|
|
220
|
+
function isManagementPath(pathname) {
|
|
221
|
+
return pathname === "/v1/link/grants" || pathname === "/v1/link/plans" || pathname === "/v1/link/endpoints"
|
|
222
|
+
|| pathname.startsWith("/v1/link/grants/");
|
|
223
|
+
}
|
|
224
|
+
// The user's own routes are called from Dari's web app too, with a bearer
|
|
225
|
+
// token and no cookie, so any origin may call.
|
|
226
|
+
function withManagementCors(response) {
|
|
227
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
228
|
+
response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
229
|
+
response.headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
|
|
230
|
+
response.headers.set("Access-Control-Max-Age", "600");
|
|
231
|
+
return response;
|
|
232
|
+
}
|
|
233
|
+
function managedGrantBody(grant) {
|
|
234
|
+
return {
|
|
235
|
+
id: grant.id,
|
|
236
|
+
client_id: grant.clientId,
|
|
237
|
+
app_name: grant.appName,
|
|
238
|
+
endpoint: grant.endpoint,
|
|
239
|
+
credential_ids: grant.credentialIds,
|
|
240
|
+
created_at: grant.createdAt,
|
|
241
|
+
budget: budgetBody(grant.budget),
|
|
242
|
+
limits: limitsBody(grant.limits),
|
|
243
|
+
spend: spendBody(grant.spend),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
// A plan or key the user can grant, as the grant body names its plans.
|
|
247
|
+
function planBody(plan) {
|
|
248
|
+
const keyFor = plan.apiKeyProvider;
|
|
249
|
+
const kind = plan.provider;
|
|
250
|
+
const client = keyFor === undefined ? subscriptionClient(kind) : undefined;
|
|
251
|
+
return {
|
|
252
|
+
id: plan.id,
|
|
253
|
+
kind: keyFor === undefined ? kind : API_KEY,
|
|
254
|
+
title: keyFor === undefined ? KINDS[kind]?.name ?? kind : plan.name,
|
|
255
|
+
...(keyFor === undefined ? {} : { provider: keyFor }),
|
|
256
|
+
plan: keyFor === undefined ? SUBSCRIPTION_PLAN_LABELS[kind] ?? kind : `${plan.name} API Key`,
|
|
257
|
+
label: planLabel(plan),
|
|
258
|
+
account_email: plan.accountEmail,
|
|
259
|
+
serves: client === undefined ? "any_app" : `${client}_only`,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
// The credential ids a request names: distinct, and not too many.
|
|
263
|
+
function credentialIdsFrom(value) {
|
|
264
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > MAX_ENDPOINT_CREDENTIALS
|
|
265
|
+
|| !value.every((id) => typeof id === "string" && id.length > 0)) {
|
|
266
|
+
throw new HttpError(400, "credential_ids must list one or more of your plans and keys.", "invalid_request_error", "credential_ids");
|
|
267
|
+
}
|
|
268
|
+
return [...new Set(value)];
|
|
269
|
+
}
|
|
270
|
+
function limitsFrom(value) {
|
|
271
|
+
const limits = validLimits(value ?? []);
|
|
272
|
+
if (limits === null) {
|
|
273
|
+
throw new HttpError(400, "limits must be a list of {credential_id, monthly_usd} with distinct credential_ids and monthly_usd a dollar amount of 0 or more; [] removes them.", "invalid_request_error", "limits");
|
|
274
|
+
}
|
|
275
|
+
return limits;
|
|
276
|
+
}
|
|
277
|
+
/** The user's own routes; null for a path and method none of them serve. */
|
|
278
|
+
async function manage(link, request, pathname) {
|
|
279
|
+
const apiKey = bearerToken(request.headers);
|
|
280
|
+
if (pathname === "/v1/link/grants" && request.method === "GET") {
|
|
281
|
+
return Response.json({ grants: (await link.grants(apiKey)).map(managedGrantBody) });
|
|
282
|
+
}
|
|
283
|
+
if (pathname === "/v1/link/plans" && request.method === "GET") {
|
|
284
|
+
return Response.json({ plans: (await link.plans(apiKey)).map(planBody) });
|
|
285
|
+
}
|
|
286
|
+
if (pathname === "/v1/link/endpoints" && request.method === "POST") {
|
|
287
|
+
const body = (await parseJsonRequest(request));
|
|
288
|
+
const { grant, key } = await link.createEndpoint({
|
|
289
|
+
apiKey,
|
|
290
|
+
name: typeof body?.name === "string" ? body.name : "",
|
|
291
|
+
credentialIds: credentialIdsFrom(body?.credential_ids),
|
|
292
|
+
limits: limitsFrom(body?.limits),
|
|
293
|
+
});
|
|
294
|
+
return Response.json({ grant: managedGrantBody(grant), key }, { status: 201 });
|
|
295
|
+
}
|
|
296
|
+
const keysRoute = GRANT_KEYS_ROUTE.exec(pathname);
|
|
297
|
+
if (keysRoute !== null && request.method === "POST") {
|
|
298
|
+
const grantId = decodeURIComponent(keysRoute[1]);
|
|
299
|
+
const key = await link.issueEndpointKey({ apiKey, grantId });
|
|
300
|
+
if (key === null)
|
|
301
|
+
throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
302
|
+
return Response.json({ id: grantId, key }, { status: 201 });
|
|
303
|
+
}
|
|
304
|
+
const limitsRoute = GRANT_LIMITS_ROUTE.exec(pathname);
|
|
305
|
+
if (limitsRoute !== null && request.method === "PUT") {
|
|
306
|
+
const grantId = decodeURIComponent(limitsRoute[1]);
|
|
307
|
+
const limits = limitsFrom((await parseJsonRequest(request))?.limits);
|
|
308
|
+
if (!(await link.setLimits({ apiKey, grantId, limits }))) {
|
|
309
|
+
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
310
|
+
}
|
|
311
|
+
return Response.json({ id: grantId, limits: limitsBody(limits) });
|
|
312
|
+
}
|
|
313
|
+
const budgetRoute = GRANT_BUDGET_ROUTE.exec(pathname);
|
|
314
|
+
if (budgetRoute !== null && request.method === "PUT") {
|
|
315
|
+
const grantId = decodeURIComponent(budgetRoute[1]);
|
|
316
|
+
const body = await parseJsonRequest(request);
|
|
317
|
+
const budget = validBudget(body?.budget);
|
|
318
|
+
if (budget === null) {
|
|
319
|
+
throw new HttpError(400, "budget must be a list of {window_minutes, max_tokens} with distinct window_minutes of 300 or 10080 and max_tokens a positive whole number; [] removes it.", "invalid_request_error", "budget");
|
|
320
|
+
}
|
|
321
|
+
if (!(await link.setBudget({ apiKey, grantId, budget }))) {
|
|
322
|
+
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
323
|
+
}
|
|
324
|
+
return Response.json({ id: grantId, budget: budgetBody(budget) });
|
|
325
|
+
}
|
|
326
|
+
const grantRoute = GRANT_ROUTE.exec(pathname);
|
|
327
|
+
if (grantRoute !== null && request.method === "PUT") {
|
|
328
|
+
const grantId = decodeURIComponent(grantRoute[1]);
|
|
329
|
+
const body = (await parseJsonRequest(request));
|
|
330
|
+
const updated = await link.updateEndpoint({
|
|
331
|
+
apiKey,
|
|
332
|
+
grantId,
|
|
333
|
+
...(typeof body?.name === "string" ? { name: body.name } : {}),
|
|
334
|
+
...(body?.credential_ids === undefined ? {} : { credentialIds: credentialIdsFrom(body.credential_ids) }),
|
|
335
|
+
});
|
|
336
|
+
if (!updated)
|
|
337
|
+
throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
338
|
+
const grant = (await link.grants(apiKey)).find((candidate) => candidate.id === grantId);
|
|
339
|
+
if (grant === undefined)
|
|
340
|
+
throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
341
|
+
return Response.json(managedGrantBody(grant));
|
|
342
|
+
}
|
|
343
|
+
if (grantRoute !== null && request.method === "DELETE") {
|
|
344
|
+
const grantId = decodeURIComponent(grantRoute[1]);
|
|
345
|
+
if (!(await link.revokeGrant({ apiKey, grantId }))) {
|
|
346
|
+
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
347
|
+
}
|
|
348
|
+
return Response.json({ id: grantId, revoked: true });
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
230
352
|
// A refusal keeps its own message; a failure says nothing of its cause but a
|
|
231
353
|
// request id, which the log line carries with the detail.
|
|
232
354
|
function linkErrorResponse(error) {
|
|
@@ -1107,14 +1229,23 @@ function connectionCard(connection, csrf) {
|
|
|
1107
1229
|
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
1108
1230
|
<input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
|
|
1109
1231
|
${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
|
|
1232
|
+
};
|
|
1233
|
+
// The most the grant may spend on each plan or key a month.
|
|
1234
|
+
const spendLimit = (plan) => {
|
|
1235
|
+
const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
|
|
1236
|
+
const id = `usd_${escapeHtml(plan.id)}_${escapeHtml(connection.id)}`;
|
|
1237
|
+
return `<label class="field" for="${id}">${escapeHtml(planName(plan))} Per Month ($)</label>
|
|
1238
|
+
<input id="${id}" type="text" inputmode="decimal" name="usd_${escapeHtml(plan.id)}" value="${spend?.monthlyUsd ?? ""}" placeholder="No Limit" autocomplete="off">
|
|
1239
|
+
<p class="hint">${dollars(spend?.spentUsd ?? 0)} this month${spend?.reached ? ", at the limit until the month ends" : ""}</p>`;
|
|
1110
1240
|
};
|
|
1111
1241
|
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1112
1242
|
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1113
|
-
<strong>${escapeHtml(connection.appName)}</strong>
|
|
1243
|
+
<strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
|
|
1114
1244
|
<small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} · ${count(connection.usage.requests)} requests · ${count(tokens)} tokens</small>
|
|
1115
1245
|
<small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
|
|
1116
1246
|
${limit(300, "Per 5 Hours")}
|
|
1117
1247
|
${limit(10080, "Per Week")}
|
|
1248
|
+
${connection.subscriptions.map(spendLimit).join("\n")}
|
|
1118
1249
|
<div class="row"><button class="btn outline" type="submit" name="decision" value="budget">Save Limits</button><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
|
|
1119
1250
|
</form>`;
|
|
1120
1251
|
}
|
|
@@ -1146,7 +1277,16 @@ async function connectionsSubmit(approval, request, form) {
|
|
|
1146
1277
|
const budget = validBudget(entries);
|
|
1147
1278
|
if (budget === null)
|
|
1148
1279
|
return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1280
|
+
const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
|
|
1281
|
+
const value = raw.replace(/[\s,$]/g, "");
|
|
1282
|
+
if (!field.startsWith("usd_") || value === "")
|
|
1283
|
+
return [];
|
|
1284
|
+
return [{ credential_id: field.slice(4), monthly_usd: /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN }];
|
|
1285
|
+
}));
|
|
1286
|
+
if (limits === null)
|
|
1287
|
+
return await connectionsPage(approval, request, "Each monthly limit is a dollar amount; leave it empty for none.");
|
|
1149
1288
|
await approval.setBudget(session.subject, grantId, budget);
|
|
1289
|
+
await approval.setLimits(session.subject, grantId, limits);
|
|
1150
1290
|
return back;
|
|
1151
1291
|
}
|
|
1152
1292
|
const removing = form.get("remove_id");
|
|
@@ -1166,6 +1306,9 @@ async function connectionsSubmit(approval, request, form) {
|
|
|
1166
1306
|
await approval.remove(session.subject, plan.id);
|
|
1167
1307
|
return back;
|
|
1168
1308
|
}
|
|
1309
|
+
function dollars(value) {
|
|
1310
|
+
return `$${value.toFixed(2)}`;
|
|
1311
|
+
}
|
|
1169
1312
|
// What a plan or key is called: "Claude", or "OpenRouter API Key".
|
|
1170
1313
|
function planName(subscription) {
|
|
1171
1314
|
return subscription.apiKeyProvider !== undefined
|
package/dist/link/errors.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export declare function linkGrantRevoked(revokedBy: string | null, revokedAt: st
|
|
|
13
13
|
export declare function plansExhausted(plans: readonly SubscriptionKind[], resetsAt: Date | null): LinkUnavailable;
|
|
14
14
|
/** The grant used the most tokens the user allowed it in a window. */
|
|
15
15
|
export declare function budgetExhausted(resetsAt: Date): LinkUnavailable;
|
|
16
|
+
/** Every plan and key of the grant is at the monthly spend limit its user set. */
|
|
17
|
+
export declare function limitsReached(resetsAt: Date): LinkUnavailable;
|
|
16
18
|
/** The granted plans for a provider serve only another client. */
|
|
17
19
|
export declare function plansForAnotherClient(plans: readonly SubscriptionKind[]): LinkUnavailable;
|
|
18
20
|
/** A granted subscription, as a platform's resolve found it. */
|
package/dist/link/errors.js
CHANGED
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
their usage limits; `resets_at` (and Retry-After) says when the first one
|
|
14
14
|
is back, when that is known.
|
|
15
15
|
- `grant_budget_exhausted`: the grant used the most tokens the user
|
|
16
|
-
allowed it in a window (per five hours or per week)
|
|
17
|
-
|
|
16
|
+
allowed it in a window (per five hours or per week), or every plan and
|
|
17
|
+
key it shares is at its monthly spend limit; `resets_at` (and
|
|
18
|
+
Retry-After) says when it serves again.
|
|
18
19
|
- `subscription_client_mismatch`: the granted plans serve only another
|
|
19
20
|
client (a Claude Code plan serves only Claude Code itself); the user must
|
|
20
21
|
grant a plan that serves any app, such as a ChatGPT plan.
|
|
@@ -75,6 +76,14 @@ export function budgetExhausted(resetsAt) {
|
|
|
75
76
|
resets_at: resetsAt.toISOString(),
|
|
76
77
|
};
|
|
77
78
|
}
|
|
79
|
+
/** Every plan and key of the grant is at the monthly spend limit its user set. */
|
|
80
|
+
export function limitsReached(resetsAt) {
|
|
81
|
+
return {
|
|
82
|
+
code: "grant_budget_exhausted",
|
|
83
|
+
message: `Every plan and API key of this Dari Link grant is at the monthly spend limit the user set. It is back at ${resetsAt.toISOString()}.`,
|
|
84
|
+
resets_at: resetsAt.toISOString(),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
78
87
|
/** The granted plans for a provider serve only another client. */
|
|
79
88
|
export function plansForAnotherClient(plans) {
|
|
80
89
|
const only = [...new Set(plans.map((plan) => `${SUBSCRIPTION_PLAN_LABELS[plan]} plans serve only ${ONLY_CLIENT[plan] ?? "their own client"}`))];
|
package/dist/link/grants.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkApp, LinkBudget, LinkChildToken, LinkClient, LinkCodeExchange, LinkTokenExchange, LinkTokens, LinkUsage, LinkUsageQuery, LinkUsageTotals } from "../platform/platform.js";
|
|
1
|
+
import type { LinkApp, LinkBudget, LinkChildToken, LinkClient, LinkCodeExchange, LinkLimit, LinkTokenExchange, LinkTokens, LinkUsage, LinkUsageQuery, LinkUsageTotals } from "../platform/platform.js";
|
|
2
2
|
export declare const LINK_ACCESS_TOKEN_TTL_MS: number;
|
|
3
3
|
export declare const LINK_CODE_TTL_MS: number;
|
|
4
4
|
export declare const LINK_REFRESH_RACE_MS = 60000;
|
|
@@ -7,7 +7,7 @@ export declare const LINK_REFRESH_TOKEN_PREFIX = "dlk_rt_";
|
|
|
7
7
|
export declare const LINK_CODE_PREFIX = "dlk_code_";
|
|
8
8
|
export declare const LINK_CLIENT_SECRET_PREFIX = "dlk_cs_";
|
|
9
9
|
export type LinkRevoker = "user" | "app" | "reuse_detected";
|
|
10
|
-
export type LinkTokenKind = "access" | "refresh" | "child";
|
|
10
|
+
export type LinkTokenKind = "access" | "refresh" | "child" | "key";
|
|
11
11
|
export type LinkPin = {
|
|
12
12
|
model: string;
|
|
13
13
|
thinking: string | null;
|
|
@@ -17,6 +17,7 @@ export type ActiveLinkGrant = {
|
|
|
17
17
|
clientId: string;
|
|
18
18
|
credentialIds: ReadonlySet<string>;
|
|
19
19
|
budget: LinkBudget[];
|
|
20
|
+
limits: LinkLimit[];
|
|
20
21
|
pins?: LinkPin[];
|
|
21
22
|
tags?: Record<string, string>;
|
|
22
23
|
};
|
|
@@ -46,6 +47,7 @@ export type LinkTokenRecord = {
|
|
|
46
47
|
clientId: string;
|
|
47
48
|
credentialIds: string[];
|
|
48
49
|
budget: LinkBudget[];
|
|
50
|
+
limits: LinkLimit[];
|
|
49
51
|
revokedAt: number | null;
|
|
50
52
|
revokedBy: string | null;
|
|
51
53
|
usable: boolean;
|
|
@@ -140,9 +142,8 @@ export declare function linkGrants(repo: LinkRepo): {
|
|
|
140
142
|
usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Promise<Omit<LinkUsage, "completeThrough">>;
|
|
141
143
|
};
|
|
142
144
|
export type LinkGrants = ReturnType<typeof linkGrants>;
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
/** What a stored access or child token is now; null when it serves nothing. */
|
|
145
|
+
export declare const TOKEN_PREFIX: Record<LinkTokenKind, string>;
|
|
146
|
+
/** What a stored access, child, or key token is now; null when it serves nothing. */
|
|
146
147
|
export declare function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null;
|
|
147
148
|
/** Totals of a grant's requests carrying every given tag, by model and optionally by one tag's values. */
|
|
148
149
|
export declare function summarizeLinkUsage(records: readonly LinkUsageRecord[], tags: Record<string, string>, groupByTag?: string): Omit<LinkUsage, "completeThrough">;
|
package/dist/link/grants.js
CHANGED
|
@@ -11,13 +11,15 @@
|
|
|
11
11
|
race, and later reuse revokes the grant. A confidential client, which
|
|
12
12
|
also proves its secret, keeps its own;
|
|
13
13
|
- a child token serves only its models, for up to twelve hours, and cannot
|
|
14
|
-
refresh, mint, or read the grant
|
|
14
|
+
refresh, mint, or read the grant;
|
|
15
|
+
- a personal endpoint's key does not expire: it is what a user pastes into
|
|
16
|
+
an app that takes their own key, and acts as the grant's access token.
|
|
15
17
|
|
|
16
18
|
Revoking the grant stops them all at once. */
|
|
17
19
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
20
|
import { HttpError } from "../http/errors.js";
|
|
19
21
|
import { linkGrantRevoked, linkTokenExpired } from "./errors.js";
|
|
20
|
-
import { LINK_ACCESS_TOKEN_PREFIX, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
|
|
22
|
+
import { LINK_ACCESS_TOKEN_PREFIX, LINK_CHILD_TOKEN_PREFIX, LINK_KEY_TOKEN_PREFIX, isLinkToken, } from "../protocol/input/router_model.js";
|
|
21
23
|
export const LINK_ACCESS_TOKEN_TTL_MS = 60 * 60_000;
|
|
22
24
|
export const LINK_CODE_TTL_MS = 10 * 60_000;
|
|
23
25
|
// A rotated refresh token presented again this soon lost a race with its own
|
|
@@ -171,24 +173,23 @@ export function linkGrants(repo) {
|
|
|
171
173
|
},
|
|
172
174
|
};
|
|
173
175
|
}
|
|
174
|
-
const TOKEN_PREFIX = {
|
|
176
|
+
export const TOKEN_PREFIX = {
|
|
175
177
|
access: LINK_ACCESS_TOKEN_PREFIX,
|
|
176
178
|
child: LINK_CHILD_TOKEN_PREFIX,
|
|
179
|
+
key: LINK_KEY_TOKEN_PREFIX,
|
|
177
180
|
refresh: LINK_REFRESH_TOKEN_PREFIX,
|
|
178
181
|
};
|
|
179
|
-
/**
|
|
180
|
-
export function isLinkToken(token) {
|
|
181
|
-
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX) || token.startsWith(LINK_CHILD_TOKEN_PREFIX);
|
|
182
|
-
}
|
|
183
|
-
/** What a stored access or child token is now; null when it serves nothing. */
|
|
182
|
+
/** What a stored access, child, or key token is now; null when it serves nothing. */
|
|
184
183
|
export function linkTokenAuth(record, now) {
|
|
185
184
|
if (record === null || record.kind === "refresh")
|
|
186
185
|
return null;
|
|
187
186
|
if (record.revokedAt !== null) {
|
|
188
187
|
return { status: "revoked", revokedBy: record.revokedBy, revokedAt: new Date(record.revokedAt).toISOString() };
|
|
189
188
|
}
|
|
190
|
-
|
|
189
|
+
// An endpoint's key never expires; every other token does.
|
|
190
|
+
if (record.kind !== "key" && (record.expiresAt === null || record.expiresAt <= now.getTime())) {
|
|
191
191
|
return { status: "expired" };
|
|
192
|
+
}
|
|
192
193
|
if (!record.usable)
|
|
193
194
|
return null;
|
|
194
195
|
const pins = record.kind === "child" ? record.pins ?? [] : undefined;
|
|
@@ -202,6 +203,7 @@ export function linkTokenAuth(record, now) {
|
|
|
202
203
|
clientId: record.clientId,
|
|
203
204
|
credentialIds: new Set(record.credentialIds),
|
|
204
205
|
budget: record.budget,
|
|
206
|
+
limits: record.limits,
|
|
205
207
|
...(pins === undefined ? {} : { pins }),
|
|
206
208
|
...(record.tags === null ? {} : { tags: record.tags }),
|
|
207
209
|
},
|
package/dist/link/service.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkPlanAdded, LinkPlatform, LinkSignIn, LinkSubscription } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkLimit, LinkPlanAdded, LinkPlatform, LinkSignIn, LinkSubscription } from "../platform/platform.js";
|
|
2
2
|
import type { SubscriptionKind } from "../types.js";
|
|
3
3
|
import { type BudgetUse } from "./budget.js";
|
|
4
|
-
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo } from "./grants.js";
|
|
4
|
+
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo, type LinkTokenIssue } from "./grants.js";
|
|
5
|
+
/** The built-in app every personal endpoint's grant belongs to. */
|
|
6
|
+
export declare const LINK_PERSONAL_CLIENT_ID = "lnk_personal";
|
|
5
7
|
type MaybePromise<T> = T | Promise<T>;
|
|
6
8
|
/** A live grant as stored. */
|
|
7
9
|
export type LinkGrantRecord = {
|
|
@@ -12,6 +14,7 @@ export type LinkGrantRecord = {
|
|
|
12
14
|
credentialIds: string[];
|
|
13
15
|
createdAt: string;
|
|
14
16
|
budget: LinkBudget[];
|
|
17
|
+
limits: LinkLimit[];
|
|
15
18
|
};
|
|
16
19
|
/** Storage for Dari Link: the token protocol's steps, and grants. */
|
|
17
20
|
export type LinkStore = LinkRepo & {
|
|
@@ -36,12 +39,29 @@ export type LinkStore = LinkRepo & {
|
|
|
36
39
|
budget: LinkBudget[];
|
|
37
40
|
now: number;
|
|
38
41
|
}): MaybePromise<string | null>;
|
|
39
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Store a personal endpoint: a grant of `LINK_PERSONAL_CLIENT_ID` named
|
|
44
|
+
* `name`, live at once, with its key token, in one step. Its id.
|
|
45
|
+
*/
|
|
46
|
+
createEndpoint(request: {
|
|
47
|
+
subject: string;
|
|
48
|
+
name: string;
|
|
49
|
+
credentialIds: string[];
|
|
50
|
+
limits: LinkLimit[];
|
|
51
|
+
key: LinkTokenIssue;
|
|
52
|
+
now: number;
|
|
53
|
+
}): MaybePromise<string>;
|
|
54
|
+
/**
|
|
55
|
+
* Change a live grant's plans, budget, or limits, or an endpoint's name;
|
|
56
|
+
* false when none is live by that id.
|
|
57
|
+
*/
|
|
40
58
|
updateGrant(grantId: string, change: {
|
|
41
59
|
credentialIds?: string[];
|
|
42
60
|
budget?: LinkBudget[];
|
|
61
|
+
limits?: LinkLimit[];
|
|
62
|
+
name?: string;
|
|
43
63
|
}): MaybePromise<boolean>;
|
|
44
|
-
/**
|
|
64
|
+
/** What each of a grant's requests received after `since` used and cost. */
|
|
45
65
|
budgetUses(grantId: string, since: number): MaybePromise<BudgetUse[]>;
|
|
46
66
|
};
|
|
47
67
|
/** A platform's users: who a key is, and where their plans and keys live. */
|
|
@@ -104,8 +124,9 @@ export declare function newLinkClientSecret(): {
|
|
|
104
124
|
};
|
|
105
125
|
/**
|
|
106
126
|
* The grant a link token serves a request for: null when the key is no link
|
|
107
|
-
* token.
|
|
108
|
-
* gets
|
|
127
|
+
* token. Its plans and keys at their monthly spend limit are left out. Throws
|
|
128
|
+
* the 401 a dead token gets, and the 424 a grant at its budget, or with every
|
|
129
|
+
* plan and key at its limit, gets until it serves again.
|
|
109
130
|
*/
|
|
110
131
|
export declare function linkTokenGrant(store: LinkStore, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
|
|
111
132
|
export {};
|