@mupt-ai/dari-gateway 1.0.321 → 1.0.323
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/README.md +1 -1
- package/dist/ingress/anthropic_messages.js +13 -7
- package/dist/ingress/codex.js +9 -4
- package/dist/link/budget.d.ts +6 -3
- package/dist/link/budget.js +6 -2
- package/dist/link/endpoints.d.ts +14 -1
- package/dist/link/endpoints.js +120 -36
- package/dist/link/errors.d.ts +20 -1
- package/dist/link/errors.js +35 -0
- package/dist/link/grants.d.ts +3 -1
- package/dist/link/grants.js +3 -0
- package/dist/link/key_providers.d.ts +2 -0
- package/dist/link/key_providers.js +4 -0
- package/dist/link/self_hosted.js +2 -2
- package/dist/link/service.d.ts +21 -1
- package/dist/link/service.js +25 -8
- package/dist/link/sqlite_store.d.ts +1 -0
- package/dist/link/sqlite_store.js +12 -11
- package/dist/platform/platform.d.ts +25 -4
- package/dist/runtime/harness_identity/extract.js +6 -1
- package/dist/self_host/resolve.js +6 -32
- package/package.json +2 -2
- package/src/ingress/anthropic_messages.ts +13 -6
- package/src/ingress/codex.ts +8 -2
- package/src/link/budget.ts +12 -4
- package/src/link/endpoints.ts +130 -39
- package/src/link/errors.ts +53 -1
- package/src/link/grants.ts +6 -1
- package/src/link/key_providers.ts +5 -0
- package/src/link/self_hosted.ts +2 -2
- package/src/link/service.ts +33 -9
- package/src/link/sqlite_store.ts +27 -19
- package/src/platform/platform.ts +22 -4
- package/src/runtime/harness_identity/extract.ts +6 -1
- package/src/self_host/resolve.ts +10 -47
package/src/link/endpoints.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
- PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
|
|
25
25
|
budget: the most tokens the app may use per
|
|
26
26
|
five hours and per week
|
|
27
|
+
- GET /v1/link/session where a platform's sign-in returns the user
|
|
27
28
|
- GET /v1/link/connections the page where the approval page's user sees
|
|
28
29
|
the apps they connected, sets each one's
|
|
29
30
|
budget, disconnects it, and removes plans
|
|
@@ -33,15 +34,16 @@
|
|
|
33
34
|
with HTTP Basic (`client_id:client_secret`); a public one sends `client_id`
|
|
34
35
|
in the body.
|
|
35
36
|
|
|
36
|
-
The
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
it, so another site cannot
|
|
37
|
+
The user picks a plan, signs in to its provider, and allows the app. The
|
|
38
|
+
gateway keeps who they are in a signed, HttpOnly, SameSite=Lax cookie
|
|
39
|
+
scoped to /v1/link/, so the next app that asks finds their plans connected
|
|
40
|
+
and the connections page knows them. On a platform with accounts (hosted:
|
|
41
|
+
Dari's own sign-in) they sign in first and are that account, with the plans
|
|
42
|
+
it already has; elsewhere their first plan makes them a user. Every change
|
|
43
|
+
needs that cookie and a form token derived from it, so another site cannot
|
|
44
|
+
make one. */
|
|
43
45
|
|
|
44
|
-
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
46
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
45
47
|
|
|
46
48
|
import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
47
49
|
|
|
@@ -61,6 +63,7 @@ import type {
|
|
|
61
63
|
LinkKeyProvider,
|
|
62
64
|
LinkUsageTotals,
|
|
63
65
|
LinkPlatform,
|
|
66
|
+
LinkSignIn,
|
|
64
67
|
LinkBudget,
|
|
65
68
|
LinkBudgetStanding,
|
|
66
69
|
LinkSubscription,
|
|
@@ -70,7 +73,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
70
73
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
71
74
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
72
75
|
import { gatewayFor } from "../models/gateways.js";
|
|
73
|
-
import { budgetBody, validBudget } from "./budget.js";
|
|
76
|
+
import { budgetBody, linkTokens, validBudget } from "./budget.js";
|
|
74
77
|
import { catalogModelFor } from "./grant_access.js";
|
|
75
78
|
import { requestTags } from "../runtime/request_tags.js";
|
|
76
79
|
import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
@@ -90,12 +93,21 @@ const MAX_REGISTRATIONS_PER_MINUTE = 20;
|
|
|
90
93
|
const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
|
|
91
94
|
const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
|
|
92
95
|
const MAX_TAG_KEY_CHARS = 64;
|
|
93
|
-
// Who the approval page's user is
|
|
96
|
+
// Who the approval page's user is. Without accounts the cookie is who they
|
|
97
|
+
// are, so it lasts a year from their last plan; with accounts, a month from
|
|
98
|
+
// their sign-in, which is a click away again.
|
|
94
99
|
const USER_COOKIE = "dari_link_user";
|
|
95
100
|
const USER_SECONDS = 365 * 24 * 60 * 60;
|
|
101
|
+
const ACCOUNT_SECONDS = 30 * 24 * 60 * 60;
|
|
96
102
|
// A provider sign-in under way, for as long as providers keep one open.
|
|
97
103
|
const CONNECT_COOKIE = "dari_link_connect";
|
|
98
104
|
const CONNECT_SECONDS = 15 * 60;
|
|
105
|
+
// A sign-in at the platform under way: the state its ticket must carry.
|
|
106
|
+
const SIGN_IN_COOKIE = "dari_link_sign_in";
|
|
107
|
+
const SIGN_IN_SECONDS = 15 * 60;
|
|
108
|
+
// How long after the platform signed the user in its ticket is good.
|
|
109
|
+
const TICKET_MS = 2 * 60 * 1000;
|
|
110
|
+
const SESSION_PATH = "/v1/link/session";
|
|
99
111
|
// How often the page asks a provider whether the user approved its code.
|
|
100
112
|
const DEVICE_POLL_SECONDS = 5;
|
|
101
113
|
const AUTHORIZE_PATH = "/v1/link/authorize";
|
|
@@ -169,6 +181,9 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
|
|
|
169
181
|
if (pathname === AUTHORIZE_PATH && request.method === "POST") {
|
|
170
182
|
return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
|
|
171
183
|
}
|
|
184
|
+
if (pathname === SESSION_PATH && request.method === "GET") {
|
|
185
|
+
return await signedIn(link.approval, request, url.searchParams);
|
|
186
|
+
}
|
|
172
187
|
if (pathname === CONNECTIONS_PATH && request.method === "GET") {
|
|
173
188
|
return await connectionsPage(link.approval, request);
|
|
174
189
|
}
|
|
@@ -315,14 +330,7 @@ function isHttps(request: Request): boolean {
|
|
|
315
330
|
|
|
316
331
|
async function registerApp(link: LinkPlatform, request: Request): Promise<Response> {
|
|
317
332
|
const apiKey = bearerToken(request.headers);
|
|
318
|
-
const
|
|
319
|
-
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
320
|
-
throw new HttpError(400, message, "invalid_request_error", param);
|
|
321
|
-
});
|
|
322
|
-
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
323
|
-
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
324
|
-
}
|
|
325
|
-
const app = await link.registerApp({ apiKey, name, redirectUris, confidential: body.confidential === true });
|
|
333
|
+
const app = await link.registerApp({ apiKey, ...linkAppMetadata(link, await parseJsonRequest(request)) });
|
|
326
334
|
return Response.json(
|
|
327
335
|
// The secret is shown this once; only its hash is stored.
|
|
328
336
|
{ ...appBody(app), ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret }) },
|
|
@@ -416,8 +424,25 @@ function registrationError(error: string, description: string): Response {
|
|
|
416
424
|
return Response.json({ error, error_description: description }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
|
417
425
|
}
|
|
418
426
|
|
|
427
|
+
/**
|
|
428
|
+
* An app's name, redirect URIs, and whether it is confidential, as every
|
|
429
|
+
* registration takes them; HttpError(400) for anything else.
|
|
430
|
+
*/
|
|
431
|
+
export function linkAppMetadata(
|
|
432
|
+
link: Pick<LinkPlatform, "httpRedirectHosts">,
|
|
433
|
+
body: { name?: unknown; redirect_uris?: unknown; confidential?: unknown },
|
|
434
|
+
): { name: string; redirectUris: string[]; confidential: boolean } {
|
|
435
|
+
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
436
|
+
throw new HttpError(400, message, "invalid_request_error", param);
|
|
437
|
+
});
|
|
438
|
+
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
439
|
+
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
440
|
+
}
|
|
441
|
+
return { name, redirectUris, confidential: body.confidential === true };
|
|
442
|
+
}
|
|
443
|
+
|
|
419
444
|
function validClient(
|
|
420
|
-
link: LinkPlatform,
|
|
445
|
+
link: Pick<LinkPlatform, "httpRedirectHosts">,
|
|
421
446
|
rawName: unknown,
|
|
422
447
|
rawRedirectUris: unknown,
|
|
423
448
|
refuse: (message: string, param: string) => never,
|
|
@@ -1008,8 +1033,9 @@ async function authorizePage(link: LinkPlatform, request: Request, params: URLSe
|
|
|
1008
1033
|
if (authorize instanceof Response) return authorize;
|
|
1009
1034
|
const approval = link.approval;
|
|
1010
1035
|
const secret = approval.sessionSecret();
|
|
1011
|
-
const session = sessionFrom(request,
|
|
1012
|
-
|
|
1036
|
+
const session = sessionFrom(request, approval);
|
|
1037
|
+
// On a platform with accounts, only a signed-in user has a provider sign-in under way.
|
|
1038
|
+
const connect = session === null && approval.signIn !== undefined ? null : connectFrom(request, secret);
|
|
1013
1039
|
if (connect !== null) {
|
|
1014
1040
|
// A provider that gave the user a code to enter is asked whether they approved.
|
|
1015
1041
|
return connect.userCode === null
|
|
@@ -1058,7 +1084,10 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1058
1084
|
if (authorize instanceof Response) return authorize;
|
|
1059
1085
|
const back = { redirectUri: authorize.redirectUri, state: authorize.state, webMessage: authorize.webMessage };
|
|
1060
1086
|
const secret = approval.sessionSecret();
|
|
1061
|
-
const session = sessionFrom(request,
|
|
1087
|
+
const session = sessionFrom(request, approval);
|
|
1088
|
+
if (session === null && approval.signIn !== undefined && !["deny", "sign_out"].includes(form.get("decision") ?? "")) {
|
|
1089
|
+
return signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
|
|
1090
|
+
}
|
|
1062
1091
|
const endConnect = clearCookie(request, CONNECT_COOKIE);
|
|
1063
1092
|
// A plan's or a key provider's row on the select page is its own submit button.
|
|
1064
1093
|
const kind = form.get("connect");
|
|
@@ -1070,6 +1099,7 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1070
1099
|
}
|
|
1071
1100
|
const decision = kind !== null ? "connect" : form.get("decision");
|
|
1072
1101
|
if (decision === "deny") return redirect(back, { error: "access_denied" }, [endConnect]);
|
|
1102
|
+
if (decision === "sign_out") return seeAuthorize(authorize, signOutCookies(request));
|
|
1073
1103
|
if (decision === "select") return selectPage(approval, authorize, undefined, [endConnect]);
|
|
1074
1104
|
if (decision === "connect") {
|
|
1075
1105
|
if (!connectKinds(approval, authorize).includes(kind as SubscriptionKind)) {
|
|
@@ -1106,7 +1136,7 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1106
1136
|
if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "link_not_configured")) throw error;
|
|
1107
1137
|
return keyPage(authorize, keyProvider, error.message);
|
|
1108
1138
|
}
|
|
1109
|
-
return seeAuthorize(authorize, [userCookie(request,
|
|
1139
|
+
return seeAuthorize(authorize, [userCookie(request, approval, added.subject), endConnect]);
|
|
1110
1140
|
}
|
|
1111
1141
|
const connect = connectFrom(request, secret);
|
|
1112
1142
|
if (decision === "complete" && connect !== null) {
|
|
@@ -1178,7 +1208,7 @@ async function finishConnect(
|
|
|
1178
1208
|
}
|
|
1179
1209
|
return connected === null
|
|
1180
1210
|
? providerPage(authorize, connect)
|
|
1181
|
-
: seeAuthorize(authorize, [userCookie(request, approval
|
|
1211
|
+
: seeAuthorize(authorize, [userCookie(request, approval, connected.subject), endConnect]);
|
|
1182
1212
|
}
|
|
1183
1213
|
|
|
1184
1214
|
/**
|
|
@@ -1187,10 +1217,13 @@ async function finishConnect(
|
|
|
1187
1217
|
* and keys, each of which they can remove.
|
|
1188
1218
|
*/
|
|
1189
1219
|
async function connectionsPage(approval: LinkApprovalPage, request: Request, error?: string): Promise<Response> {
|
|
1190
|
-
const session = sessionFrom(request, approval
|
|
1220
|
+
const session = sessionFrom(request, approval);
|
|
1191
1221
|
const title = "Connected Apps";
|
|
1192
1222
|
if (session === null) {
|
|
1193
|
-
return
|
|
1223
|
+
return approval.signIn === undefined
|
|
1224
|
+
? page(title, `<div class="body"><h1>${title}</h1><p>No apps are connected in this browser. Apps that use Dari Link connect from their own Connect button.</p></div>`)
|
|
1225
|
+
: page(title, `<form method="post" action="${CONNECTIONS_PATH}"><div class="body"><h1>${title}</h1><p>Sign in to see the apps you connected.</p></div>
|
|
1226
|
+
<div class="foot"><button class="btn primary" type="submit" name="decision" value="sign_in">Sign In</button></div></form>`);
|
|
1194
1227
|
}
|
|
1195
1228
|
const [connections, plans] = await Promise.all([
|
|
1196
1229
|
approval.connections(session.subject),
|
|
@@ -1207,13 +1240,13 @@ async function connectionsPage(approval: LinkApprovalPage, request: Request, err
|
|
|
1207
1240
|
${error === undefined ? "" : `<p role="alert">${escapeHtml(error)}</p>`}
|
|
1208
1241
|
${cards.length === 0 ? "<p>No apps are connected.</p>" : cards.join("\n")}
|
|
1209
1242
|
${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${planRows.join("\n")}`}
|
|
1243
|
+
${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${SIGN_OUT}</form>` : ""}
|
|
1210
1244
|
</div>`,
|
|
1211
1245
|
);
|
|
1212
1246
|
}
|
|
1213
1247
|
|
|
1214
1248
|
function connectionCard(connection: LinkConnection, csrf: string): string {
|
|
1215
|
-
const tokens = connection.usage
|
|
1216
|
-
+ connection.usage.cacheReadTokens + connection.usage.cacheWriteTokens;
|
|
1249
|
+
const tokens = linkTokens(connection.usage);
|
|
1217
1250
|
const limit = (minutes: number, label: string) => {
|
|
1218
1251
|
const standing = connection.budget.find((window) => window.windowMinutes === minutes);
|
|
1219
1252
|
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
@@ -1235,10 +1268,19 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
|
|
|
1235
1268
|
if (crossSite(request)) {
|
|
1236
1269
|
return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open the connections page again.</p></div>`, { status: 403 });
|
|
1237
1270
|
}
|
|
1238
|
-
const
|
|
1271
|
+
const secret = approval.sessionSecret();
|
|
1272
|
+
const session = sessionFrom(request, approval);
|
|
1273
|
+
if (session === null && approval.signIn !== undefined && form.get("decision") === "sign_in") {
|
|
1274
|
+
return signIn(request, approval.signIn, secret, CONNECTIONS_PATH);
|
|
1275
|
+
}
|
|
1239
1276
|
const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
|
|
1240
1277
|
if (session === null || !sameText(form.get("csrf") ?? "", session.csrf)) return back;
|
|
1241
1278
|
const decision = form.get("decision");
|
|
1279
|
+
if (decision === "sign_out") {
|
|
1280
|
+
const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
|
|
1281
|
+
for (const cookie of signOutCookies(request)) headers.append("Set-Cookie", cookie);
|
|
1282
|
+
return new Response(null, { status: 303, headers });
|
|
1283
|
+
}
|
|
1242
1284
|
const grantId = form.get("grant_id") ?? "";
|
|
1243
1285
|
if (decision === "disconnect") {
|
|
1244
1286
|
await approval.disconnect(session.subject, grantId);
|
|
@@ -1321,12 +1363,18 @@ function shareable(authorize: AuthorizeRequest, subscriptions: LinkSubscription[
|
|
|
1321
1363
|
}
|
|
1322
1364
|
|
|
1323
1365
|
// The user the cookie remembers, and the form token that ties an approval to
|
|
1324
|
-
// them; another site has neither.
|
|
1325
|
-
|
|
1366
|
+
// them; another site has neither. `account`: they signed in to the platform's
|
|
1367
|
+
// account, so they can sign out (as on a shared computer).
|
|
1368
|
+
type Session = { subject: string; csrf: string; account: boolean };
|
|
1326
1369
|
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1370
|
+
const SIGN_OUT = `<button class="btn ghost" type="submit" name="decision" value="sign_out" formnovalidate>Sign Out</button>`;
|
|
1371
|
+
|
|
1372
|
+
function sessionFrom(request: Request, approval: LinkApprovalPage): Session | null {
|
|
1373
|
+
const secret = approval.sessionSecret();
|
|
1374
|
+
const user = readSigned(request, secret, USER_COOKIE);
|
|
1375
|
+
// A platform with accounts knows only users its sign-in made.
|
|
1376
|
+
if (typeof user?.sub !== "string" || (approval.signIn !== undefined && user.account !== true)) return null;
|
|
1377
|
+
return { subject: user.sub, csrf: sign(secret, `csrf\0${user.sub}`), account: approval.signIn !== undefined };
|
|
1330
1378
|
}
|
|
1331
1379
|
|
|
1332
1380
|
// A provider sign-in under way.
|
|
@@ -1348,6 +1396,39 @@ function connectFrom(request: Request, secret: string): Connect | null {
|
|
|
1348
1396
|
};
|
|
1349
1397
|
}
|
|
1350
1398
|
|
|
1399
|
+
// Send the user to the platform's sign-in, which returns them to `next` (a
|
|
1400
|
+
// page of this gateway's) by way of /v1/link/session. The state, kept in a
|
|
1401
|
+
// cookie here, binds the ticket that comes back to this browser, so no one
|
|
1402
|
+
// can sign a user in as someone else.
|
|
1403
|
+
function signIn(request: Request, platform: LinkSignIn, secret: string, next: string): Response {
|
|
1404
|
+
const state = randomBytes(24).toString("base64url");
|
|
1405
|
+
const url = new URL(platform.url());
|
|
1406
|
+
url.searchParams.set("state", state);
|
|
1407
|
+
url.searchParams.set("next", next);
|
|
1408
|
+
const headers = new Headers({ Location: url.toString(), "Cache-Control": "no-store" });
|
|
1409
|
+
headers.append("Set-Cookie", signedCookie(request, secret, SIGN_IN_COOKIE, { state }, SIGN_IN_SECONDS));
|
|
1410
|
+
return new Response(null, { status: 303, headers });
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
// The platform's sign-in returns here: a fresh ticket for this browser's state
|
|
1414
|
+
// makes the browser that user's, and the user goes on to `next`.
|
|
1415
|
+
async function signedIn(approval: LinkApprovalPage, request: Request, params: URLSearchParams): Promise<Response> {
|
|
1416
|
+
const secret = approval.sessionSecret();
|
|
1417
|
+
const state = readSigned(request, secret, SIGN_IN_COOKIE)?.state;
|
|
1418
|
+
const next = params.get("next") ?? "";
|
|
1419
|
+
const ticket = params.get("ticket") ?? "";
|
|
1420
|
+
const signed = approval.signIn === undefined || typeof state !== "string" || !ticket || !next.startsWith(LINK_ROUTE_PREFIX)
|
|
1421
|
+
? null
|
|
1422
|
+
: await approval.signIn.redeem(ticket);
|
|
1423
|
+
if (signed === null || signed.state !== state || Date.now() - signed.issuedAt > TICKET_MS) {
|
|
1424
|
+
return page("Sign-In Expired", `<div class="body"><h1>Sign-In Expired</h1><p>Open Dari Link from the app again.</p></div>`, { status: 400 });
|
|
1425
|
+
}
|
|
1426
|
+
const headers = new Headers({ Location: next, "Cache-Control": "no-store" });
|
|
1427
|
+
headers.append("Set-Cookie", userCookie(request, approval, signed.subject));
|
|
1428
|
+
headers.append("Set-Cookie", clearCookie(request, SIGN_IN_COOKIE));
|
|
1429
|
+
return new Response(null, { status: 303, headers });
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1351
1432
|
// A signed cookie's payload: `<payload>.<HMAC-SHA256>`, where the payload
|
|
1352
1433
|
// holds the value and when it ends.
|
|
1353
1434
|
function readSigned(request: Request, secret: string, cookie: string): Record<string, unknown> | null {
|
|
@@ -1377,9 +1458,16 @@ function signedCookie(request: Request, secret: string, cookie: string, value: R
|
|
|
1377
1458
|
return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${COOKIE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
1378
1459
|
}
|
|
1379
1460
|
|
|
1380
|
-
// Who the user is,
|
|
1381
|
-
function userCookie(request: Request,
|
|
1382
|
-
return
|
|
1461
|
+
// Who the user is, from when the page last said so (see USER_COOKIE).
|
|
1462
|
+
function userCookie(request: Request, approval: LinkApprovalPage, subject: string): string {
|
|
1463
|
+
return approval.signIn === undefined
|
|
1464
|
+
? signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject }, USER_SECONDS)
|
|
1465
|
+
: signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
|
|
1469
|
+
function signOutCookies(request: Request): string[] {
|
|
1470
|
+
return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
|
|
1383
1471
|
}
|
|
1384
1472
|
|
|
1385
1473
|
function clearCookie(request: Request, cookie: string): string {
|
|
@@ -1583,7 +1671,8 @@ function choosePage(
|
|
|
1583
1671
|
body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
|
|
1584
1672
|
<input type="hidden" name="csrf" value="${session.csrf}">
|
|
1585
1673
|
${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
|
|
1586
|
-
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button
|
|
1674
|
+
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
|
|
1675
|
+
${session.account ? SIGN_OUT : ""}`,
|
|
1587
1676
|
footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
|
|
1588
1677
|
<p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
|
|
1589
1678
|
});
|
|
@@ -1722,7 +1811,9 @@ ${body}
|
|
|
1722
1811
|
"Cache-Control": "no-store",
|
|
1723
1812
|
"Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
|
|
1724
1813
|
"X-Frame-Options": "DENY",
|
|
1725
|
-
|
|
1814
|
+
// No other site sees these pages' URLs. Not no-referrer: under it a form
|
|
1815
|
+
// posts Origin: null, which an http gateway (sent no Sec-Fetch-Site) refuses.
|
|
1816
|
+
"Referrer-Policy": "same-origin",
|
|
1726
1817
|
});
|
|
1727
1818
|
for (const cookie of options.cookies ?? []) headers.append("Set-Cookie", cookie);
|
|
1728
1819
|
return new Response(html, { status: options.status ?? 200, headers });
|
package/src/link/errors.ts
CHANGED
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
25
25
|
|
|
26
26
|
import { HttpError } from "../http/errors.js";
|
|
27
|
-
import
|
|
27
|
+
import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
28
|
+
import type { ClientHarness, LinkUnavailable, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
28
29
|
|
|
29
30
|
export const LINK_GRANT_ERROR_CODES = [
|
|
30
31
|
"subscription_exhausted",
|
|
@@ -100,6 +101,57 @@ export function plansForAnotherClient(plans: readonly SubscriptionKind[]): LinkU
|
|
|
100
101
|
};
|
|
101
102
|
}
|
|
102
103
|
|
|
104
|
+
/** A granted subscription, as a platform's resolve found it. */
|
|
105
|
+
export type LinkGrantedPlan = { kind: SubscriptionKind; unavailableUntil: Date | null };
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Why a grant serves nothing for each provider in `unserved` (the request
|
|
109
|
+
* wanted it, the grant holds a plan for it, and no plan served): its plans
|
|
110
|
+
* serve only another client, or are all at their usage limits. Every
|
|
111
|
+
* platform's resolve says it this way.
|
|
112
|
+
*/
|
|
113
|
+
export function providersUnavailable(
|
|
114
|
+
granted: readonly LinkGrantedPlan[],
|
|
115
|
+
unserved: Iterable<string>,
|
|
116
|
+
clientHarness: ClientHarness | undefined,
|
|
117
|
+
now: Date,
|
|
118
|
+
): Record<string, LinkUnavailable> {
|
|
119
|
+
const unavailable: Record<string, LinkUnavailable> = {};
|
|
120
|
+
for (const provider of unserved) {
|
|
121
|
+
const plans = granted.filter((plan) => subscriptionModelProvider(plan.kind) === provider);
|
|
122
|
+
if (plans.length === 0) continue;
|
|
123
|
+
const usable = plans.filter((plan) => {
|
|
124
|
+
const client = subscriptionClient(plan.kind);
|
|
125
|
+
return client === undefined || client === clientHarness;
|
|
126
|
+
});
|
|
127
|
+
if (usable.length === 0) {
|
|
128
|
+
unavailable[provider] = plansForAnotherClient(plans.map((plan) => plan.kind));
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const held = usable.flatMap((plan) =>
|
|
132
|
+
plan.unavailableUntil !== null && plan.unavailableUntil > now ? [plan.unavailableUntil] : []
|
|
133
|
+
);
|
|
134
|
+
unavailable[provider] = plansExhausted(
|
|
135
|
+
usable.map((plan) => plan.kind),
|
|
136
|
+
held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return unavailable;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The error a grant that serves the request nothing gets: why its one pinned
|
|
144
|
+
* model is not served, or why none is.
|
|
145
|
+
*/
|
|
146
|
+
export function linkNothingServed(
|
|
147
|
+
unavailable: Record<string, LinkUnavailable>,
|
|
148
|
+
pins: readonly { model: string }[] | null | undefined,
|
|
149
|
+
): HttpError {
|
|
150
|
+
return pins?.length === 1
|
|
151
|
+
? modelNotServed({ link_unavailable: unavailable }, pins[0]!.model)
|
|
152
|
+
: linkGrantUnavailableError(unavailable);
|
|
153
|
+
}
|
|
154
|
+
|
|
103
155
|
/**
|
|
104
156
|
* Why a grant serves nothing at all: its plans are at their limits, serve
|
|
105
157
|
* only another client, or serve no model.
|
package/src/link/grants.ts
CHANGED
|
@@ -134,13 +134,15 @@ export type LinkRepo = {
|
|
|
134
134
|
/**
|
|
135
135
|
* Store tokens for a grant, all or none. With `rotate`, also mark that
|
|
136
136
|
* refresh token rotated: `race` when another request already did. `revoked`
|
|
137
|
-
* when the grant is no longer live.
|
|
137
|
+
* when the grant is no longer live. The grant's tokens that expired, or were
|
|
138
|
+
* rotated (except refresh tokens), before `forgetBefore` go.
|
|
138
139
|
*/
|
|
139
140
|
issueTokens(request: {
|
|
140
141
|
grantId: string;
|
|
141
142
|
tokens: LinkTokenIssue[];
|
|
142
143
|
rotate?: string;
|
|
143
144
|
now: number;
|
|
145
|
+
forgetBefore: number;
|
|
144
146
|
}): MaybePromise<"ok" | "race" | "revoked">;
|
|
145
147
|
/** Delete one token. */
|
|
146
148
|
deleteToken(tokenHash: string): MaybePromise<void>;
|
|
@@ -182,6 +184,9 @@ export function linkGrants(repo: LinkRepo) {
|
|
|
182
184
|
tokens: kinds.map((entry, index) => ({ ...entry, tokenHash: linkHash(tokens[index]!) })),
|
|
183
185
|
...(rotate === undefined ? {} : { rotate }),
|
|
184
186
|
now: now.getTime(),
|
|
187
|
+
// Rotated refresh tokens stay while the grant lives (revoking it deletes
|
|
188
|
+
// them): presenting one again is how a stolen refresh token is caught.
|
|
189
|
+
forgetBefore: now.getTime() - LINK_TOKEN_RETENTION_MS,
|
|
185
190
|
});
|
|
186
191
|
if (result === "race") {
|
|
187
192
|
throw new HttpError(
|
|
@@ -23,3 +23,8 @@ export const LINK_KEY_PROVIDERS: readonly LinkKeyProvider[] = [
|
|
|
23
23
|
.map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
|
|
24
24
|
...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway)!.label })),
|
|
25
25
|
];
|
|
26
|
+
|
|
27
|
+
/** What a provider is called where a user's key for it is shown: "OpenRouter". */
|
|
28
|
+
export function linkKeyProviderName(provider: string): string {
|
|
29
|
+
return LINK_KEY_PROVIDERS.find((candidate) => candidate.id === provider)?.name ?? provider;
|
|
30
|
+
}
|
package/src/link/self_hosted.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
type SubscriptionCredential,
|
|
22
22
|
} from "../self_host/subscriptions/index.js";
|
|
23
23
|
import { linkCompleteThrough } from "./in_flight.js";
|
|
24
|
-
import { LINK_KEY_PROVIDERS } from "./key_providers.js";
|
|
24
|
+
import { LINK_KEY_PROVIDERS, linkKeyProviderName } from "./key_providers.js";
|
|
25
25
|
import { linkPlatform } from "./service.js";
|
|
26
26
|
import type { LinkApiKey } from "./sqlite_store.js";
|
|
27
27
|
|
|
@@ -160,7 +160,7 @@ function linkKey(key: LinkApiKey): LinkSubscription {
|
|
|
160
160
|
id: key.id,
|
|
161
161
|
provider: "api_key",
|
|
162
162
|
apiKeyProvider: key.provider,
|
|
163
|
-
name:
|
|
163
|
+
name: linkKeyProviderName(key.provider),
|
|
164
164
|
label: `Key ending ${key.apiKey.slice(-4)}`,
|
|
165
165
|
accountEmail: null,
|
|
166
166
|
unavailableUntil: null,
|
package/src/link/service.ts
CHANGED
|
@@ -9,13 +9,13 @@ import { randomUUID } from "node:crypto";
|
|
|
9
9
|
|
|
10
10
|
import { HttpError } from "../http/errors.js";
|
|
11
11
|
import type {
|
|
12
|
-
LinkApp,
|
|
13
12
|
LinkBudget,
|
|
14
13
|
LinkBudgetStanding,
|
|
15
14
|
LinkConnect,
|
|
16
15
|
LinkKeyProvider,
|
|
17
16
|
LinkPlanAdded,
|
|
18
17
|
LinkPlatform,
|
|
18
|
+
LinkSignIn,
|
|
19
19
|
LinkSubscription,
|
|
20
20
|
} from "../platform/platform.js";
|
|
21
21
|
import type { SubscriptionKind } from "../types.js";
|
|
@@ -80,6 +80,8 @@ export type LinkStore = LinkRepo & {
|
|
|
80
80
|
export type LinkUsers = {
|
|
81
81
|
/** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
|
|
82
82
|
sessionSecret(): string;
|
|
83
|
+
/** See `LinkApprovalPage.signIn`. */
|
|
84
|
+
signIn?: LinkSignIn;
|
|
83
85
|
connectable: readonly SubscriptionKind[];
|
|
84
86
|
keyProviders: readonly LinkKeyProvider[];
|
|
85
87
|
/** See `LinkPlatform.httpRedirectHosts`. */
|
|
@@ -135,6 +137,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
135
137
|
httpRedirectHosts: users.httpRedirectHosts ?? [],
|
|
136
138
|
approval: {
|
|
137
139
|
sessionSecret: () => users.sessionSecret(),
|
|
140
|
+
...(users.signIn === undefined ? {} : { signIn: users.signIn }),
|
|
138
141
|
connectable: users.connectable,
|
|
139
142
|
keyProviders: users.keyProviders,
|
|
140
143
|
subscriptions: (subject) => users.plans(subject),
|
|
@@ -213,14 +216,9 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
213
216
|
if (apiKey === undefined && !users.openRegistration) {
|
|
214
217
|
throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
|
|
215
218
|
}
|
|
216
|
-
const clientSecret = confidential === true
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
name,
|
|
220
|
-
redirectUris,
|
|
221
|
-
confidential: clientSecret !== undefined,
|
|
222
|
-
};
|
|
223
|
-
await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
|
|
219
|
+
const { record, clientSecret } = newLinkApp({ name, redirectUris, confidential: confidential === true });
|
|
220
|
+
await users.registerApp(record, apiKey);
|
|
221
|
+
const { clientSecretHash: _, ...app } = record;
|
|
224
222
|
return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
|
|
225
223
|
},
|
|
226
224
|
async app(clientId) {
|
|
@@ -268,6 +266,32 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
268
266
|
};
|
|
269
267
|
}
|
|
270
268
|
|
|
269
|
+
/**
|
|
270
|
+
* A new app: its client id, and for a confidential one a client secret,
|
|
271
|
+
* returned this once, of which only the hash is kept. Every app is made here,
|
|
272
|
+
* whichever way it registers (hosted Dari's console included).
|
|
273
|
+
*/
|
|
274
|
+
export function newLinkApp(request: { name: string; redirectUris: string[]; confidential: boolean }): {
|
|
275
|
+
record: LinkAppRecord;
|
|
276
|
+
clientSecret?: string;
|
|
277
|
+
} {
|
|
278
|
+
const secret = request.confidential ? newLinkClientSecret() : null;
|
|
279
|
+
const record: LinkAppRecord = {
|
|
280
|
+
clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
|
|
281
|
+
name: request.name,
|
|
282
|
+
redirectUris: request.redirectUris,
|
|
283
|
+
confidential: secret !== null,
|
|
284
|
+
clientSecretHash: secret?.hash ?? null,
|
|
285
|
+
};
|
|
286
|
+
return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
290
|
+
export function newLinkClientSecret(): { secret: string; hash: string } {
|
|
291
|
+
const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
|
|
292
|
+
return { secret, hash: linkHash(secret) };
|
|
293
|
+
}
|
|
294
|
+
|
|
271
295
|
/**
|
|
272
296
|
* The grant a link token serves a request for: null when the key is no link
|
|
273
297
|
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|
package/src/link/sqlite_store.ts
CHANGED
|
@@ -9,9 +9,8 @@ import { randomUUID } from "node:crypto";
|
|
|
9
9
|
|
|
10
10
|
import { type SecretBox, openWithoutKey } from "../self_host/secret_box.js";
|
|
11
11
|
import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
|
|
12
|
-
import type { BudgetUse } from "./budget.js";
|
|
12
|
+
import type { BudgetUse, LinkTokenCounts } from "./budget.js";
|
|
13
13
|
import {
|
|
14
|
-
LINK_TOKEN_RETENTION_MS,
|
|
15
14
|
type LinkAppRecord,
|
|
16
15
|
type LinkPin,
|
|
17
16
|
type LinkRevoker,
|
|
@@ -211,12 +210,12 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
211
210
|
|
|
212
211
|
budgetUses(grantId: string, since: number): BudgetUse[] {
|
|
213
212
|
return this.db
|
|
214
|
-
.query<{ received_at: number
|
|
215
|
-
`SELECT received_at, input_tokens
|
|
213
|
+
.query<UsageTokenRow & { received_at: number }, [string, number]>(
|
|
214
|
+
`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
|
|
216
215
|
FROM link_usage WHERE grant_id = ? AND received_at > ?`,
|
|
217
216
|
)
|
|
218
217
|
.all(grantId, since)
|
|
219
|
-
.map((row) => ({ at: new Date(row.received_at),
|
|
218
|
+
.map((row) => ({ at: new Date(row.received_at), ...tokenCounts(row) }));
|
|
220
219
|
}
|
|
221
220
|
|
|
222
221
|
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
@@ -256,10 +255,7 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
256
255
|
model: row.model,
|
|
257
256
|
thinking: row.thinking,
|
|
258
257
|
tags: JSON.parse(row.tags) as Record<string, string>,
|
|
259
|
-
|
|
260
|
-
outputTokens: row.output_tokens,
|
|
261
|
-
cacheReadTokens: row.cache_read_tokens,
|
|
262
|
-
cacheWriteTokens: row.cache_write_tokens,
|
|
258
|
+
...tokenCounts(row),
|
|
263
259
|
}));
|
|
264
260
|
}
|
|
265
261
|
|
|
@@ -392,7 +388,7 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
392
388
|
};
|
|
393
389
|
}
|
|
394
390
|
|
|
395
|
-
issueTokens(request: { grantId: string; tokens: LinkTokenIssue[]; rotate?: string; now: number }): "ok" | "race" | "revoked" {
|
|
391
|
+
issueTokens(request: { grantId: string; tokens: LinkTokenIssue[]; rotate?: string; now: number; forgetBefore: number }): "ok" | "race" | "revoked" {
|
|
396
392
|
return this.db.transaction((): "ok" | "race" | "revoked" => {
|
|
397
393
|
const live = this.db
|
|
398
394
|
.query<{ id: string }, [string]>("SELECT id FROM link_grants WHERE id = ? AND revoked_at IS NULL")
|
|
@@ -405,10 +401,10 @@ export class SqliteLinkStore implements LinkStore {
|
|
|
405
401
|
).changes;
|
|
406
402
|
if (rotated === 0) return "race";
|
|
407
403
|
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
404
|
+
this.db.run(
|
|
405
|
+
"DELETE FROM link_tokens WHERE grant_id = ? AND (expires_at < ? OR (rotated_at < ? AND kind != 'refresh'))",
|
|
406
|
+
[request.grantId, request.forgetBefore, request.forgetBefore],
|
|
407
|
+
);
|
|
412
408
|
this.insertTokens(request.grantId, request.tokens, request.now);
|
|
413
409
|
return "ok";
|
|
414
410
|
})();
|
|
@@ -470,17 +466,29 @@ export type LinkUsageEntry = {
|
|
|
470
466
|
status: string;
|
|
471
467
|
};
|
|
472
468
|
|
|
473
|
-
type
|
|
474
|
-
status: string | null;
|
|
475
|
-
model: string | null;
|
|
476
|
-
thinking: string | null;
|
|
477
|
-
tags: string;
|
|
469
|
+
type UsageTokenRow = {
|
|
478
470
|
input_tokens: number;
|
|
479
471
|
output_tokens: number;
|
|
480
472
|
cache_read_tokens: number;
|
|
481
473
|
cache_write_tokens: number;
|
|
482
474
|
};
|
|
483
475
|
|
|
476
|
+
type UsageRow = UsageTokenRow & {
|
|
477
|
+
status: string | null;
|
|
478
|
+
model: string | null;
|
|
479
|
+
thinking: string | null;
|
|
480
|
+
tags: string;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
function tokenCounts(row: UsageTokenRow): LinkTokenCounts {
|
|
484
|
+
return {
|
|
485
|
+
inputTokens: row.input_tokens,
|
|
486
|
+
outputTokens: row.output_tokens,
|
|
487
|
+
cacheReadTokens: row.cache_read_tokens,
|
|
488
|
+
cacheWriteTokens: row.cache_write_tokens,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
484
492
|
// A child token's models. One minted before `pins` existed kept its one model
|
|
485
493
|
// in `model` and `thinking`.
|
|
486
494
|
function childPins(row: TokenRow): LinkPin[] | null {
|