@mupt-ai/dari-gateway 1.0.313 → 1.0.315
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 +17 -20
- package/dist/http/handler.js +1 -1
- package/dist/http/http2_server.js +5 -1
- package/dist/ingress/anthropic_messages.js +1 -1
- package/dist/ingress/models.js +1 -1
- package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
- package/dist/{link_client.js → link/client.js} +5 -6
- package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
- package/dist/{ingress/link.js → link/endpoints.js} +158 -62
- package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
- package/dist/link/grants.d.ts +151 -0
- package/dist/link/grants.js +275 -0
- package/dist/link/key_providers.d.ts +6 -0
- package/dist/link/key_providers.js +21 -0
- package/dist/link/self_hosted.d.ts +3 -0
- package/dist/link/self_hosted.js +166 -0
- package/dist/link/service.d.ts +85 -0
- package/dist/link/service.js +187 -0
- package/dist/link/sqlite_store.d.ts +74 -0
- package/dist/link/sqlite_store.js +381 -0
- package/dist/models/canonical_models.json +19 -0
- package/dist/platform/platform.d.ts +42 -47
- package/dist/runtime/explicit_model.js +1 -1
- package/dist/runtime/prepare_routed_completion.js +1 -1
- package/dist/self_host/main.js +2 -2
- package/dist/self_host/platform.js +4 -249
- package/dist/self_host/resolve.d.ts +2 -2
- package/dist/self_host/resolve.js +3 -19
- package/dist/self_host/stub_gateway.js +3 -3
- package/dist/self_host/subscriptions/http.js +2 -2
- package/dist/telemetry/report.js +1 -1
- package/package.json +2 -2
- package/src/http/handler.ts +1 -1
- package/src/http/http2_server.ts +4 -1
- package/src/ingress/anthropic_messages.ts +1 -1
- package/src/ingress/models.ts +1 -1
- package/src/{link_client.ts → link/client.ts} +11 -14
- package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
- package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
- package/src/link/grants.ts +436 -0
- package/src/link/key_providers.ts +25 -0
- package/src/link/self_hosted.ts +186 -0
- package/src/link/service.ts +281 -0
- package/src/link/sqlite_store.ts +512 -0
- package/src/models/canonical_models.json +19 -0
- package/src/platform/platform.ts +39 -45
- package/src/runtime/explicit_model.ts +1 -1
- package/src/runtime/prepare_routed_completion.ts +1 -1
- package/src/self_host/main.ts +2 -2
- package/src/self_host/platform.ts +5 -267
- package/src/self_host/resolve.ts +6 -21
- package/src/self_host/stub_gateway.ts +3 -3
- package/src/self_host/subscriptions/http.ts +2 -2
- package/src/telemetry/report.ts +1 -1
- package/dist/self_host/link_store.d.ts +0 -167
- package/dist/self_host/link_store.js +0 -564
- package/src/self_host/link_store.ts +0 -782
- /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
- /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
- /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
- /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
- /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
- /package/dist/{models/link_errors.js → link/errors.js} +0 -0
- /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
- /package/dist/{ingress/link_font.js → link/font.js} +0 -0
- /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
- /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
- /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
- /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
- /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
- /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
/* Dari Link: OAuth 2.0 authorization code grants with PKCE (S256) that let an
|
|
2
2
|
app send one user's requests on the subscriptions the user chose. The
|
|
3
|
-
gateway serves the protocol
|
|
4
|
-
|
|
5
|
-
grants, and tokens
|
|
3
|
+
gateway serves the protocol, the approval page, and the connections page
|
|
4
|
+
on every platform; the platform (GatewayPlatform.link, made by
|
|
5
|
+
link/service.ts) stores apps, grants, and tokens, and says who its users
|
|
6
|
+
are.
|
|
6
7
|
|
|
7
8
|
- GET /.well-known/oauth-authorization-server metadata (RFC 8414)
|
|
8
9
|
- POST /v1/link/register open client registration (RFC 7591)
|
|
9
|
-
- GET /v1/link/authorize the approval page
|
|
10
|
-
consent page gets the validated request
|
|
11
|
-
redirected there
|
|
10
|
+
- GET /v1/link/authorize the approval page
|
|
12
11
|
- POST /v1/link/authorize each step of the page: connect a plan, then
|
|
13
12
|
approve or deny; returns `code`
|
|
14
13
|
or `error` to the app: on its redirect URI,
|
|
@@ -25,6 +24,10 @@
|
|
|
25
24
|
- PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
|
|
26
25
|
budget: the most tokens the app may use per
|
|
27
26
|
five hours and per week
|
|
27
|
+
- GET /v1/link/connections the page where the approval page's user sees
|
|
28
|
+
the apps they connected, sets each one's
|
|
29
|
+
budget, disconnects it, and removes plans
|
|
30
|
+
- POST /v1/link/connections each of those changes
|
|
28
31
|
|
|
29
32
|
A confidential client authenticates at the token and revocation endpoints
|
|
30
33
|
with HTTP Basic (`client_id:client_secret`); a public one sends `client_id`
|
|
@@ -32,26 +35,27 @@
|
|
|
32
35
|
|
|
33
36
|
The gateway's own approval page needs no account, like a bank link: the
|
|
34
37
|
user picks a plan, signs in to its provider, and allows the app. Their first
|
|
35
|
-
plan makes them
|
|
36
|
-
SameSite=Lax cookie scoped to
|
|
37
|
-
finds their plans connected
|
|
38
|
-
|
|
38
|
+
plan makes them a user (hosted: a Dari account with no sign-in) the gateway
|
|
39
|
+
keeps in a signed, HttpOnly, SameSite=Lax cookie scoped to /v1/link/, so
|
|
40
|
+
the next app that asks finds their plans connected and the connections page
|
|
41
|
+
knows them. Every change needs that cookie and a form token derived from
|
|
42
|
+
it, so another site cannot make one. */
|
|
39
43
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
40
44
|
import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
41
45
|
import { bearerToken } from "../http/auth.js";
|
|
42
46
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
43
|
-
import { SUBSCRIPTION_PLAN_LABELS } from "
|
|
47
|
+
import { SUBSCRIPTION_PLAN_LABELS } from "./errors.js";
|
|
44
48
|
import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
45
49
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
46
50
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
47
51
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
48
52
|
import { gatewayFor } from "../models/gateways.js";
|
|
49
|
-
import { budgetBody, validBudget } from "
|
|
50
|
-
import { catalogModelFor } from "
|
|
53
|
+
import { budgetBody, validBudget } from "./budget.js";
|
|
54
|
+
import { catalogModelFor } from "./grant_access.js";
|
|
51
55
|
import { requestTags } from "../runtime/request_tags.js";
|
|
52
|
-
import { parseJsonRequest } from "
|
|
53
|
-
import { DARI_MARK, ICONS, linkLogo } from "./
|
|
54
|
-
import { GEIST_WOFF2 } from "./
|
|
56
|
+
import { parseJsonRequest } from "../ingress/json.js";
|
|
57
|
+
import { DARI_MARK, ICONS, linkLogo } from "./assets.js";
|
|
58
|
+
import { GEIST_WOFF2 } from "./font.js";
|
|
55
59
|
const VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
56
60
|
// The base64url SHA-256 of a verifier.
|
|
57
61
|
const CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
|
|
@@ -73,6 +77,9 @@ const CONNECT_SECONDS = 15 * 60;
|
|
|
73
77
|
// How often the page asks a provider whether the user approved its code.
|
|
74
78
|
const DEVICE_POLL_SECONDS = 5;
|
|
75
79
|
const AUTHORIZE_PATH = "/v1/link/authorize";
|
|
80
|
+
const CONNECTIONS_PATH = "/v1/link/connections";
|
|
81
|
+
// Where the pages' cookies are sent.
|
|
82
|
+
const COOKIE_PATH = "/v1/link/";
|
|
76
83
|
const CALLBACK_SCRIPT_PATH = "/v1/link/callback.js";
|
|
77
84
|
// The approval page's typeface.
|
|
78
85
|
const FONT_PATH = "/v1/link/geist.woff2";
|
|
@@ -134,6 +141,12 @@ export async function handleLinkRequest(request, platform) {
|
|
|
134
141
|
if (pathname === AUTHORIZE_PATH && request.method === "POST") {
|
|
135
142
|
return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
|
|
136
143
|
}
|
|
144
|
+
if (pathname === CONNECTIONS_PATH && request.method === "GET") {
|
|
145
|
+
return await connectionsPage(link.approval, request);
|
|
146
|
+
}
|
|
147
|
+
if (pathname === CONNECTIONS_PATH && request.method === "POST") {
|
|
148
|
+
return await connectionsSubmit(link.approval, request, new URLSearchParams(await request.text()));
|
|
149
|
+
}
|
|
137
150
|
if (request.method === "OPTIONS" && (CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname))) {
|
|
138
151
|
return withCors(new Response(null, { status: 204 }));
|
|
139
152
|
}
|
|
@@ -215,16 +228,15 @@ function metadata(origin, link) {
|
|
|
215
228
|
authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
|
|
216
229
|
response_modes_supported: ["query", WEB_MESSAGE],
|
|
217
230
|
// The origin a `web_message` result is posted from: the page that approves.
|
|
218
|
-
web_message_origin:
|
|
231
|
+
web_message_origin: origin,
|
|
219
232
|
token_endpoint: `${origin}/v1/link/token`,
|
|
220
233
|
registration_endpoint: `${origin}/v1/link/register`,
|
|
221
234
|
revocation_endpoint: `${origin}/v1/link/revoke`,
|
|
222
235
|
// A script for the redirect URI's page that hands an approval back to the
|
|
223
236
|
// window that opened the popup (see the README's callback contract).
|
|
224
237
|
callback_script: `${origin}${CALLBACK_SCRIPT_PATH}`,
|
|
225
|
-
// Where users manage the apps they connected
|
|
226
|
-
|
|
227
|
-
connected_apps_uri: "consentUrl" in link.approval ? link.approval.connectedAppsUrl : null,
|
|
238
|
+
// Where users manage the apps they connected.
|
|
239
|
+
connected_apps_uri: `${origin}${CONNECTIONS_PATH}`,
|
|
228
240
|
response_types_supported: ["code"],
|
|
229
241
|
grant_types_supported: ["authorization_code", "refresh_token", TOKEN_EXCHANGE_GRANT],
|
|
230
242
|
code_challenge_methods_supported: ["S256"],
|
|
@@ -426,7 +438,7 @@ async function token(platform, link, request) {
|
|
|
426
438
|
if (!VERIFIER.test(verifier)) {
|
|
427
439
|
return oauthError("invalid_request", "code_verifier must be 43 to 128 unreserved characters.");
|
|
428
440
|
}
|
|
429
|
-
return await tokenResponse(platform, link, await link.exchangeCode({
|
|
441
|
+
return await tokenResponse(platform, link, request, await link.exchangeCode({
|
|
430
442
|
...client,
|
|
431
443
|
code,
|
|
432
444
|
redirectUri,
|
|
@@ -437,7 +449,7 @@ async function token(platform, link, request) {
|
|
|
437
449
|
const refreshToken = body.get("refresh_token") ?? "";
|
|
438
450
|
if (!refreshToken)
|
|
439
451
|
return oauthError("invalid_request", "refresh_token is required.");
|
|
440
|
-
return await tokenResponse(platform, link, await link.refresh({ ...client, refreshToken }));
|
|
452
|
+
return await tokenResponse(platform, link, request, await link.refresh({ ...client, refreshToken }));
|
|
441
453
|
}
|
|
442
454
|
if (grantType === TOKEN_EXCHANGE_GRANT)
|
|
443
455
|
return await childToken(platform, link, client, body);
|
|
@@ -563,7 +575,7 @@ async function revoke(link, request) {
|
|
|
563
575
|
async function grant(platform, link, request) {
|
|
564
576
|
const accessToken = bearerToken(request.headers);
|
|
565
577
|
const detail = await link.grant(accessToken);
|
|
566
|
-
return Response.json(await grantBody(platform, accessToken, detail), { headers: { "Cache-Control": "no-store" } });
|
|
578
|
+
return Response.json(await grantBody(platform, request, accessToken, detail), { headers: { "Cache-Control": "no-store" } });
|
|
567
579
|
}
|
|
568
580
|
/**
|
|
569
581
|
* What the grant's requests used, child tokens' included: `tag=k=v`
|
|
@@ -631,13 +643,13 @@ async function usage(link, request, params, requestId) {
|
|
|
631
643
|
function stringFields(body) {
|
|
632
644
|
return Object.fromEntries(Object.entries(body).flatMap(([key, value]) => typeof value === "string" ? [[key, value]] : typeof value === "number" ? [[key, String(value)]] : []));
|
|
633
645
|
}
|
|
634
|
-
async function tokenResponse(platform, link, tokens) {
|
|
646
|
+
async function tokenResponse(platform, link, request, tokens) {
|
|
635
647
|
return Response.json({
|
|
636
648
|
access_token: tokens.accessToken,
|
|
637
649
|
token_type: "Bearer",
|
|
638
650
|
expires_in: tokens.expiresIn,
|
|
639
651
|
refresh_token: tokens.refreshToken,
|
|
640
|
-
...(await grantBody(platform, tokens.accessToken, await link.grant(tokens.accessToken))),
|
|
652
|
+
...(await grantBody(platform, request, tokens.accessToken, await link.grant(tokens.accessToken))),
|
|
641
653
|
}, { headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });
|
|
642
654
|
}
|
|
643
655
|
/**
|
|
@@ -646,8 +658,7 @@ async function tokenResponse(platform, link, tokens) {
|
|
|
646
658
|
* `models` is what a plain API client (anything but Claude Code or Muse Code)
|
|
647
659
|
* can name, and `routes` whether `dari/routing` serves it.
|
|
648
660
|
*/
|
|
649
|
-
async function grantBody(platform, accessToken, detail) {
|
|
650
|
-
const approval = platform.link?.approval;
|
|
661
|
+
async function grantBody(platform, request, accessToken, detail) {
|
|
651
662
|
const now = Date.now();
|
|
652
663
|
const kinds = detail.subscriptions
|
|
653
664
|
.filter((subscription) => subscription.apiKeyProvider === undefined)
|
|
@@ -673,10 +684,8 @@ async function grantBody(platform, accessToken, detail) {
|
|
|
673
684
|
})),
|
|
674
685
|
// `budget_limit` while a window is at its cap, until `available_at`.
|
|
675
686
|
...grantState(detail.budget),
|
|
676
|
-
//
|
|
677
|
-
|
|
678
|
-
// Where the user manages this grant; null without a signed-in app.
|
|
679
|
-
manage_url: approval !== undefined && "consentUrl" in approval ? manageUrl(approval.connectedAppsUrl, detail.id) : null,
|
|
687
|
+
// Where the user manages this grant: the connections page, in the browser they approved it in.
|
|
688
|
+
manage_url: `${publicOrigin(request)}${CONNECTIONS_PATH}#${encodeURIComponent(detail.id)}`,
|
|
680
689
|
plans: detail.subscriptions.map((subscription) => {
|
|
681
690
|
// An API key serves its provider's models to any app.
|
|
682
691
|
const keyFor = subscription.apiKeyProvider;
|
|
@@ -710,11 +719,6 @@ async function grantBody(platform, accessToken, detail) {
|
|
|
710
719
|
routes: (plain?.enabled_models.length ?? 0) > 0,
|
|
711
720
|
};
|
|
712
721
|
}
|
|
713
|
-
function manageUrl(connectedAppsUrl, grantId) {
|
|
714
|
-
const url = new URL(connectedAppsUrl);
|
|
715
|
-
url.searchParams.set("grant", grantId);
|
|
716
|
-
return url.toString();
|
|
717
|
-
}
|
|
718
722
|
/** The latest of some times, or null for none. */
|
|
719
723
|
function latest(times) {
|
|
720
724
|
return times.reduce((last, time) => last === null || Date.parse(time) > Date.parse(last) ? time : last, null);
|
|
@@ -859,18 +863,10 @@ async function authorizePage(link, request, params) {
|
|
|
859
863
|
if (authorize instanceof Response)
|
|
860
864
|
return authorize;
|
|
861
865
|
const approval = link.approval;
|
|
862
|
-
if ("consentUrl" in approval) {
|
|
863
|
-
// The platform's own page signs the user in and approves; it gets the
|
|
864
|
-
// request as validated here.
|
|
865
|
-
return new Response(null, {
|
|
866
|
-
status: 303,
|
|
867
|
-
headers: { Location: `${approval.consentUrl}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" },
|
|
868
|
-
});
|
|
869
|
-
}
|
|
870
866
|
const secret = approval.sessionSecret();
|
|
871
867
|
const session = sessionFrom(request, secret);
|
|
872
|
-
const connect =
|
|
873
|
-
if (
|
|
868
|
+
const connect = connectFrom(request, secret);
|
|
869
|
+
if (connect !== null) {
|
|
874
870
|
// A provider that gave the user a code to enter is asked whether they approved.
|
|
875
871
|
return connect.userCode === null
|
|
876
872
|
? providerPage(authorize, connect)
|
|
@@ -903,9 +899,6 @@ async function grantToUpdate(approval, authorize, session) {
|
|
|
903
899
|
return grant;
|
|
904
900
|
}
|
|
905
901
|
async function authorizeSubmit(link, request, form) {
|
|
906
|
-
// A platform with its own consent page takes no approval here.
|
|
907
|
-
if ("consentUrl" in link.approval)
|
|
908
|
-
return errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
909
902
|
const approval = link.approval;
|
|
910
903
|
// Only the page itself submits here: another site's form would otherwise
|
|
911
904
|
// arrive without the user's cookie and replace it with a new identity.
|
|
@@ -936,11 +929,9 @@ async function authorizeSubmit(link, request, form) {
|
|
|
936
929
|
if (!connectKinds(approval, authorize).includes(kind)) {
|
|
937
930
|
return selectPage(approval, authorize, "Choose a subscription to connect.", [endConnect]);
|
|
938
931
|
}
|
|
939
|
-
// A first plan makes the user: an opaque subject the cookie remembers.
|
|
940
|
-
const subject = session?.subject ?? `lu_${randomUUID().replaceAll("-", "")}`;
|
|
941
932
|
let started;
|
|
942
933
|
try {
|
|
943
|
-
started = await approval.startConnect(
|
|
934
|
+
started = await approval.startConnect(kind);
|
|
944
935
|
}
|
|
945
936
|
catch (error) {
|
|
946
937
|
if (!(error instanceof HttpError))
|
|
@@ -950,7 +941,6 @@ async function authorizeSubmit(link, request, form) {
|
|
|
950
941
|
return selectPage(approval, authorize, reason, [endConnect]);
|
|
951
942
|
}
|
|
952
943
|
return seeAuthorize(authorize, [
|
|
953
|
-
signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS),
|
|
954
944
|
signedCookie(request, secret, CONNECT_COOKIE, { session: started.session, kind, url: started.authorizationUrl, code: started.userCode }, CONNECT_SECONDS),
|
|
955
945
|
]);
|
|
956
946
|
}
|
|
@@ -960,19 +950,20 @@ async function authorizeSubmit(link, request, form) {
|
|
|
960
950
|
const apiKey = form.get("api_key")?.trim() ?? "";
|
|
961
951
|
if (!apiKey)
|
|
962
952
|
return keyPage(authorize, keyProvider, `Paste your ${keyProvider.name} API key.`);
|
|
963
|
-
|
|
953
|
+
// A first plan makes the user, whom the cookie remembers.
|
|
954
|
+
let added;
|
|
964
955
|
try {
|
|
965
|
-
await approval.addKey(subject, keyProvider.id, apiKey);
|
|
956
|
+
added = await approval.addKey(session?.subject ?? null, keyProvider.id, apiKey);
|
|
966
957
|
}
|
|
967
958
|
catch (error) {
|
|
968
959
|
if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "link_not_configured"))
|
|
969
960
|
throw error;
|
|
970
961
|
return keyPage(authorize, keyProvider, error.message);
|
|
971
962
|
}
|
|
972
|
-
return seeAuthorize(authorize, [
|
|
963
|
+
return seeAuthorize(authorize, [userCookie(request, secret, added.subject), endConnect]);
|
|
973
964
|
}
|
|
974
|
-
const connect =
|
|
975
|
-
if (decision === "complete" &&
|
|
965
|
+
const connect = connectFrom(request, secret);
|
|
966
|
+
if (decision === "complete" && connect !== null) {
|
|
976
967
|
return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
|
|
977
968
|
}
|
|
978
969
|
// Removing a plan or key asks once, then deletes what Dari stored for it.
|
|
@@ -1028,7 +1019,8 @@ async function finishConnect(approval, request, authorize, session, connect, aut
|
|
|
1028
1019
|
const endConnect = clearCookie(request, CONNECT_COOKIE);
|
|
1029
1020
|
let connected;
|
|
1030
1021
|
try {
|
|
1031
|
-
|
|
1022
|
+
// A first plan makes the user, whom the cookie remembers.
|
|
1023
|
+
connected = await approval.completeConnect(session?.subject ?? null, connect.session, authorizationResponse);
|
|
1032
1024
|
}
|
|
1033
1025
|
catch (error) {
|
|
1034
1026
|
if (!(error instanceof HttpError) || error.status !== 400)
|
|
@@ -1038,7 +1030,105 @@ async function finishConnect(approval, request, authorize, session, connect, aut
|
|
|
1038
1030
|
? providerPage(authorize, connect, error.message)
|
|
1039
1031
|
: selectPage(approval, authorize, error.message, [endConnect]);
|
|
1040
1032
|
}
|
|
1041
|
-
return connected === null
|
|
1033
|
+
return connected === null
|
|
1034
|
+
? providerPage(authorize, connect)
|
|
1035
|
+
: seeAuthorize(authorize, [userCookie(request, approval.sessionSecret(), connected.subject), endConnect]);
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* The connections page: the apps the browser's user connected, with what each
|
|
1039
|
+
* shares and used so far, its budget, and Disconnect; then the user's plans
|
|
1040
|
+
* and keys, each of which they can remove.
|
|
1041
|
+
*/
|
|
1042
|
+
async function connectionsPage(approval, request, error) {
|
|
1043
|
+
const session = sessionFrom(request, approval.sessionSecret());
|
|
1044
|
+
const title = "Connected Apps";
|
|
1045
|
+
if (session === null) {
|
|
1046
|
+
return 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>`);
|
|
1047
|
+
}
|
|
1048
|
+
const [connections, plans] = await Promise.all([
|
|
1049
|
+
approval.connections(session.subject),
|
|
1050
|
+
approval.subscriptions(session.subject),
|
|
1051
|
+
]);
|
|
1052
|
+
const csrf = `<input type="hidden" name="csrf" value="${session.csrf}">`;
|
|
1053
|
+
const cards = connections.map((connection) => connectionCard(connection, csrf));
|
|
1054
|
+
const planRows = plans.map((plan) => `<form class="option pick" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1055
|
+
<input type="hidden" name="remove_id" value="${escapeHtml(plan.id)}">${logo(plan.apiKeyProvider ?? plan.provider, planName(plan))}<span class="grow"><strong>${escapeHtml(planName(plan))}</strong><small>${escapeHtml(planLabel(plan))}</small></span><button class="nav drop" type="submit" name="decision" value="remove" aria-label="Remove">${ICONS.trash}</button></form>`);
|
|
1056
|
+
return page(title, `<div class="body">
|
|
1057
|
+
<h1>${title}</h1>
|
|
1058
|
+
${error === undefined ? "" : `<p role="alert">${escapeHtml(error)}</p>`}
|
|
1059
|
+
${cards.length === 0 ? "<p>No apps are connected.</p>" : cards.join("\n")}
|
|
1060
|
+
${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${planRows.join("\n")}`}
|
|
1061
|
+
</div>`);
|
|
1062
|
+
}
|
|
1063
|
+
function connectionCard(connection, csrf) {
|
|
1064
|
+
const tokens = connection.usage.inputTokens + connection.usage.outputTokens
|
|
1065
|
+
+ connection.usage.cacheReadTokens + connection.usage.cacheWriteTokens;
|
|
1066
|
+
const limit = (minutes, label) => {
|
|
1067
|
+
const standing = connection.budget.find((window) => window.windowMinutes === minutes);
|
|
1068
|
+
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
1069
|
+
<input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
|
|
1070
|
+
${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
|
|
1071
|
+
};
|
|
1072
|
+
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1073
|
+
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1074
|
+
<strong>${escapeHtml(connection.appName)}</strong>
|
|
1075
|
+
<small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} · ${count(connection.usage.requests)} requests · ${count(tokens)} tokens</small>
|
|
1076
|
+
<small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
|
|
1077
|
+
${limit(300, "Per 5 Hours")}
|
|
1078
|
+
${limit(10080, "Per Week")}
|
|
1079
|
+
<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>
|
|
1080
|
+
</form>`;
|
|
1081
|
+
}
|
|
1082
|
+
async function connectionsSubmit(approval, request, form) {
|
|
1083
|
+
if (crossSite(request)) {
|
|
1084
|
+
return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open the connections page again.</p></div>`, { status: 403 });
|
|
1085
|
+
}
|
|
1086
|
+
const session = sessionFrom(request, approval.sessionSecret());
|
|
1087
|
+
const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
|
|
1088
|
+
if (session === null || !sameText(form.get("csrf") ?? "", session.csrf))
|
|
1089
|
+
return back;
|
|
1090
|
+
const decision = form.get("decision");
|
|
1091
|
+
const grantId = form.get("grant_id") ?? "";
|
|
1092
|
+
if (decision === "disconnect") {
|
|
1093
|
+
await approval.disconnect(session.subject, grantId);
|
|
1094
|
+
return back;
|
|
1095
|
+
}
|
|
1096
|
+
if (decision === "budget") {
|
|
1097
|
+
const entries = [300, 10080].flatMap((minutes) => {
|
|
1098
|
+
const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
|
|
1099
|
+
return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
|
|
1100
|
+
});
|
|
1101
|
+
const budget = validBudget(entries);
|
|
1102
|
+
if (budget === null)
|
|
1103
|
+
return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1104
|
+
await approval.setBudget(session.subject, grantId, budget);
|
|
1105
|
+
return back;
|
|
1106
|
+
}
|
|
1107
|
+
const removing = form.get("remove_id");
|
|
1108
|
+
const plan = removing === null ? undefined : (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
|
|
1109
|
+
if (plan !== undefined && decision === "remove") {
|
|
1110
|
+
const name = planName(plan);
|
|
1111
|
+
return page(`Remove ${name}`, `<form method="post" action="${CONNECTIONS_PATH}"><div class="body">
|
|
1112
|
+
<span class="who">${logo(plan.apiKeyProvider ?? plan.provider, name)}</span>
|
|
1113
|
+
<h1>Remove ${escapeHtml(name)}</h1>
|
|
1114
|
+
<p>${escapeHtml(planLabel(plan))}</p>
|
|
1115
|
+
<p>Dari deletes ${plan.apiKeyProvider === undefined ? "the sign-in it holds for this plan" : "this key"}. Every app you shared it with stops using it.</p>
|
|
1116
|
+
<input type="hidden" name="csrf" value="${session.csrf}">
|
|
1117
|
+
<input type="hidden" name="remove_id" value="${escapeHtml(plan.id)}">
|
|
1118
|
+
</div><div class="foot"><button class="btn danger" type="submit" name="decision" value="remove_confirmed">Remove</button></div></form>`);
|
|
1119
|
+
}
|
|
1120
|
+
if (plan !== undefined && decision === "remove_confirmed")
|
|
1121
|
+
await approval.remove(session.subject, plan.id);
|
|
1122
|
+
return back;
|
|
1123
|
+
}
|
|
1124
|
+
// What a plan or key is called: "Claude", or "OpenRouter API Key".
|
|
1125
|
+
function planName(subscription) {
|
|
1126
|
+
return subscription.apiKeyProvider !== undefined
|
|
1127
|
+
? `${subscription.name} API Key`
|
|
1128
|
+
: KINDS[subscription.provider]?.name ?? subscription.name;
|
|
1129
|
+
}
|
|
1130
|
+
function count(value) {
|
|
1131
|
+
return value.toLocaleString("en-US");
|
|
1042
1132
|
}
|
|
1043
1133
|
// Back to the approval page by GET, so no form is left to resubmit.
|
|
1044
1134
|
function seeAuthorize(authorize, cookies) {
|
|
@@ -1119,10 +1209,14 @@ function signedValue(secret, cookie, value, seconds) {
|
|
|
1119
1209
|
return `${payload}.${sign(secret, `${cookie}\0${payload}`)}`;
|
|
1120
1210
|
}
|
|
1121
1211
|
function signedCookie(request, secret, cookie, value, seconds) {
|
|
1122
|
-
return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${
|
|
1212
|
+
return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${COOKIE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
1213
|
+
}
|
|
1214
|
+
// Who the user is, for a year from their last plan.
|
|
1215
|
+
function userCookie(request, secret, subject) {
|
|
1216
|
+
return signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS);
|
|
1123
1217
|
}
|
|
1124
1218
|
function clearCookie(request, cookie) {
|
|
1125
|
-
return `${cookie}=; Path=${
|
|
1219
|
+
return `${cookie}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
1126
1220
|
}
|
|
1127
1221
|
/**
|
|
1128
1222
|
* The `Cookie` header value that makes a request this user's on the approval
|
|
@@ -1459,6 +1553,8 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
|
|
|
1459
1553
|
.btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
|
|
1460
1554
|
.btn.ghost{height:32px;margin:4px 0 0 -8px;padding:0 10px 0 8px;font-size:13px;color:var(--muted)}.btn.ghost:hover{background:rgba(237,237,237,.06);color:var(--ink)}
|
|
1461
1555
|
.fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
|
|
1556
|
+
.card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
|
|
1557
|
+
.row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
|
|
1462
1558
|
.nav{position:absolute;top:10px;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--muted);cursor:pointer}
|
|
1463
1559
|
.nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
|
|
1464
1560
|
.done{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;margin:0 0 20px;border:1px solid rgba(142,230,189,.4);border-radius:6px;background:rgba(142,230,189,.1);color:var(--mint)}.done .icon{width:22px;height:22px}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { linkGrantError, modelNotServed } from "
|
|
1
|
+
import { linkGrantError, modelNotServed } from "./errors.js";
|
|
2
2
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
3
3
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
4
4
|
import { modelMetadataLookup } from "../providers/pi.js";
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type { LinkApp, LinkBudget, LinkChildToken, LinkClient, LinkCodeExchange, LinkTokenExchange, LinkTokens, LinkUsage, LinkUsageQuery, LinkUsageTotals } from "../platform/platform.js";
|
|
2
|
+
export declare const LINK_ACCESS_TOKEN_TTL_MS: number;
|
|
3
|
+
export declare const LINK_CODE_TTL_MS: number;
|
|
4
|
+
export declare const LINK_REFRESH_RACE_MS = 60000;
|
|
5
|
+
export declare const LINK_TOKEN_RETENTION_MS: number;
|
|
6
|
+
export declare const LINK_REFRESH_TOKEN_PREFIX = "dlk_rt_";
|
|
7
|
+
export declare const LINK_CODE_PREFIX = "dlk_code_";
|
|
8
|
+
export declare const LINK_CLIENT_SECRET_PREFIX = "dlk_cs_";
|
|
9
|
+
export type LinkRevoker = "user" | "app" | "reuse_detected";
|
|
10
|
+
export type LinkTokenKind = "access" | "refresh" | "child";
|
|
11
|
+
export type LinkPin = {
|
|
12
|
+
model: string;
|
|
13
|
+
thinking: string | null;
|
|
14
|
+
};
|
|
15
|
+
export type ActiveLinkGrant = {
|
|
16
|
+
id: string;
|
|
17
|
+
clientId: string;
|
|
18
|
+
credentialIds: ReadonlySet<string>;
|
|
19
|
+
budget: LinkBudget[];
|
|
20
|
+
pins?: LinkPin[];
|
|
21
|
+
tags?: Record<string, string>;
|
|
22
|
+
};
|
|
23
|
+
/** What a presented link token is; null when it is not one the platform issued. */
|
|
24
|
+
export type LinkTokenAuth = {
|
|
25
|
+
status: "active";
|
|
26
|
+
grant: ActiveLinkGrant;
|
|
27
|
+
} | {
|
|
28
|
+
status: "expired";
|
|
29
|
+
} | {
|
|
30
|
+
status: "revoked";
|
|
31
|
+
revokedBy: string | null;
|
|
32
|
+
revokedAt: string | null;
|
|
33
|
+
};
|
|
34
|
+
/** A registered app as stored: with the hash of a confidential client's secret. */
|
|
35
|
+
export type LinkAppRecord = LinkApp & {
|
|
36
|
+
clientSecretHash: string | null;
|
|
37
|
+
};
|
|
38
|
+
/** A stored token with the grant it belongs to. Times are epoch milliseconds. */
|
|
39
|
+
export type LinkTokenRecord = {
|
|
40
|
+
kind: LinkTokenKind;
|
|
41
|
+
expiresAt: number | null;
|
|
42
|
+
rotatedAt: number | null;
|
|
43
|
+
pins: LinkPin[] | null;
|
|
44
|
+
tags: Record<string, string> | null;
|
|
45
|
+
grantId: string;
|
|
46
|
+
clientId: string;
|
|
47
|
+
credentialIds: string[];
|
|
48
|
+
budget: LinkBudget[];
|
|
49
|
+
revokedAt: number | null;
|
|
50
|
+
revokedBy: string | null;
|
|
51
|
+
usable: boolean;
|
|
52
|
+
};
|
|
53
|
+
/** A token to store: its hash, never the token. */
|
|
54
|
+
export type LinkTokenIssue = {
|
|
55
|
+
tokenHash: string;
|
|
56
|
+
kind: LinkTokenKind;
|
|
57
|
+
expiresAt: number | null;
|
|
58
|
+
pins?: LinkPin[];
|
|
59
|
+
tags?: Record<string, string>;
|
|
60
|
+
};
|
|
61
|
+
/** One request's usage as stored. */
|
|
62
|
+
export type LinkUsageRecord = Omit<LinkUsageTotals, "requests" | "errors"> & {
|
|
63
|
+
status: string | null;
|
|
64
|
+
model: string | null;
|
|
65
|
+
thinking: string | null;
|
|
66
|
+
tags: Record<string, string>;
|
|
67
|
+
};
|
|
68
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
69
|
+
/**
|
|
70
|
+
* Storage for the token protocol. Each method is one atomic step; the rules
|
|
71
|
+
* that decide between them are `linkGrants`'s.
|
|
72
|
+
*/
|
|
73
|
+
export type LinkRepo = {
|
|
74
|
+
/** The app a client id names; null for an unknown or disabled one. */
|
|
75
|
+
appRecord(clientId: string): MaybePromise<LinkAppRecord | null>;
|
|
76
|
+
/**
|
|
77
|
+
* Consume a live grant's unexpired code when the client, redirect URI, and
|
|
78
|
+
* PKCE challenge are the ones it was issued for, and store its first tokens
|
|
79
|
+
* in the same step: the grant's id, once.
|
|
80
|
+
*/
|
|
81
|
+
redeemCode(request: {
|
|
82
|
+
codeHash: string;
|
|
83
|
+
clientId: string;
|
|
84
|
+
redirectUri: string;
|
|
85
|
+
codeChallenge: string;
|
|
86
|
+
tokens: LinkTokenIssue[];
|
|
87
|
+
now: number;
|
|
88
|
+
}): MaybePromise<string | null>;
|
|
89
|
+
/** The token with this hash and its grant; null when there is none. */
|
|
90
|
+
tokenRecord(tokenHash: string): MaybePromise<LinkTokenRecord | null>;
|
|
91
|
+
/**
|
|
92
|
+
* Store tokens for a grant, all or none. With `rotate`, also mark that
|
|
93
|
+
* refresh token rotated: `race` when another request already did. `revoked`
|
|
94
|
+
* when the grant is no longer live.
|
|
95
|
+
*/
|
|
96
|
+
issueTokens(request: {
|
|
97
|
+
grantId: string;
|
|
98
|
+
tokens: LinkTokenIssue[];
|
|
99
|
+
rotate?: string;
|
|
100
|
+
now: number;
|
|
101
|
+
}): MaybePromise<"ok" | "race" | "revoked">;
|
|
102
|
+
/** Delete one token. */
|
|
103
|
+
deleteToken(tokenHash: string): MaybePromise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Revoke a grant: its code and refresh tokens go, and its access and child
|
|
106
|
+
* tokens stop working. False when none is live by that id.
|
|
107
|
+
*/
|
|
108
|
+
revokeGrant(grantId: string, by: LinkRevoker, now: number): MaybePromise<boolean>;
|
|
109
|
+
/** A grant's requests, received in the time range or the one by that id. */
|
|
110
|
+
usageRecords(grantId: string, query: Pick<LinkUsageQuery, "since" | "until" | "requestId">): MaybePromise<LinkUsageRecord[]>;
|
|
111
|
+
};
|
|
112
|
+
/** The token protocol over a platform's storage. `now` is for tests. */
|
|
113
|
+
export declare function linkGrants(repo: LinkRepo): {
|
|
114
|
+
/** What a presented access or child token is, or null when it is neither. */
|
|
115
|
+
authenticate: (token: string, now?: Date) => Promise<LinkTokenAuth | null>;
|
|
116
|
+
/** Redeem a code once: the grant's first tokens. */
|
|
117
|
+
exchangeCode(request: LinkCodeExchange, now?: Date): Promise<LinkTokens>;
|
|
118
|
+
/**
|
|
119
|
+
* A new access token for a grant. A public client's refresh token rotates;
|
|
120
|
+
* a confidential client keeps the one it presented.
|
|
121
|
+
*/
|
|
122
|
+
refresh(request: LinkClient & {
|
|
123
|
+
refreshToken: string;
|
|
124
|
+
}, now?: Date): Promise<LinkTokens>;
|
|
125
|
+
/** Mint a child token from the grant's access token (RFC 8693). */
|
|
126
|
+
exchangeToken(request: LinkTokenExchange, now?: Date): Promise<LinkChildToken>;
|
|
127
|
+
/** Revoke the grant any of its tokens names, when the client owns it (RFC 7009). */
|
|
128
|
+
revokeToken(request: LinkClient & {
|
|
129
|
+
token: string;
|
|
130
|
+
}, now?: Date): Promise<void>;
|
|
131
|
+
/**
|
|
132
|
+
* The live grant a grant's own access token names. Throws the 401 a dead
|
|
133
|
+
* token gets, and 403 for a child token, which cannot read its grant or
|
|
134
|
+
* its usage.
|
|
135
|
+
*/
|
|
136
|
+
parentGrant(accessToken: string, now?: Date): Promise<ActiveLinkGrant>;
|
|
137
|
+
/** What a grant's requests used, filtered by tags and receive time. */
|
|
138
|
+
usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Promise<Omit<LinkUsage, "completeThrough">>;
|
|
139
|
+
};
|
|
140
|
+
export type LinkGrants = ReturnType<typeof linkGrants>;
|
|
141
|
+
/** Whether a presented key is shaped like an access or child token. */
|
|
142
|
+
export declare function isLinkToken(token: string): boolean;
|
|
143
|
+
/** What a stored access or child token is now; null when it serves nothing. */
|
|
144
|
+
export declare function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null;
|
|
145
|
+
/** Totals of a grant's requests carrying every given tag, by model and optionally by one tag's values. */
|
|
146
|
+
export declare function summarizeLinkUsage(records: readonly LinkUsageRecord[], tags: Record<string, string>, groupByTag?: string): Omit<LinkUsage, "completeThrough">;
|
|
147
|
+
/** A new secret: a code, a token, or a client secret. */
|
|
148
|
+
export declare function linkSecret(prefix: string): string;
|
|
149
|
+
/** How a secret is stored. */
|
|
150
|
+
export declare function linkHash(value: string): string;
|
|
151
|
+
export {};
|