@mupt-ai/dari-gateway 1.0.313 → 1.0.314

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.
Files changed (71) hide show
  1. package/README.md +17 -20
  2. package/dist/http/handler.js +1 -1
  3. package/dist/ingress/anthropic_messages.js +1 -1
  4. package/dist/ingress/models.js +1 -1
  5. package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
  6. package/dist/{link_client.js → link/client.js} +5 -6
  7. package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
  8. package/dist/{ingress/link.js → link/endpoints.js} +158 -62
  9. package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
  10. package/dist/link/grants.d.ts +151 -0
  11. package/dist/link/grants.js +275 -0
  12. package/dist/link/key_providers.d.ts +6 -0
  13. package/dist/link/key_providers.js +21 -0
  14. package/dist/link/self_hosted.d.ts +3 -0
  15. package/dist/link/self_hosted.js +166 -0
  16. package/dist/link/service.d.ts +85 -0
  17. package/dist/link/service.js +187 -0
  18. package/dist/link/sqlite_store.d.ts +74 -0
  19. package/dist/link/sqlite_store.js +381 -0
  20. package/dist/models/canonical_models.json +19 -0
  21. package/dist/platform/platform.d.ts +42 -47
  22. package/dist/runtime/explicit_model.js +1 -1
  23. package/dist/runtime/prepare_routed_completion.js +1 -1
  24. package/dist/self_host/main.js +2 -2
  25. package/dist/self_host/platform.js +4 -249
  26. package/dist/self_host/resolve.d.ts +2 -2
  27. package/dist/self_host/resolve.js +3 -19
  28. package/dist/self_host/stub_gateway.js +3 -3
  29. package/dist/self_host/subscriptions/http.js +2 -2
  30. package/dist/telemetry/report.js +1 -1
  31. package/package.json +2 -2
  32. package/src/http/handler.ts +1 -1
  33. package/src/ingress/anthropic_messages.ts +1 -1
  34. package/src/ingress/models.ts +1 -1
  35. package/src/{link_client.ts → link/client.ts} +11 -14
  36. package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
  37. package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
  38. package/src/link/grants.ts +436 -0
  39. package/src/link/key_providers.ts +25 -0
  40. package/src/link/self_hosted.ts +186 -0
  41. package/src/link/service.ts +281 -0
  42. package/src/link/sqlite_store.ts +512 -0
  43. package/src/models/canonical_models.json +19 -0
  44. package/src/platform/platform.ts +39 -45
  45. package/src/runtime/explicit_model.ts +1 -1
  46. package/src/runtime/prepare_routed_completion.ts +1 -1
  47. package/src/self_host/main.ts +2 -2
  48. package/src/self_host/platform.ts +5 -267
  49. package/src/self_host/resolve.ts +6 -21
  50. package/src/self_host/stub_gateway.ts +3 -3
  51. package/src/self_host/subscriptions/http.ts +2 -2
  52. package/src/telemetry/report.ts +1 -1
  53. package/dist/self_host/link_store.d.ts +0 -167
  54. package/dist/self_host/link_store.js +0 -564
  55. package/src/self_host/link_store.ts +0 -782
  56. /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
  57. /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
  58. /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
  59. /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
  60. /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
  61. /package/dist/{models/link_errors.js → link/errors.js} +0 -0
  62. /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
  63. /package/dist/{ingress/link_font.js → link/font.js} +0 -0
  64. /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
  65. /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
  66. /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
  67. /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
  68. /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
  69. /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
  70. /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
  71. /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
@@ -8,7 +8,7 @@
8
8
  * popup, the user signs in, picks plans, and approves, and the popup closes.
9
9
  *
10
10
  * ```ts
11
- * import { DariLink } from "@mupt-ai/dari-gateway/link_client";
11
+ * import { DariLink } from "@mupt-ai/dari-gateway/link/client";
12
12
  *
13
13
  * button.onclick = async () => {
14
14
  * const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
@@ -19,7 +19,7 @@
19
19
  * Without a popup, send the user to the approval URL yourself:
20
20
  *
21
21
  * ```ts
