@mupt-ai/dari-gateway 1.0.320 → 1.0.322
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 +2 -2
- 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/protocol/input/router_model.js +1 -1
- package/dist/providers/pi_options.js +5 -0
- package/dist/self_host/resolve.js +6 -32
- package/dist/self_host/subscriptions/http.js +53 -7
- package/package.json +2 -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/protocol/input/router_model.ts +1 -1
- package/src/providers/pi_options.ts +4 -0
- package/src/self_host/resolve.ts +10 -47
- package/src/self_host/subscriptions/http.ts +55 -7
package/README.md
CHANGED
|
@@ -112,7 +112,7 @@ Model ids are `provider/model`. Clients send `model: "dari/routing"` to let the
|
|
|
112
112
|
export DARI_GATEWAY_URL=http://localhost:8080
|
|
113
113
|
export DARI_GATEWAY_KEY=<one of DARI_GATEWAY_KEYS>
|
|
114
114
|
|
|
115
|
-
dari
|
|
115
|
+
dari accounts subscription connect claude-code # or codex or muse-code; repeat to pool plans
|
|
116
116
|
dari claude
|
|
117
117
|
```
|
|
118
118
|
|
|
@@ -202,7 +202,7 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
202
202
|
- `response_mode=web_message`: for a page opened as a popup. The result is posted to the window that opened it (`{"type": "dari-link", "code" | "error", "state"}`, addressed to the redirect URI's origin) instead of sent on a redirect; a page with no opener left redirects to `redirect_uri` instead. `DariLink.open` does this for you.
|
|
203
203
|
- `grant_id`: update mode (above).
|
|
204
204
|
|
|
205
|
-
The gateway serves the page itself, hosted and self-hosted alike
|
|
205
|
+
The gateway serves the page itself, hosted and self-hosted alike. A new user sees what connecting means, picks a subscription (Claude, ChatGPT, Meta Muse, OpenCode Go) or a provider to add an API key for, signs in to that provider (Claude shows a code to paste back; the others take a code the page shows and continue on their own), and allows the app with what they connected ticked. A self-hosted gateway needs no sign-in: their first plan or key makes them a user. A platform with accounts (`LinkApprovalPage.signIn`; on hosted Dari, the user's Dari account) has them sign in first, and they are that account, with the plans it already has. Either way the gateway remembers them in a signed HttpOnly cookie, so the next app that asks finds their plans connected and takes one click: for a year without accounts, since the cookie is who they are; for 30 days with them, and they can sign out from the approval and connections pages. A self-hosted gateway takes their subscriptions and keys only when it encrypts what it stores (`DARI_GATEWAY_ENCRYPTION_KEY`). A plan a user connects this way is theirs alone: it serves only the grants they approve, never a gateway key, and the gateway owner's own plans are never offered on the page.
|
|
206
206
|
|
|
207
207
|
The user approves; they can later cap the tokens the app may use per 5 hours and per week (see **Budgets**). The app gets `code` and `state`, or `error=access_denied`, on `redirect_uri` or as the popup's message.
|
|
208
208
|
3. `POST /v1/link/token` (form or JSON; CORS open) with `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `code_verifier` returns an access token (`dlk_at_…`, one hour) and a refresh token (`dlk_rt_…`), with the grant's fields below. `grant_type=refresh_token` with `refresh_token` returns a new access token:
|
package/dist/link/budget.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import type { LinkBudget } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkUsageTotals } from "../platform/platform.js";
|
|
2
2
|
/** The windows a budget can cap: five hours and one week. */
|
|
3
3
|
export declare const LINK_BUDGET_WINDOW_MINUTES: readonly [300, 10080];
|
|
4
|
+
/** The tokens a request used, as each kind is recorded. */
|
|
5
|
+
export type LinkTokenCounts = Pick<LinkUsageTotals, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens">;
|
|
6
|
+
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
7
|
+
export declare function linkTokens(counts: LinkTokenCounts): number;
|
|
4
8
|
/** Tokens one of a grant's requests used, and when it was received. */
|
|
5
|
-
export type BudgetUse = {
|
|
9
|
+
export type BudgetUse = LinkTokenCounts & {
|
|
6
10
|
at: Date;
|
|
7
|
-
tokens: number;
|
|
8
11
|
};
|
|
9
12
|
/** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
|
|
10
13
|
export type BudgetStanding = {
|
package/dist/link/budget.js
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
bring it under the cap again: `resetsAt` is when that happens. */
|
|
12
12
|
/** The windows a budget can cap: five hours and one week. */
|
|
13
13
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080];
|
|
14
|
+
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
15
|
+
export function linkTokens(counts) {
|
|
16
|
+
return counts.inputTokens + counts.outputTokens + counts.cacheReadTokens + counts.cacheWriteTokens;
|
|
17
|
+
}
|
|
14
18
|
/** Each budget window as it stands, from the grant's uses. */
|
|
15
19
|
export function budgetStandings(budget, uses, now) {
|
|
16
20
|
return budget.map((entry) => {
|
|
@@ -18,13 +22,13 @@ export function budgetStandings(budget, uses, now) {
|
|
|
18
22
|
const live = uses
|
|
19
23
|
.filter((use) => use.at.getTime() > now.getTime() - windowMs)
|
|
20
24
|
.sort((a, b) => a.at.getTime() - b.at.getTime());
|
|
21
|
-
const usedTokens = live.reduce((sum, use) => sum + use
|
|
25
|
+
const usedTokens = live.reduce((sum, use) => sum + linkTokens(use), 0);
|
|
22
26
|
let resetsAt = null;
|
|
23
27
|
let remaining = usedTokens;
|
|
24
28
|
for (const use of live) {
|
|
25
29
|
if (remaining < entry.maxTokens)
|
|
26
30
|
break;
|
|
27
|
-
remaining -= use
|
|
31
|
+
remaining -= linkTokens(use);
|
|
28
32
|
resetsAt = new Date(use.at.getTime() + windowMs);
|
|
29
33
|
}
|
|
30
34
|
return { windowMinutes: entry.windowMinutes, maxTokens: entry.maxTokens, usedTokens, resetsAt };
|
package/dist/link/endpoints.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { GatewayPlatform } from "../platform/platform.js";
|
|
1
|
+
import type { GatewayPlatform, LinkPlatform } from "../platform/platform.js";
|
|
2
2
|
/** The `type` of the message a `web_message` approval posts to its opener. */
|
|
3
3
|
export declare const LINK_MESSAGE_TYPE = "dari-link";
|
|
4
4
|
export declare const LINK_EVENT_TYPE = "dari-link-event";
|
|
@@ -8,6 +8,19 @@ export declare const LINK_METADATA_PATH = "/.well-known/oauth-authorization-serv
|
|
|
8
8
|
/** The PKCE S256 challenge for a code verifier. */
|
|
9
9
|
export declare function pkceChallenge(verifier: string): string;
|
|
10
10
|
export declare function handleLinkRequest(request: Request, platform: GatewayPlatform): Promise<Response>;
|
|
11
|
+
/**
|
|
12
|
+
* An app's name, redirect URIs, and whether it is confidential, as every
|
|
13
|
+
* registration takes them; HttpError(400) for anything else.
|
|
14
|
+
*/
|
|
15
|
+
export declare function linkAppMetadata(link: Pick<LinkPlatform, "httpRedirectHosts">, body: {
|
|
16
|
+
name?: unknown;
|
|
17
|
+
redirect_uris?: unknown;
|
|
18
|
+
confidential?: unknown;
|
|
19
|
+
}): {
|
|
20
|
+
name: string;
|
|
21
|
+
redirectUris: string[];
|
|
22
|
+
confidential: boolean;
|
|
23
|
+
};
|
|
11
24
|
/**
|
|
12
25
|
* The `Cookie` header value that makes a request this user's on the approval
|
|
13
26
|
* page, for a platform's own tooling (the stub gateway approves with it).
|
package/dist/link/endpoints.js
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,14 +34,15 @@
|
|
|
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
|
|
43
|
-
|
|
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. */
|
|
45
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
44
46
|
import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
45
47
|
import { bearerToken } from "../http/auth.js";
|
|
46
48
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
@@ -50,7 +52,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
50
52
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
51
53
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
52
54
|
import { gatewayFor } from "../models/gateways.js";
|
|
53
|
-
import { budgetBody, validBudget } from "./budget.js";
|
|
55
|
+
import { budgetBody, linkTokens, validBudget } from "./budget.js";
|
|
54
56
|
import { catalogModelFor } from "./grant_access.js";
|
|
55
57
|
import { requestTags } from "../runtime/request_tags.js";
|
|
56
58
|
import { parseJsonRequest } from "../ingress/json.js";
|
|
@@ -68,12 +70,21 @@ const MAX_REGISTRATIONS_PER_MINUTE = 20;
|
|
|
68
70
|
const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
|
|
69
71
|
const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
|
|
70
72
|
const MAX_TAG_KEY_CHARS = 64;
|
|
71
|
-
// Who the approval page's user is
|
|
73
|
+
// Who the approval page's user is. Without accounts the cookie is who they
|
|
74
|
+
// are, so it lasts a year from their last plan; with accounts, a month from
|
|
75
|
+
// their sign-in, which is a click away again.
|
|
72
76
|
const USER_COOKIE = "dari_link_user";
|
|
73
77
|
const USER_SECONDS = 365 * 24 * 60 * 60;
|
|
78
|
+
const ACCOUNT_SECONDS = 30 * 24 * 60 * 60;
|
|
74
79
|
// A provider sign-in under way, for as long as providers keep one open.
|
|
75
80
|
const CONNECT_COOKIE = "dari_link_connect";
|
|
76
81
|
const CONNECT_SECONDS = 15 * 60;
|
|
82
|
+
// A sign-in at the platform under way: the state its ticket must carry.
|
|
83
|
+
const SIGN_IN_COOKIE = "dari_link_sign_in";
|
|
84
|
+
const SIGN_IN_SECONDS = 15 * 60;
|
|
85
|
+
// How long after the platform signed the user in its ticket is good.
|
|
86
|
+
const TICKET_MS = 2 * 60 * 1000;
|
|
87
|
+
const SESSION_PATH = "/v1/link/session";
|
|
77
88
|
// How often the page asks a provider whether the user approved its code.
|
|
78
89
|
const DEVICE_POLL_SECONDS = 5;
|
|
79
90
|
const AUTHORIZE_PATH = "/v1/link/authorize";
|
|
@@ -141,6 +152,9 @@ export async function handleLinkRequest(request, platform) {
|
|
|
141
152
|
if (pathname === AUTHORIZE_PATH && request.method === "POST") {
|
|
142
153
|
return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
|
|
143
154
|
}
|
|
155
|
+
if (pathname === SESSION_PATH && request.method === "GET") {
|
|
156
|
+
return await signedIn(link.approval, request, url.searchParams);
|
|
157
|
+
}
|
|
144
158
|
if (pathname === CONNECTIONS_PATH && request.method === "GET") {
|
|
145
159
|
return await connectionsPage(link.approval, request);
|
|
146
160
|
}
|
|
@@ -271,14 +285,7 @@ function isHttps(request) {
|
|
|
271
285
|
}
|
|
272
286
|
async function registerApp(link, request) {
|
|
273
287
|
const apiKey = bearerToken(request.headers);
|
|
274
|
-
const
|
|
275
|
-
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
276
|
-
throw new HttpError(400, message, "invalid_request_error", param);
|
|
277
|
-
});
|
|
278
|
-
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
279
|
-
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
280
|
-
}
|
|
281
|
-
const app = await link.registerApp({ apiKey, name, redirectUris, confidential: body.confidential === true });
|
|
288
|
+
const app = await link.registerApp({ apiKey, ...linkAppMetadata(link, await parseJsonRequest(request)) });
|
|
282
289
|
return Response.json(
|
|
283
290
|
// The secret is shown this once; only its hash is stored.
|
|
284
291
|
{ ...appBody(app), ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret }) }, { status: 201, headers: { "Cache-Control": "no-store" } });
|
|
@@ -360,6 +367,19 @@ async function registerClient(link, request) {
|
|
|
360
367
|
function registrationError(error, description) {
|
|
361
368
|
return Response.json({ error, error_description: description }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
|
362
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* An app's name, redirect URIs, and whether it is confidential, as every
|
|
372
|
+
* registration takes them; HttpError(400) for anything else.
|
|
373
|
+
*/
|
|
374
|
+
export function linkAppMetadata(link, body) {
|
|
375
|
+
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
376
|
+
throw new HttpError(400, message, "invalid_request_error", param);
|
|
377
|
+
});
|
|
378
|
+
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
379
|
+
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
380
|
+
}
|
|
381
|
+
return { name, redirectUris, confidential: body.confidential === true };
|
|
382
|
+
}
|
|
363
383
|
function validClient(link, rawName, rawRedirectUris, refuse) {
|
|
364
384
|
const name = typeof rawName === "string" ? rawName.trim() : "";
|
|
365
385
|
if (!name || name.length > MAX_APP_NAME_CHARS)
|
|
@@ -884,8 +904,9 @@ async function authorizePage(link, request, params) {
|
|
|
884
904
|
return authorize;
|
|
885
905
|
const approval = link.approval;
|
|
886
906
|
const secret = approval.sessionSecret();
|
|
887
|
-
const session = sessionFrom(request,
|
|
888
|
-
|
|
907
|
+
const session = sessionFrom(request, approval);
|
|
908
|
+
// On a platform with accounts, only a signed-in user has a provider sign-in under way.
|
|
909
|
+
const connect = session === null && approval.signIn !== undefined ? null : connectFrom(request, secret);
|
|
889
910
|
if (connect !== null) {
|
|
890
911
|
// A provider that gave the user a code to enter is asked whether they approved.
|
|
891
912
|
return connect.userCode === null
|
|
@@ -930,7 +951,10 @@ async function authorizeSubmit(link, request, form) {
|
|
|
930
951
|
return authorize;
|
|
931
952
|
const back = { redirectUri: authorize.redirectUri, state: authorize.state, webMessage: authorize.webMessage };
|
|
932
953
|
const secret = approval.sessionSecret();
|
|
933
|
-
const session = sessionFrom(request,
|
|
954
|
+
const session = sessionFrom(request, approval);
|
|
955
|
+
if (session === null && approval.signIn !== undefined && !["deny", "sign_out"].includes(form.get("decision") ?? "")) {
|
|
956
|
+
return signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
|
|
957
|
+
}
|
|
934
958
|
const endConnect = clearCookie(request, CONNECT_COOKIE);
|
|
935
959
|
// A plan's or a key provider's row on the select page is its own submit button.
|
|
936
960
|
const kind = form.get("connect");
|
|
@@ -943,6 +967,8 @@ async function authorizeSubmit(link, request, form) {
|
|
|
943
967
|
const decision = kind !== null ? "connect" : form.get("decision");
|
|
944
968
|
if (decision === "deny")
|
|
945
969
|
return redirect(back, { error: "access_denied" }, [endConnect]);
|
|
970
|
+
if (decision === "sign_out")
|
|
971
|
+
return seeAuthorize(authorize, signOutCookies(request));
|
|
946
972
|
if (decision === "select")
|
|
947
973
|
return selectPage(approval, authorize, undefined, [endConnect]);
|
|
948
974
|
if (decision === "connect") {
|
|
@@ -980,7 +1006,7 @@ async function authorizeSubmit(link, request, form) {
|
|
|
980
1006
|
throw error;
|
|
981
1007
|
return keyPage(authorize, keyProvider, error.message);
|
|
982
1008
|
}
|
|
983
|
-
return seeAuthorize(authorize, [userCookie(request,
|
|
1009
|
+
return seeAuthorize(authorize, [userCookie(request, approval, added.subject), endConnect]);
|
|
984
1010
|
}
|
|
985
1011
|
const connect = connectFrom(request, secret);
|
|
986
1012
|
if (decision === "complete" && connect !== null) {
|
|
@@ -1052,7 +1078,7 @@ async function finishConnect(approval, request, authorize, session, connect, aut
|
|
|
1052
1078
|
}
|
|
1053
1079
|
return connected === null
|
|
1054
1080
|
? providerPage(authorize, connect)
|
|
1055
|
-
: seeAuthorize(authorize, [userCookie(request, approval
|
|
1081
|
+
: seeAuthorize(authorize, [userCookie(request, approval, connected.subject), endConnect]);
|
|
1056
1082
|
}
|
|
1057
1083
|
/**
|
|
1058
1084
|
* The connections page: the apps the browser's user connected, with what each
|
|
@@ -1060,10 +1086,13 @@ async function finishConnect(approval, request, authorize, session, connect, aut
|
|
|
1060
1086
|
* and keys, each of which they can remove.
|
|
1061
1087
|
*/
|
|
1062
1088
|
async function connectionsPage(approval, request, error) {
|
|
1063
|
-
const session = sessionFrom(request, approval
|
|
1089
|
+
const session = sessionFrom(request, approval);
|
|
1064
1090
|
const title = "Connected Apps";
|
|
1065
1091
|
if (session === null) {
|
|
1066
|
-
return
|
|
1092
|
+
return approval.signIn === undefined
|
|
1093
|
+
? 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>`)
|
|
1094
|
+
: 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>
|
|
1095
|
+
<div class="foot"><button class="btn primary" type="submit" name="decision" value="sign_in">Sign In</button></div></form>`);
|
|
1067
1096
|
}
|
|
1068
1097
|
const [connections, plans] = await Promise.all([
|
|
1069
1098
|
approval.connections(session.subject),
|
|
@@ -1078,11 +1107,11 @@ async function connectionsPage(approval, request, error) {
|
|
|
1078
1107
|
${error === undefined ? "" : `<p role="alert">${escapeHtml(error)}</p>`}
|
|
1079
1108
|
${cards.length === 0 ? "<p>No apps are connected.</p>" : cards.join("\n")}
|
|
1080
1109
|
${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${planRows.join("\n")}`}
|
|
1110
|
+
${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${SIGN_OUT}</form>` : ""}
|
|
1081
1111
|
</div>`);
|
|
1082
1112
|
}
|
|
1083
1113
|
function connectionCard(connection, csrf) {
|
|
1084
|
-
const tokens = connection.usage
|
|
1085
|
-
+ connection.usage.cacheReadTokens + connection.usage.cacheWriteTokens;
|
|
1114
|
+
const tokens = linkTokens(connection.usage);
|
|
1086
1115
|
const limit = (minutes, label) => {
|
|
1087
1116
|
const standing = connection.budget.find((window) => window.windowMinutes === minutes);
|
|
1088
1117
|
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
@@ -1103,11 +1132,21 @@ async function connectionsSubmit(approval, request, form) {
|
|
|
1103
1132
|
if (crossSite(request)) {
|
|
1104
1133
|
return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open the connections page again.</p></div>`, { status: 403 });
|
|
1105
1134
|
}
|
|
1106
|
-
const
|
|
1135
|
+
const secret = approval.sessionSecret();
|
|
1136
|
+
const session = sessionFrom(request, approval);
|
|
1137
|
+
if (session === null && approval.signIn !== undefined && form.get("decision") === "sign_in") {
|
|
1138
|
+
return signIn(request, approval.signIn, secret, CONNECTIONS_PATH);
|
|
1139
|
+
}
|
|
1107
1140
|
const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
|
|
1108
1141
|
if (session === null || !sameText(form.get("csrf") ?? "", session.csrf))
|
|
1109
1142
|
return back;
|
|
1110
1143
|
const decision = form.get("decision");
|
|
1144
|
+
if (decision === "sign_out") {
|
|
1145
|
+
const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
|
|
1146
|
+
for (const cookie of signOutCookies(request))
|
|
1147
|
+
headers.append("Set-Cookie", cookie);
|
|
1148
|
+
return new Response(null, { status: 303, headers });
|
|
1149
|
+
}
|
|
1111
1150
|
const grantId = form.get("grant_id") ?? "";
|
|
1112
1151
|
if (decision === "disconnect") {
|
|
1113
1152
|
await approval.disconnect(session.subject, grantId);
|
|
@@ -1184,9 +1223,14 @@ function shareable(authorize, subscriptions) {
|
|
|
1184
1223
|
return (authorize.plans === null || authorize.plans.includes(kind)) && usableBy(kind, authorize.clients);
|
|
1185
1224
|
});
|
|
1186
1225
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1226
|
+
const SIGN_OUT = `<button class="btn ghost" type="submit" name="decision" value="sign_out" formnovalidate>Sign Out</button>`;
|
|
1227
|
+
function sessionFrom(request, approval) {
|
|
1228
|
+
const secret = approval.sessionSecret();
|
|
1229
|
+
const user = readSigned(request, secret, USER_COOKIE);
|
|
1230
|
+
// A platform with accounts knows only users its sign-in made.
|
|
1231
|
+
if (typeof user?.sub !== "string" || (approval.signIn !== undefined && user.account !== true))
|
|
1232
|
+
return null;
|
|
1233
|
+
return { subject: user.sub, csrf: sign(secret, `csrf\0${user.sub}`), account: approval.signIn !== undefined };
|
|
1190
1234
|
}
|
|
1191
1235
|
function connectFrom(request, secret) {
|
|
1192
1236
|
const value = readSigned(request, secret, CONNECT_COOKIE);
|
|
@@ -1201,6 +1245,37 @@ function connectFrom(request, secret) {
|
|
|
1201
1245
|
userCode: typeof value.code === "string" ? value.code : null,
|
|
1202
1246
|
};
|
|
1203
1247
|
}
|
|
1248
|
+
// Send the user to the platform's sign-in, which returns them to `next` (a
|
|
1249
|
+
// page of this gateway's) by way of /v1/link/session. The state, kept in a
|
|
1250
|
+
// cookie here, binds the ticket that comes back to this browser, so no one
|
|
1251
|
+
// can sign a user in as someone else.
|
|
1252
|
+
function signIn(request, platform, secret, next) {
|
|
1253
|
+
const state = randomBytes(24).toString("base64url");
|
|
1254
|
+
const url = new URL(platform.url());
|
|
1255
|
+
url.searchParams.set("state", state);
|
|
1256
|
+
url.searchParams.set("next", next);
|
|
1257
|
+
const headers = new Headers({ Location: url.toString(), "Cache-Control": "no-store" });
|
|
1258
|
+
headers.append("Set-Cookie", signedCookie(request, secret, SIGN_IN_COOKIE, { state }, SIGN_IN_SECONDS));
|
|
1259
|
+
return new Response(null, { status: 303, headers });
|
|
1260
|
+
}
|
|
1261
|
+
// The platform's sign-in returns here: a fresh ticket for this browser's state
|
|
1262
|
+
// makes the browser that user's, and the user goes on to `next`.
|
|
1263
|
+
async function signedIn(approval, request, params) {
|
|
1264
|
+
const secret = approval.sessionSecret();
|
|
1265
|
+
const state = readSigned(request, secret, SIGN_IN_COOKIE)?.state;
|
|
1266
|
+
const next = params.get("next") ?? "";
|
|
1267
|
+
const ticket = params.get("ticket") ?? "";
|
|
1268
|
+
const signed = approval.signIn === undefined || typeof state !== "string" || !ticket || !next.startsWith(LINK_ROUTE_PREFIX)
|
|
1269
|
+
? null
|
|
1270
|
+
: await approval.signIn.redeem(ticket);
|
|
1271
|
+
if (signed === null || signed.state !== state || Date.now() - signed.issuedAt > TICKET_MS) {
|
|
1272
|
+
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 });
|
|
1273
|
+
}
|
|
1274
|
+
const headers = new Headers({ Location: next, "Cache-Control": "no-store" });
|
|
1275
|
+
headers.append("Set-Cookie", userCookie(request, approval, signed.subject));
|
|
1276
|
+
headers.append("Set-Cookie", clearCookie(request, SIGN_IN_COOKIE));
|
|
1277
|
+
return new Response(null, { status: 303, headers });
|
|
1278
|
+
}
|
|
1204
1279
|
// A signed cookie's payload: `<payload>.<HMAC-SHA256>`, where the payload
|
|
1205
1280
|
// holds the value and when it ends.
|
|
1206
1281
|
function readSigned(request, secret, cookie) {
|
|
@@ -1231,9 +1306,15 @@ function signedValue(secret, cookie, value, seconds) {
|
|
|
1231
1306
|
function signedCookie(request, secret, cookie, value, seconds) {
|
|
1232
1307
|
return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${COOKIE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
1233
1308
|
}
|
|
1234
|
-
// Who the user is,
|
|
1235
|
-
function userCookie(request,
|
|
1236
|
-
return
|
|
1309
|
+
// Who the user is, from when the page last said so (see USER_COOKIE).
|
|
1310
|
+
function userCookie(request, approval, subject) {
|
|
1311
|
+
return approval.signIn === undefined
|
|
1312
|
+
? signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject }, USER_SECONDS)
|
|
1313
|
+
: signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
|
|
1314
|
+
}
|
|
1315
|
+
// Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
|
|
1316
|
+
function signOutCookies(request) {
|
|
1317
|
+
return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
|
|
1237
1318
|
}
|
|
1238
1319
|
function clearCookie(request, cookie) {
|
|
1239
1320
|
return `${cookie}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
@@ -1397,7 +1478,8 @@ function choosePage(authorize, session, subscriptions, current, error) {
|
|
|
1397
1478
|
body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
|
|
1398
1479
|
<input type="hidden" name="csrf" value="${session.csrf}">
|
|
1399
1480
|
${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
|
|
1400
|
-
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button
|
|
1481
|
+
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
|
|
1482
|
+
${session.account ? SIGN_OUT : ""}`,
|
|
1401
1483
|
footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
|
|
1402
1484
|
<p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
|
|
1403
1485
|
});
|
|
@@ -1505,7 +1587,9 @@ ${body}
|
|
|
1505
1587
|
"Cache-Control": "no-store",
|
|
1506
1588
|
"Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
|
|
1507
1589
|
"X-Frame-Options": "DENY",
|
|
1508
|
-
|
|
1590
|
+
// No other site sees these pages' URLs. Not no-referrer: under it a form
|
|
1591
|
+
// posts Origin: null, which an http gateway (sent no Sec-Fetch-Site) refuses.
|
|
1592
|
+
"Referrer-Policy": "same-origin",
|
|
1509
1593
|
});
|
|
1510
1594
|
for (const cookie of options.cookies ?? [])
|
|
1511
1595
|
headers.append("Set-Cookie", cookie);
|
package/dist/link/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { HttpError } from "../http/errors.js";
|
|
2
|
-
import type { LinkUnavailable, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
2
|
+
import type { ClientHarness, LinkUnavailable, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
3
3
|
export declare const LINK_GRANT_ERROR_CODES: readonly ["subscription_exhausted", "grant_budget_exhausted", "subscription_client_mismatch", "model_not_granted"];
|
|
4
4
|
export type LinkGrantErrorCode = (typeof LINK_GRANT_ERROR_CODES)[number];
|
|
5
5
|
export declare const LINK_TOKEN_ERROR_CODES: readonly ["link_token_expired", "grant_revoked"];
|
|
@@ -15,6 +15,25 @@ export declare function plansExhausted(plans: readonly SubscriptionKind[], reset
|
|
|
15
15
|
export declare function budgetExhausted(resetsAt: Date): LinkUnavailable;
|
|
16
16
|
/** The granted plans for a provider serve only another client. */
|
|
17
17
|
export declare function plansForAnotherClient(plans: readonly SubscriptionKind[]): LinkUnavailable;
|
|
18
|
+
/** A granted subscription, as a platform's resolve found it. */
|
|
19
|
+
export type LinkGrantedPlan = {
|
|
20
|
+
kind: SubscriptionKind;
|
|
21
|
+
unavailableUntil: Date | null;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Why a grant serves nothing for each provider in `unserved` (the request
|
|
25
|
+
* wanted it, the grant holds a plan for it, and no plan served): its plans
|
|
26
|
+
* serve only another client, or are all at their usage limits. Every
|
|
27
|
+
* platform's resolve says it this way.
|
|
28
|
+
*/
|
|
29
|
+
export declare function providersUnavailable(granted: readonly LinkGrantedPlan[], unserved: Iterable<string>, clientHarness: ClientHarness | undefined, now: Date): Record<string, LinkUnavailable>;
|
|
30
|
+
/**
|
|
31
|
+
* The error a grant that serves the request nothing gets: why its one pinned
|
|
32
|
+
* model is not served, or why none is.
|
|
33
|
+
*/
|
|
34
|
+
export declare function linkNothingServed(unavailable: Record<string, LinkUnavailable>, pins: readonly {
|
|
35
|
+
model: string;
|
|
36
|
+
}[] | null | undefined): HttpError;
|
|
18
37
|
/**
|
|
19
38
|
* Why a grant serves nothing at all: its plans are at their limits, serve
|
|
20
39
|
* only another client, or serve no model.
|
package/dist/link/errors.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
or any model the router lists. */
|
|
23
23
|
import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
24
24
|
import { HttpError } from "../http/errors.js";
|
|
25
|
+
import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
25
26
|
export const LINK_GRANT_ERROR_CODES = [
|
|
26
27
|
"subscription_exhausted",
|
|
27
28
|
"grant_budget_exhausted",
|
|
@@ -82,6 +83,40 @@ export function plansForAnotherClient(plans) {
|
|
|
82
83
|
message: `This Dari Link grant cannot serve this client: ${only.join("; ")}. Ask the user to grant a plan that serves any app, such as a ChatGPT plan.`,
|
|
83
84
|
};
|
|
84
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* Why a grant serves nothing for each provider in `unserved` (the request
|
|
88
|
+
* wanted it, the grant holds a plan for it, and no plan served): its plans
|
|
89
|
+
* serve only another client, or are all at their usage limits. Every
|
|
90
|
+
* platform's resolve says it this way.
|
|
91
|
+
*/
|
|
92
|
+
export function providersUnavailable(granted, unserved, clientHarness, now) {
|
|
93
|
+
const unavailable = {};
|
|
94
|
+
for (const provider of unserved) {
|
|
95
|
+
const plans = granted.filter((plan) => subscriptionModelProvider(plan.kind) === provider);
|
|
96
|
+
if (plans.length === 0)
|
|
97
|
+
continue;
|
|
98
|
+
const usable = plans.filter((plan) => {
|
|
99
|
+
const client = subscriptionClient(plan.kind);
|
|
100
|
+
return client === undefined || client === clientHarness;
|
|
101
|
+
});
|
|
102
|
+
if (usable.length === 0) {
|
|
103
|
+
unavailable[provider] = plansForAnotherClient(plans.map((plan) => plan.kind));
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const held = usable.flatMap((plan) => plan.unavailableUntil !== null && plan.unavailableUntil > now ? [plan.unavailableUntil] : []);
|
|
107
|
+
unavailable[provider] = plansExhausted(usable.map((plan) => plan.kind), held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null);
|
|
108
|
+
}
|
|
109
|
+
return unavailable;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The error a grant that serves the request nothing gets: why its one pinned
|
|
113
|
+
* model is not served, or why none is.
|
|
114
|
+
*/
|
|
115
|
+
export function linkNothingServed(unavailable, pins) {
|
|
116
|
+
return pins?.length === 1
|
|
117
|
+
? modelNotServed({ link_unavailable: unavailable }, pins[0].model)
|
|
118
|
+
: linkGrantUnavailableError(unavailable);
|
|
119
|
+
}
|
|
85
120
|
/**
|
|
86
121
|
* Why a grant serves nothing at all: its plans are at their limits, serve
|
|
87
122
|
* only another client, or serve no model.
|
package/dist/link/grants.d.ts
CHANGED
|
@@ -91,13 +91,15 @@ export type LinkRepo = {
|
|
|
91
91
|
/**
|
|
92
92
|
* Store tokens for a grant, all or none. With `rotate`, also mark that
|
|
93
93
|
* refresh token rotated: `race` when another request already did. `revoked`
|
|
94
|
-
* when the grant is no longer live.
|
|
94
|
+
* when the grant is no longer live. The grant's tokens that expired, or were
|
|
95
|
+
* rotated (except refresh tokens), before `forgetBefore` go.
|
|
95
96
|
*/
|
|
96
97
|
issueTokens(request: {
|
|
97
98
|
grantId: string;
|
|
98
99
|
tokens: LinkTokenIssue[];
|
|
99
100
|
rotate?: string;
|
|
100
101
|
now: number;
|
|
102
|
+
forgetBefore: number;
|
|
101
103
|
}): MaybePromise<"ok" | "race" | "revoked">;
|
|
102
104
|
/** Delete one token. */
|
|
103
105
|
deleteToken(tokenHash: string): MaybePromise<void>;
|
package/dist/link/grants.js
CHANGED
|
@@ -49,6 +49,9 @@ export function linkGrants(repo) {
|
|
|
49
49
|
tokens: kinds.map((entry, index) => ({ ...entry, tokenHash: linkHash(tokens[index]) })),
|
|
50
50
|
...(rotate === undefined ? {} : { rotate }),
|
|
51
51
|
now: now.getTime(),
|
|
52
|
+
// Rotated refresh tokens stay while the grant lives (revoking it deletes
|
|
53
|
+
// them): presenting one again is how a stolen refresh token is caught.
|
|
54
|
+
forgetBefore: now.getTime() - LINK_TOKEN_RETENTION_MS,
|
|
52
55
|
});
|
|
53
56
|
if (result === "race") {
|
|
54
57
|
throw new HttpError(400, "This refresh token was just rotated by another request. Use the tokens that request received.", "refresh_race");
|
|
@@ -4,3 +4,5 @@ import type { LinkKeyProvider } from "../platform/platform.js";
|
|
|
4
4
|
* catalog models the gateway can call with a key, then the gateways.
|
|
5
5
|
*/
|
|
6
6
|
export declare const LINK_KEY_PROVIDERS: readonly LinkKeyProvider[];
|
|
7
|
+
/** What a provider is called where a user's key for it is shown: "OpenRouter". */
|
|
8
|
+
export declare function linkKeyProviderName(provider: string): string;
|
|
@@ -19,3 +19,7 @@ export const LINK_KEY_PROVIDERS = [
|
|
|
19
19
|
.map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
|
|
20
20
|
...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway).label })),
|
|
21
21
|
];
|
|
22
|
+
/** What a provider is called where a user's key for it is shown: "OpenRouter". */
|
|
23
|
+
export function linkKeyProviderName(provider) {
|
|
24
|
+
return LINK_KEY_PROVIDERS.find((candidate) => candidate.id === provider)?.name ?? provider;
|
|
25
|
+
}
|
package/dist/link/self_hosted.js
CHANGED
|
@@ -7,7 +7,7 @@ import { checkProviderKey } from "../providers/key_check.js";
|
|
|
7
7
|
import { gatewayKeyIndex } from "../self_host/resolve.js";
|
|
8
8
|
import { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, currentUsage, startOAuth, } from "../self_host/subscriptions/index.js";
|
|
9
9
|
import { linkCompleteThrough } from "./in_flight.js";
|
|
10
|
-
import { LINK_KEY_PROVIDERS } from "./key_providers.js";
|
|
10
|
+
import { LINK_KEY_PROVIDERS, linkKeyProviderName } from "./key_providers.js";
|
|
11
11
|
import { linkPlatform } from "./service.js";
|
|
12
12
|
// A user of the approval page connects their own plans there, which serve
|
|
13
13
|
// only the grants they approve; a gateway key manages every grant, and apps
|
|
@@ -141,7 +141,7 @@ function linkKey(key) {
|
|
|
141
141
|
id: key.id,
|
|
142
142
|
provider: "api_key",
|
|
143
143
|
apiKeyProvider: key.provider,
|
|
144
|
-
name:
|
|
144
|
+
name: linkKeyProviderName(key.provider),
|
|
145
145
|
label: `Key ending ${key.apiKey.slice(-4)}`,
|
|
146
146
|
accountEmail: null,
|
|
147
147
|
unavailableUntil: null,
|
package/dist/link/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkPlanAdded, LinkPlatform, LinkSubscription } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, 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
4
|
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo } from "./grants.js";
|
|
@@ -48,6 +48,8 @@ export type LinkStore = LinkRepo & {
|
|
|
48
48
|
export type LinkUsers = {
|
|
49
49
|
/** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
|
|
50
50
|
sessionSecret(): string;
|
|
51
|
+
/** See `LinkApprovalPage.signIn`. */
|
|
52
|
+
signIn?: LinkSignIn;
|
|
51
53
|
connectable: readonly SubscriptionKind[];
|
|
52
54
|
keyProviders: readonly LinkKeyProvider[];
|
|
53
55
|
/** See `LinkPlatform.httpRedirectHosts`. */
|
|
@@ -82,6 +84,24 @@ export type LinkUsers = {
|
|
|
82
84
|
removePlan(subject: string, credentialId: string): Promise<boolean>;
|
|
83
85
|
};
|
|
84
86
|
export declare function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform;
|
|
87
|
+
/**
|
|
88
|
+
* A new app: its client id, and for a confidential one a client secret,
|
|
89
|
+
* returned this once, of which only the hash is kept. Every app is made here,
|
|
90
|
+
* whichever way it registers (hosted Dari's console included).
|
|
91
|
+
*/
|
|
92
|
+
export declare function newLinkApp(request: {
|
|
93
|
+
name: string;
|
|
94
|
+
redirectUris: string[];
|
|
95
|
+
confidential: boolean;
|
|
96
|
+
}): {
|
|
97
|
+
record: LinkAppRecord;
|
|
98
|
+
clientSecret?: string;
|
|
99
|
+
};
|
|
100
|
+
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
101
|
+
export declare function newLinkClientSecret(): {
|
|
102
|
+
secret: string;
|
|
103
|
+
hash: string;
|
|
104
|
+
};
|
|
85
105
|
/**
|
|
86
106
|
* The grant a link token serves a request for: null when the key is no link
|
|
87
107
|
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|