22
- * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link_client";
22
+ * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
23
23
  *
24
24
  * const { url, codeVerifier, state } = await authorizeUrl({ gatewayUrl, clientId, redirectUri });
25
25
  * // Keep codeVerifier and state with the user's session, send them to `url`;
@@ -95,10 +95,8 @@ export type LinkTokenSet = {
95
95
  plans: LinkPlan[];
96
96
  // The models a plain API client can name now.
97
97
  models: LinkModel[];
98
- // The Dari account that approved the grant, when accounts have one.
99
- user: { email: string | null; name: string | null } | null;
100
- // Where the user manages this connection on Dari; null on a self-hosted gateway.
101
- manageUrl: string | null;
98
+ // The connections page, where the user manages this connection.
99
+ manageUrl: string;
102
100
  // Whether `dari/routing` serves a plain API client now.
103
101
  routes: boolean;
104
102
  };
@@ -254,14 +252,14 @@ const POPUP_POLL_MS = 400;
254
252
  // A closed popup may have just handed its result to `completeLink`.
255
253
  const POPUP_CLOSED_GRACE_MS = 300;
256
254
  const LINK_CHANNEL = "dari-link";
257
- const STEPS: readonly LinkStep[] = ["sign_in", "connect_subscription", "choose_plans"];
255
+ const STEPS: readonly LinkStep[] = ["connect_subscription", "choose_plans"];
258
256
 
259
257
  /**
260
- * The approval step the user reached in the popup: `sign_in`,
261
- * `connect_subscription` (no plan to share yet), or `choose_plans`. A user who
262
- * denies leaves at `denied`.
258
+ * The approval step the user reached in the popup: `connect_subscription`
259
+ * (no plan to share yet) or `choose_plans`. A user who denies leaves at
260
+ * `denied`.
263
261
  */
264
- export type LinkStep = "sign_in" | "connect_subscription" | "choose_plans" | "denied";
262
+ export type LinkStep = "connect_subscription" | "choose_plans" | "denied";
265
263
 
266
264
  /** Why the popup ended without a code, and the step the user left at (null before any). */
267
265
  export type LinkExit = { error: string; step: LinkStep | null };
@@ -478,7 +476,7 @@ export function renderButton(
478
476
  export const DariLink = { open: openLink, callback: completeLink, renderButton };
479
477
 
480
478
  // The origin the approval page posts its result from, as the gateway's
481
- // metadata names it: the gateway itself, or its platform's consent page.
479
+ // metadata names it: the gateway's public origin.
482
480
  async function approvalOrigin(args: Gateway): Promise<string> {
483
481
  const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/.well-known/oauth-authorization-server"));
484
482
  const origin = (await json(response)).web_message_origin;
@@ -733,8 +731,7 @@ function tokenSet(payload: Record<string, unknown>): LinkTokenSet {
733
731
  plans: Array.isArray(payload.plans) ? payload.plans as LinkPlan[] : [],
734
732
  models: Array.isArray(payload.models) ? payload.models as LinkModel[] : [],
735
733
  routes: payload.routes === true,
736
- user: typeof payload.user === "object" && payload.user !== null ? payload.user as LinkTokenSet["user"] : null,
737
- manageUrl: typeof payload.manage_url === "string" ? payload.manage_url : null,
734
+ manageUrl: String(payload.manage_url),
738
735
  };
739
736
  }
740
737
 
@@ -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 and validates its parameters; the platform
4
- (GatewayPlatform.link) authenticates users and clients and stores apps,
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. A platform with its own
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,10 +35,11 @@
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 an opaque subject the gateway keeps in a signed, HttpOnly,
36
- SameSite=Lax cookie scoped to the authorize path, so the next app that asks
37
- finds their plans connected. Approving needs that cookie and a form token
38
- derived from it, so another site cannot approve. */
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
 
40
44
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
41
45
 
@@ -43,7 +47,7 @@ import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy
43
47
 
44
48
  import { bearerToken } from "../http/auth.js";
45
49
  import { errorResponse, HttpError } from "../http/errors.js";
46
- import { SUBSCRIPTION_PLAN_LABELS } from "../models/link_errors.js";
50
+ import { SUBSCRIPTION_PLAN_LABELS } from "./errors.js";
47
51
  import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
48
52
  import type {
49
53
  GatewayPlatform,
@@ -51,6 +55,8 @@ import type {
51
55
  LinkApprovalPage,
52
56
  LinkClient,
53
57
  LinkConnect,
58
+ LinkConnection,
59
+ LinkPlanAdded,
54
60
  LinkGrantDetail,
55
61
  LinkKeyProvider,
56
62
  LinkUsageTotals,
@@ -64,13 +70,13 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
64
70
  import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
65
71
  import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
66
72
  import { gatewayFor } from "../models/gateways.js";
67
- import { budgetBody, validBudget } from "../runtime/link_budget.js";
68
- import { catalogModelFor } from "../runtime/link_grant_access.js";
73
+ import { budgetBody, validBudget } from "./budget.js";
74
+ import { catalogModelFor } from "./grant_access.js";
69
75
  import { requestTags } from "../runtime/request_tags.js";
70
76
  import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
71
- import { parseJsonRequest } from "./json.js";
72
- import { DARI_MARK, ICONS, linkLogo } from "./link_assets.js";
73
- import { GEIST_WOFF2 } from "./link_font.js";
77
+ import { parseJsonRequest } from "../ingress/json.js";
78
+ import { DARI_MARK, ICONS, linkLogo } from "./assets.js";
79
+ import { GEIST_WOFF2 } from "./font.js";
74
80
 
75
81
  const VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
76
82
  // The base64url SHA-256 of a verifier.
@@ -93,6 +99,9 @@ const CONNECT_SECONDS = 15 * 60;
93
99
  // How often the page asks a provider whether the user approved its code.
94
100
  const DEVICE_POLL_SECONDS = 5;
95
101
  const AUTHORIZE_PATH = "/v1/link/authorize";
102
+ const CONNECTIONS_PATH = "/v1/link/connections";
103
+ // Where the pages' cookies are sent.
104
+ const COOKIE_PATH = "/v1/link/";
96
105
  const CALLBACK_SCRIPT_PATH = "/v1/link/callback.js";
97
106
  // The approval page's typeface.
98
107
  const FONT_PATH = "/v1/link/geist.woff2";
@@ -160,6 +169,12 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
160
169
  if (pathname === AUTHORIZE_PATH && request.method === "POST") {
161
170
  return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
162
171
  }
172
+ if (pathname === CONNECTIONS_PATH && request.method === "GET") {
173
+ return await connectionsPage(link.approval, request);
174
+ }
175
+ if (pathname === CONNECTIONS_PATH && request.method === "POST") {
176
+ return await connectionsSubmit(link.approval, request, new URLSearchParams(await request.text()));
177
+ }
163
178
  if (request.method === "OPTIONS" && (CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname))) {
164
179
  return withCors(new Response(null, { status: 204 }));
165
180
  }
@@ -253,16 +268,15 @@ function metadata(origin: string, link: LinkPlatform) {
253
268
  authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
254
269
  response_modes_supported: ["query", WEB_MESSAGE],
255
270
  // The origin a `web_message` result is posted from: the page that approves.
256
- web_message_origin: "consentUrl" in link.approval ? new URL(link.approval.consentUrl).origin : origin,
271
+ web_message_origin: origin,
257
272
  token_endpoint: `${origin}/v1/link/token`,
258
273
  registration_endpoint: `${origin}/v1/link/register`,
259
274
  revocation_endpoint: `${origin}/v1/link/revoke`,
260
275
  // A script for the redirect URI's page that hands an approval back to the
261
276
  // window that opened the popup (see the README's callback contract).
262
277
  callback_script: `${origin}${CALLBACK_SCRIPT_PATH}`,
263
- // Where users manage the apps they connected; null when the platform has
264
- // no signed-in app for it.
265
- connected_apps_uri: "consentUrl" in link.approval ? link.approval.connectedAppsUrl : null,
278
+ // Where users manage the apps they connected.
279
+ connected_apps_uri: `${origin}${CONNECTIONS_PATH}`,
266
280
  response_types_supported: ["code"],
267
281
  grant_types_supported: ["authorization_code", "refresh_token", TOKEN_EXCHANGE_GRANT],
268
282
  code_challenge_methods_supported: ["S256"],
@@ -481,7 +495,7 @@ async function token(platform: GatewayPlatform, link: LinkPlatform, request: Req
481
495
  if (!VERIFIER.test(verifier)) {
482
496
  return oauthError("invalid_request", "code_verifier must be 43 to 128 unreserved characters.");
483
497
  }
484
- return await tokenResponse(platform, link, await link.exchangeCode({
498
+ return await tokenResponse(platform, link, request, await link.exchangeCode({
485
499
  ...client,
486
500
  code,
487
501
  redirectUri,
@@ -491,7 +505,7 @@ async function token(platform: GatewayPlatform, link: LinkPlatform, request: Req
491
505
  if (grantType === "refresh_token") {
492
506
  const refreshToken = body.get("refresh_token") ?? "";
493
507
  if (!refreshToken) return oauthError("invalid_request", "refresh_token is required.");
494
- return await tokenResponse(platform, link, await link.refresh({ ...client, refreshToken }));
508
+ return await tokenResponse(platform, link, request, await link.refresh({ ...client, refreshToken }));
495
509
  }
496
510
  if (grantType === TOKEN_EXCHANGE_GRANT) return await childToken(platform, link, client, body);
497
511
  return oauthError(
@@ -631,7 +645,7 @@ async function revoke(link: LinkPlatform, request: Request): Promise<Response> {
631
645
  async function grant(platform: GatewayPlatform, link: LinkPlatform, request: Request): Promise<Response> {
632
646
  const accessToken = bearerToken(request.headers);
633
647
  const detail = await link.grant(accessToken);
634
- return Response.json(await grantBody(platform, accessToken, detail), { headers: { "Cache-Control": "no-store" } });
648
+ return Response.json(await grantBody(platform, request, accessToken, detail), { headers: { "Cache-Control": "no-store" } });
635
649
  }
636
650
 
637
651
  /**
@@ -707,14 +721,14 @@ function stringFields(body: Record<string, unknown>): Record<string, string> {
707
721
  );
708
722
  }
709
723
 
710
- async function tokenResponse(platform: GatewayPlatform, link: LinkPlatform, tokens: LinkTokens): Promise<Response> {
724
+ async function tokenResponse(platform: GatewayPlatform, link: LinkPlatform, request: Request, tokens: LinkTokens): Promise<Response> {
711
725
  return Response.json(
712
726
  {
713
727
  access_token: tokens.accessToken,
714
728
  token_type: "Bearer",
715
729
  expires_in: tokens.expiresIn,
716
730
  refresh_token: tokens.refreshToken,
717
- ...(await grantBody(platform, tokens.accessToken, await link.grant(tokens.accessToken))),
731
+ ...(await grantBody(platform, request, tokens.accessToken, await link.grant(tokens.accessToken))),
718
732
  },
719
733
  { headers: { "Cache-Control": "no-store", Pragma: "no-cache" } },
720
734
  );
@@ -726,8 +740,7 @@ async function tokenResponse(platform: GatewayPlatform, link: LinkPlatform, toke
726
740
  * `models` is what a plain API client (anything but Claude Code or Muse Code)
727
741
  * can name, and `routes` whether `dari/routing` serves it.
728
742
  */
729
- async function grantBody(platform: GatewayPlatform, accessToken: string, detail: LinkGrantDetail) {
730
- const approval = platform.link?.approval;
743
+ async function grantBody(platform: GatewayPlatform, request: Request, accessToken: string, detail: LinkGrantDetail) {
731
744
  const now = Date.now();
732
745
  const kinds = detail.subscriptions
733
746
  .filter((subscription) => subscription.apiKeyProvider === undefined)
@@ -752,10 +765,8 @@ async function grantBody(platform: GatewayPlatform, accessToken: string, detail:
752
765
  })),
753
766
  // `budget_limit` while a window is at its cap, until `available_at`.
754
767
  ...grantState(detail.budget),
755
- // The Dari account that approved the grant, when accounts have one.
756
- user: detail.user,
757
- // Where the user manages this grant; null without a signed-in app.
758
- manage_url: approval !== undefined && "consentUrl" in approval ? manageUrl(approval.connectedAppsUrl, detail.id) : null,
768
+ // Where the user manages this grant: the connections page, in the browser they approved it in.
769
+ manage_url: `${publicOrigin(request)}${CONNECTIONS_PATH}#${encodeURIComponent(detail.id)}`,
759
770
  plans: detail.subscriptions.map((subscription) => {
760
771
  // An API key serves its provider's models to any app.
761
772
  const keyFor = subscription.apiKeyProvider;
@@ -790,12 +801,6 @@ async function grantBody(platform: GatewayPlatform, accessToken: string, detail:
790
801
  };
791
802
  }
792
803
 
793
- function manageUrl(connectedAppsUrl: string, grantId: string): string {
794
- const url = new URL(connectedAppsUrl);
795
- url.searchParams.set("grant", grantId);
796
- return url.toString();
797
- }
798
-
799
804
  /** The latest of some times, or null for none. */
800
805
  function latest(times: readonly string[]): string | null {
801
806
  return times.reduce<string | null>((last, time) => last === null || Date.parse(time) > Date.parse(last) ? time : last, null);
@@ -980,18 +985,10 @@ async function authorizePage(link: LinkPlatform, request: Request, params: URLSe
980
985
  const authorize = await authorizeRequest(link, params);
981
986
  if (authorize instanceof Response) return authorize;
982
987
  const approval = link.approval;
983
- if ("consentUrl" in approval) {
984
- // The platform's own page signs the user in and approves; it gets the
985
- // request as validated here.
986
- return new Response(null, {
987
- status: 303,
988
- headers: { Location: `${approval.consentUrl}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" },
989
- });
990
- }
991
988
  const secret = approval.sessionSecret();
992
989
  const session = sessionFrom(request, secret);
993
- const connect = session === null ? null : connectFrom(request, secret);
994
- if (session !== null && connect !== null) {
990
+ const connect = connectFrom(request, secret);
991
+ if (connect !== null) {
995
992
  // A provider that gave the user a code to enter is asked whether they approved.
996
993
  return connect.userCode === null
997
994
  ? providerPage(authorize, connect)
@@ -1029,9 +1026,7 @@ async function grantToUpdate(
1029
1026
  type GrantToUpdate = { credentialIds: string[]; budget: LinkBudget[] };
1030
1027
 
1031
1028
  async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSearchParams): Promise<Response> {
1032
- // A platform with its own consent page takes no approval here.
1033
- if ("consentUrl" in link.approval) return errorResponse(new HttpError(404, "Not found", "not_found"));
1034
- const approval: LinkApprovalPage = link.approval;
1029
+ const approval = link.approval;
1035
1030
  // Only the page itself submits here: another site's form would otherwise
1036
1031
  // arrive without the user's cookie and replace it with a new identity.
1037
1032
  if (crossSite(request)) {
@@ -1058,11 +1053,9 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1058
1053
  if (!connectKinds(approval, authorize).includes(kind as SubscriptionKind)) {
1059
1054
  return selectPage(approval, authorize, "Choose a subscription to connect.", [endConnect]);
1060
1055
  }
1061
- // A first plan makes the user: an opaque subject the cookie remembers.
1062
- const subject = session?.subject ?? `lu_${randomUUID().replaceAll("-", "")}`;
1063
1056
  let started: LinkConnect;
1064
1057
  try {
1065
- started = await approval.startConnect(subject, kind as SubscriptionKind);
1058
+ started = await approval.startConnect(kind as SubscriptionKind);
1066
1059
  } catch (error) {
1067
1060
  if (!(error instanceof HttpError)) throw error;
1068
1061
  // A gateway that cannot take subscriptions says why; anything else is the provider.
@@ -1070,7 +1063,6 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1070
1063
  return selectPage(approval, authorize, reason, [endConnect]);
1071
1064
  }
1072
1065
  return seeAuthorize(authorize, [
1073
- signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS),
1074
1066
  signedCookie(
1075
1067
  request,
1076
1068
  secret,
@@ -1084,17 +1076,18 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1084
1076
  if (keyProvider === undefined) return selectPage(approval, authorize, "Choose a provider to add a key for.", [endConnect]);
1085
1077
  const apiKey = form.get("api_key")?.trim() ?? "";
1086
1078
  if (!apiKey) return keyPage(authorize, keyProvider, `Paste your ${keyProvider.name} API key.`);
1087
- const subject = session?.subject ?? `lu_${randomUUID().replaceAll("-", "")}`;
1079
+ // A first plan makes the user, whom the cookie remembers.
1080
+ let added;
1088
1081
  try {
1089
- await approval.addKey(subject, keyProvider.id, apiKey);
1082
+ added = await approval.addKey(session?.subject ?? null, keyProvider.id, apiKey);
1090
1083
  } catch (error) {
1091
1084
  if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "link_not_configured")) throw error;
1092
1085
  return keyPage(authorize, keyProvider, error.message);
1093
1086
  }
1094
- return seeAuthorize(authorize, [signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS), endConnect]);
1087
+ return seeAuthorize(authorize, [userCookie(request, secret, added.subject), endConnect]);
1095
1088
  }
1096
- const connect = session === null ? null : connectFrom(request, secret);
1097
- if (decision === "complete" && session !== null && connect !== null) {
1089
+ const connect = connectFrom(request, secret);
1090
+ if (decision === "complete" && connect !== null) {
1098
1091
  return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
1099
1092
  }
1100
1093
  // Removing a plan or key asks once, then deletes what Dari stored for it.
@@ -1145,14 +1138,15 @@ async function finishConnect(
1145
1138
  approval: LinkApprovalPage,
1146
1139
  request: Request,
1147
1140
  authorize: AuthorizeRequest,
1148
- session: Session,
1141
+ session: Session | null,
1149
1142
  connect: Connect,
1150
1143
  authorizationResponse: string,
1151
1144
  ): Promise<Response> {
1152
1145
  const endConnect = clearCookie(request, CONNECT_COOKIE);
1153
- let connected: { credentialId: string } | null;
1146
+ let connected: LinkPlanAdded | null;
1154
1147
  try {
1155
- connected = await approval.completeConnect(session.subject, connect.session, authorizationResponse);
1148
+ // A first plan makes the user, whom the cookie remembers.
1149
+ connected = await approval.completeConnect(session?.subject ?? null, connect.session, authorizationResponse);
1156
1150
  } catch (error) {
1157
1151
  if (!(error instanceof HttpError) || error.status !== 400) throw error;
1158
1152
  // A pasted code can be pasted again; a sign-in the provider ended starts over.
@@ -1160,7 +1154,110 @@ async function finishConnect(
1160
1154
  ? providerPage(authorize, connect, error.message)
1161
1155
  : selectPage(approval, authorize, error.message, [endConnect]);
1162
1156
  }
1163
- return connected === null ? providerPage(authorize, connect) : seeAuthorize(authorize, [endConnect]);
1157
+ return connected === null
1158
+ ? providerPage(authorize, connect)
1159
+ : seeAuthorize(authorize, [userCookie(request, approval.sessionSecret(), connected.subject), endConnect]);
1160
+ }
1161
+
1162
+ /**
1163
+ * The connections page: the apps the browser's user connected, with what each
1164
+ * shares and used so far, its budget, and Disconnect; then the user's plans
1165
+ * and keys, each of which they can remove.
1166
+ */
1167
+ async function connectionsPage(approval: LinkApprovalPage, request: Request, error?: string): Promise<Response> {
1168
+ const session = sessionFrom(request, approval.sessionSecret());
1169
+ const title = "Connected Apps";
1170
+ if (session === null) {
1171
+ 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>`);
1172
+ }
1173
+ const [connections, plans] = await Promise.all([
1174
+ approval.connections(session.subject),
1175
+ approval.subscriptions(session.subject),
1176
+ ]);
1177
+ const csrf = `<input type="hidden" name="csrf" value="${session.csrf}">`;
1178
+ const cards = connections.map((connection) => connectionCard(connection, csrf));
1179
+ const planRows = plans.map((plan) => `<form class="option pick" method="post" action="${CONNECTIONS_PATH}">${csrf}
1180
+ <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>`);
1181
+ return page(
1182
+ title,
1183
+ `<div class="body">
1184
+ <h1>${title}</h1>
1185
+ ${error === undefined ? "" : `<p role="alert">${escapeHtml(error)}</p>`}
1186
+ ${cards.length === 0 ? "<p>No apps are connected.</p>" : cards.join("\n")}
1187
+ ${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${planRows.join("\n")}`}
1188
+ </div>`,
1189
+ );
1190
+ }
1191
+
1192
+ function connectionCard(connection: LinkConnection, csrf: string): string {
1193
+ const tokens = connection.usage.inputTokens + connection.usage.outputTokens
1194
+ + connection.usage.cacheReadTokens + connection.usage.cacheWriteTokens;
1195
+ const limit = (minutes: number, label: string) => {
1196
+ const standing = connection.budget.find((window) => window.windowMinutes === minutes);
1197
+ return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
1198
+ <input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
1199
+ ${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
1200
+ };
1201
+ return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
1202
+ <input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
1203
+ <strong>${escapeHtml(connection.appName)}</strong>
1204
+ <small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} &middot; ${count(connection.usage.requests)} requests &middot; ${count(tokens)} tokens</small>
1205
+ <small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
1206
+ ${limit(300, "Per 5 Hours")}
1207
+ ${limit(10080, "Per Week")}
1208
+ <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>
1209
+ </form>`;
1210
+ }
1211
+
1212
+ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, form: URLSearchParams): Promise<Response> {
1213
+ if (crossSite(request)) {
1214
+ return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open the connections page again.</p></div>`, { status: 403 });
1215
+ }
1216
+ const session = sessionFrom(request, approval.sessionSecret());
1217
+ const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
1218
+ if (session === null || !sameText(form.get("csrf") ?? "", session.csrf)) return back;
1219
+ const decision = form.get("decision");
1220
+ const grantId = form.get("grant_id") ?? "";
1221
+ if (decision === "disconnect") {
1222
+ await approval.disconnect(session.subject, grantId);
1223
+ return back;
1224
+ }
1225
+ if (decision === "budget") {
1226
+ const entries = [300, 10080].flatMap((minutes) => {
1227
+ const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
1228
+ return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
1229
+ });
1230
+ const budget = validBudget(entries);
1231
+ if (budget === null) return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
1232
+ await approval.setBudget(session.subject, grantId, budget);
1233
+ return back;
1234
+ }
1235
+ const removing = form.get("remove_id");
1236
+ const plan = removing === null ? undefined : (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
1237
+ if (plan !== undefined && decision === "remove") {
1238
+ const name = planName(plan);
1239
+ return page(`Remove ${name}`, `<form method="post" action="${CONNECTIONS_PATH}"><div class="body">
1240
+ <span class="who">${logo(plan.apiKeyProvider ?? plan.provider, name)}</span>
1241
+ <h1>Remove ${escapeHtml(name)}</h1>
1242
+ <p>${escapeHtml(planLabel(plan))}</p>
1243
+ <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>
1244
+ <input type="hidden" name="csrf" value="${session.csrf}">
1245
+ <input type="hidden" name="remove_id" value="${escapeHtml(plan.id)}">
1246
+ </div><div class="foot"><button class="btn danger" type="submit" name="decision" value="remove_confirmed">Remove</button></div></form>`);
1247
+ }
1248
+ if (plan !== undefined && decision === "remove_confirmed") await approval.remove(session.subject, plan.id);
1249
+ return back;
1250
+ }
1251
+
1252
+ // What a plan or key is called: "Claude", or "OpenRouter API Key".
1253
+ function planName(subscription: LinkSubscription): string {
1254
+ return subscription.apiKeyProvider !== undefined
1255
+ ? `${subscription.name} API Key`
1256
+ : KINDS[subscription.provider as SubscriptionKind]?.name ?? subscription.name;
1257
+ }
1258
+
1259
+ function count(value: number): string {
1260
+ return value.toLocaleString("en-US");
1164
1261
  }
1165
1262
 
1166
1263
  // Back to the approval page by GET, so no form is left to resubmit.
@@ -1255,11 +1352,16 @@ function signedValue(secret: string, cookie: string, value: Record<string, unkno
1255
1352
  }
1256
1353
 
1257
1354
  function signedCookie(request: Request, secret: string, cookie: string, value: Record<string, unknown>, seconds: number): string {
1258
- return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${AUTHORIZE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1355
+ return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${COOKIE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1356
+ }
1357
+
1358
+ // Who the user is, for a year from their last plan.
1359
+ function userCookie(request: Request, secret: string, subject: string): string {
1360
+ return signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS);
1259
1361
  }
1260
1362
 
1261
1363
  function clearCookie(request: Request, cookie: string): string {
1262
- return `${cookie}=; Path=${AUTHORIZE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1364
+ return `${cookie}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1263
1365
  }
1264
1366
 
1265
1367
  /**
@@ -1319,11 +1421,10 @@ function queryRedirect(back: { redirectUri: string; state: string | null }, para
1319
1421
  * The step of approval the user reached, which a popup posts to the window
1320
1422
  * that opened it (`{type: "dari-link-event", version: 1, event, state}`; the
1321
1423
  * result alone is `type: "dari-link"`), so the app can tell where the user
1322
- * left: `connect_subscription` (connecting a plan) or `choose_plans`. A
1323
- * platform with its own consent page may also post `sign_in`. A user who
1324
- * denies leaves at `denied`, which the `access_denied` result says.
1424
+ * left: `connect_subscription` (connecting a plan) or `choose_plans`. A user
1425
+ * who denies leaves at `denied`, which the `access_denied` result says.
1325
1426
  */
1326
- export type LinkStep = "sign_in" | "connect_subscription" | "choose_plans";
1427
+ export type LinkStep = "connect_subscription" | "choose_plans";
1327
1428
  type PageEvent = { message: Record<string, string>; origin: string };
1328
1429
 
1329
1430
  function eventFor(authorize: AuthorizeRequest, step: LinkStep): PageEvent | undefined {
@@ -1667,6 +1768,8 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
1667
1768
  .btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
1668
1769
  .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)}
1669
1770
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1771
+ .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}
1772
+ .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
1670
1773
  .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}
1671
1774
  .nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
1672
1775
  .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,5 +1,5 @@
1
1
  import type { InteractionRequest } from "../interaction/types.js";
2
- import { linkGrantError, modelNotServed } from "../models/link_errors.js";
2
+ import { linkGrantError, modelNotServed } from "./errors.js";
3
3
  import { CANONICAL_MODELS } from "../models/canonical.js";
4
4
  import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
5
5
  import { modelMetadataLookup } from "../providers/pi.js";