@mupt-ai/dari-gateway 1.0.342 → 1.0.344

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.
@@ -191,6 +191,35 @@ export async function authorizeUrl(args: AuthorizeOptions): Promise<{ url: strin
191
191
  return { url: authorizationUrl({ ...args, codeChallenge, state }), codeVerifier, state };
192
192
  }
193
193
 
194
+ /**
195
+ * On your server: a link token for one user's `DariLink.open`, as Plaid's
196
+ * `/link/token/create`. It carries what Link offers and lasts four hours.
197
+ * `redirectUri` defaults to the first one the app registered; `grantId`
198
+ * opens Link on that grant to change its plans (update mode).
199
+ */
200
+ export async function createLinkToken(
201
+ args: Client & { clientSecret: string } & Omit<AuthorizeOptions, "gatewayUrl" | "clientId" | "redirectUri" | "state" | "responseMode"> & {
202
+ redirectUri?: string;
203
+ },
204
+ ): Promise<{ linkToken: string; expiration: string }> {
205
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/v1/link/link_token/create"), {
206
+ method: "POST",
207
+ headers: { "content-type": "application/json" },
208
+ body: JSON.stringify({
209
+ client_id: args.clientId,
210
+ secret: args.clientSecret,
211
+ ...(args.redirectUri ? { redirect_uri: args.redirectUri } : {}),
212
+ ...(args.plans?.length ? { plans: args.plans } : {}),
213
+ ...(args.clients?.length ? { client: args.clients } : {}),
214
+ ...(args.keyProviders?.length ? { key_providers: args.keyProviders } : {}),
215
+ ...(args.purposes ? { purposes: args.purposes } : {}),
216
+ ...(args.grantId ? { grant_id: args.grantId } : {}),
217
+ }),
218
+ });
219
+ const body = await json(response);
220
+ return { linkToken: String(body.link_token), expiration: String(body.expiration) };
221
+ }
222
+
194
223
  export type AuthorizeOptions = {
195
224
  gatewayUrl: string;
196
225
  clientId: string;
@@ -278,11 +307,7 @@ export type LinkStep = "connect_subscription" | "choose_plans" | "denied";
278
307
  /** Why the popup ended without a code, and the step the user left at (null before any). */
279
308
  export type LinkExit = { error: string; step: LinkStep | null };
280
309
 
281
- export type OpenLinkOptions = AuthorizeOptions & {
282
- // A PKCE challenge and state your server made with `createAuthorization`
283
- // (recommended for a server app): the verifier stays on the server, the page
284
- // needs no Web Crypto, and the result's `codeVerifier` is null.
285
- codeChallenge?: string;
310
+ type LinkCallbacks = {
286
311
  fetch?: Fetch;
287
312
  window?: LinkBrowser;
288
313
  // Each step the user reaches, as they reach it.
@@ -291,6 +316,19 @@ export type OpenLinkOptions = AuthorizeOptions & {
291
316
  onExit?: (exit: LinkExit) => void;
292
317
  };
293
318
 
319
+ /**
320
+ * `{ gatewayUrl, linkToken }` with a token from `createLinkToken` (a server
321
+ * app); or the authorize options themselves, for an app with no server.
322
+ */
323
+ export type OpenLinkOptions = ({ gatewayUrl: string; linkToken: string } & LinkCallbacks) | PublicLinkOptions;
324
+
325
+ type PublicLinkOptions = AuthorizeOptions & LinkCallbacks & {
326
+ // A PKCE challenge and state your server made with `createAuthorization`
327
+ // (recommended for a server app): the verifier stays on the server, the page
328
+ // needs no Web Crypto, and the result's `codeVerifier` is null.
329
+ codeChallenge?: string;
330
+ };
331
+
294
332
  /**
295
333
  * Open Dari's approval page in a popup and resolve with the code once the
296
334
  * user approves. Call it from a click handler, so the browser allows the
@@ -320,7 +358,7 @@ export async function openLink(
320
358
  // Making PKCE in the page needs Web Crypto, which browsers give only to
321
359
  // https (or localhost) pages; a challenge from the server needs none.
322
360
  const insecure = (args: OpenLinkOptions) =>
323
- args.codeChallenge === undefined && (browser.isSecureContext === false || globalThis.crypto?.subtle === undefined);
361
+ !("linkToken" in args) && args.codeChallenge === undefined && (browser.isSecureContext === false || globalThis.crypto?.subtle === undefined);
324
362
  const insecureError = () => new LinkError(
325
363
  "insecure_context",
326
364
  "Connect with Dari needs a secure page (https, or localhost) to make its PKCE pair, or a codeChallenge and state from your server.",
@@ -351,16 +389,7 @@ export async function openLink(
351
389
  args.onExit?.({ error: "insecure_context", step: null });
352
390
  throw insecureError();
353
391
  }
354
- const supplied = args.codeChallenge;
355
- if (supplied !== undefined && args.state === undefined) {
356
- throw new LinkError("invalid_request", "Pass the state your server made with the codeChallenge.", 0);
357
- }
358
- [request, origin] = await Promise.all([
359
- supplied !== undefined
360
- ? { url: authorizationUrl({ ...args, codeChallenge: supplied, state: args.state!, responseMode: "web_message" }), codeVerifier: null, state: args.state! }
361
- : authorizeUrl({ ...args, responseMode: "web_message" }),
362
- approvalOrigin(args),
363
- ]);
392
+ [request, origin] = await Promise.all([linkRequest(args), approvalOrigin(args)]);
364
393
  } catch (error) {
365
394
  popup.close();
366
395
  throw error;
@@ -426,6 +455,26 @@ export async function openLink(
426
455
  });
427
456
  }
428
457
 
458
+ // The approval URL to open, and the state its result comes back with.
459
+ async function linkRequest(args: OpenLinkOptions): Promise<{ url: string; codeVerifier: string | null; state: string }> {
460
+ if ("linkToken" in args) {
461
+ const url = new URL(endpoint(args.gatewayUrl, "/v1/link/authorize"));
462
+ url.search = new URLSearchParams({ link_token: args.linkToken, response_mode: "web_message" }).toString();
463
+ // The gateway returns the link token as the state.
464
+ return { url: url.toString(), codeVerifier: null, state: args.linkToken };
465
+ }
466
+ const supplied = args.codeChallenge;
467
+ if (supplied === undefined) return await authorizeUrl({ ...args, responseMode: "web_message" });
468
+ if (args.state === undefined) {
469
+ throw new LinkError("invalid_request", "Pass the state your server made with the codeChallenge.", 0);
470
+ }
471
+ return {
472
+ url: authorizationUrl({ ...args, codeChallenge: supplied, state: args.state, responseMode: "web_message" }),
473
+ codeVerifier: null,
474
+ state: args.state,
475
+ };
476
+ }
477
+
429
478
  /**
430
479
  * On your redirect URI's page: hand an approval that arrived there in the
431
480
  * popup to the window that called `DariLink.open`, and close the popup.
@@ -497,15 +546,19 @@ async function approvalOrigin(args: Gateway): Promise<string> {
497
546
  return typeof origin === "string" ? origin : new URL(args.gatewayUrl).origin;
498
547
  }
499
548
 
500
- /** Redeem the code from the approval redirect for the grant's first tokens. */
549
+ /**
550
+ * Redeem the code `DariLink.open` returned for the grant's first tokens. A
551
+ * code from a link token needs only your client secret; one from an
552
+ * authorize URL also needs its `redirectUri` and `codeVerifier`.
553
+ */
501
554
  export async function exchange(
502
- args: Client & { redirectUri: string; code: string; codeVerifier: string },
555
+ args: Client & { code: string; redirectUri?: string; codeVerifier?: string },
503
556
  ): Promise<LinkTokenSet> {
504
557
  return tokenSet(await tokenCall(args, {
505
558
  grant_type: "authorization_code",
506
- redirect_uri: args.redirectUri,
507
559
  code: args.code,
508
- code_verifier: args.codeVerifier,
560
+ ...(args.redirectUri ? { redirect_uri: args.redirectUri } : {}),
561
+ ...(args.codeVerifier ? { code_verifier: args.codeVerifier } : {}),
509
562
  }));
510
563
  }
511
564
 
@@ -616,20 +669,20 @@ export type LinkUsageTotals = {
616
669
  // Requests the provider or Dari failed; they count in `requests` too.
617
670
  errors: number;
618
671
  // Excludes cache reads and writes, whatever protocol the requests spoke.
619
- input_tokens: number;
620
- output_tokens: number;
621
- cache_read_tokens: number;
622
- cache_write_tokens: number;
672
+ inputTokens: number;
673
+ outputTokens: number;
674
+ cacheReadTokens: number;
675
+ cacheWriteTokens: number;
623
676
  };
624
677
 
625
678
  export type LinkUsage = LinkUsageTotals & {
626
679
  // Every request received before this time is counted; null when the
627
680
  // gateway cannot tell (hosted Dari, for now).
628
- complete_through: string | null;
681
+ completeThrough: string | null;
629
682
  // Per model and thinking level served, most requests first.
630
- by_model: Array<LinkUsageTotals & { model: string; thinking: string | null }>;
683
+ byModel: Array<LinkUsageTotals & { model: string; thinking: string | null }>;
631
684
  // With `groupByTag`: per value of that tag (null: requests without it).
632
- by_tag?: Array<LinkUsageTotals & { value: string | null }>;
685
+ byTag?: Array<LinkUsageTotals & { value: string | null }>;
633
686
  };
634
687
 
635
688
  // A `linkFetch` the app already made, or what makes one.
@@ -669,7 +722,28 @@ export async function usage(args: GrantCall & {
669
722
  const query = params.toString();
670
723
  const fetcher = "fetcher" in args ? args.fetcher : linkFetch(args);
671
724
  const response = await fetcher(`/v1/link/usage${query ? `?${query}` : ""}`);
672
- return await json(response) as LinkUsage;
725
+ const payload = await json(response) as Record<string, unknown> & {
726
+ complete_through: string | null;
727
+ by_model: Array<Record<string, unknown> & { model: string; thinking: string | null }>;
728
+ by_tag?: Array<Record<string, unknown> & { value: string | null }>;
729
+ };
730
+ return {
731
+ ...usageTotals(payload),
732
+ completeThrough: payload.complete_through,
733
+ byModel: payload.by_model.map((row) => ({ ...usageTotals(row), model: row.model, thinking: row.thinking })),
734
+ ...(payload.by_tag === undefined ? {} : { byTag: payload.by_tag.map((row) => ({ ...usageTotals(row), value: row.value })) }),
735
+ };
736
+ }
737
+
738
+ function usageTotals(row: Record<string, unknown>): LinkUsageTotals {
739
+ return {
740
+ requests: row.requests as number,
741
+ errors: row.errors as number,
742
+ inputTokens: row.input_tokens as number,
743
+ outputTokens: row.output_tokens as number,
744
+ cacheReadTokens: row.cache_read_tokens as number,
745
+ cacheWriteTokens: row.cache_write_tokens as number,
746
+ };
673
747
  }
674
748
 
675
749
  /**
@@ -67,6 +67,7 @@ import type {
67
67
  GatewayPlatform,
68
68
  LinkApp,
69
69
  LinkApprovalPage,
70
+ LinkLimit,
70
71
  LinkClient,
71
72
  LinkConnect,
72
73
  LinkConnection,
@@ -89,6 +90,7 @@ import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
89
90
  import { gatewayFor } from "../models/gateways.js";
90
91
  import { budgetBody, limitsBody, spendBody, validBudget, validLimits } from "./budget.js";
91
92
  import { catalogModelFor } from "./grant_access.js";
93
+ import { registeredRedirect } from "./grants.js";
92
94
  import { requestTags } from "../runtime/request_tags.js";
93
95
  import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
94
96
  import { parseJsonRequest } from "../ingress/json.js";
@@ -166,6 +168,10 @@ type PlanAudience = "any_app" | "claude_code" | "muse_code";
166
168
  const PLAN_AUDIENCES: readonly PlanAudience[] = ["any_app", "claude_code", "muse_code"];
167
169
 
168
170
  export const LINK_ROUTE_PREFIX = "/v1/link/";
171
+ const LINK_TOKEN_CREATE_PATH = "/v1/link/link_token/create";
172
+ const LINK_TOKEN_PREFIX = "link-";
173
+ // A link token is good this long, as long as Plaid's.
174
+ const LINK_TOKEN_SECONDS = 4 * 60 * 60;
169
175
  export const LINK_METADATA_PATH = "/.well-known/oauth-authorization-server";
170
176
 
171
177
  /** The PKCE S256 challenge for a code verifier. */
@@ -213,6 +219,9 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
213
219
  if (pathname === "/v1/link/token" && request.method === "POST") {
214
220
  return withCors(await oauthEndpoint(() => token(platform, link, request)));
215
221
  }
222
+ if (pathname === LINK_TOKEN_CREATE_PATH && request.method === "POST") {
223
+ return await oauthEndpoint(() => createLinkToken(link, request));
224
+ }
216
225
  if (pathname === "/v1/link/register" && request.method === "POST") {
217
226
  return withCors(await registerClient(link, request));
218
227
  }
@@ -667,17 +676,37 @@ async function token(platform: GatewayPlatform, link: LinkPlatform, request: Req
667
676
  const grantType = body.get("grant_type");
668
677
  if (grantType === "authorization_code") {
669
678
  const code = body.get("code") ?? "";
679
+ const verifier = body.get("code_verifier");
680
+ if (!code) return oauthError("invalid_request", "code is required.");
681
+ if (verifier === null && client.clientSecret !== undefined) {
682
+ // A code from a link token: the client's secret proves it, as Plaid's
683
+ // public token exchange does. It was approved on one of the app's
684
+ // redirect URIs, which the link token named.
685
+ const app = await link.authenticateClient(client);
686
+ const codeChallenge = linkTokenChallenge(link, app.clientId);
687
+ let failure: unknown = new HttpError(400, "The authorization code is invalid, expired, or already used.", "invalid_grant");
688
+ for (const redirectUri of app.redirectUris) {
689
+ let tokens: LinkTokens;
690
+ try {
691
+ tokens = await link.exchangeCode({ ...client, code, redirectUri, codeChallenge });
692
+ } catch (error) {
693
+ failure = error;
694
+ continue;
695
+ }
696
+ return await tokenResponse(platform, link, request, tokens);
697
+ }
698
+ throw failure;
699
+ }
670
700
  const redirectUri = body.get("redirect_uri") ?? "";
671
- const verifier = body.get("code_verifier") ?? "";
672
- if (!code || !redirectUri) return oauthError("invalid_request", "code and redirect_uri are required.");
673
- if (!VERIFIER.test(verifier)) {
701
+ if (!redirectUri) return oauthError("invalid_request", "redirect_uri is required with code_verifier.");
702
+ if (!VERIFIER.test(verifier ?? "")) {
674
703
  return oauthError("invalid_request", "code_verifier must be 43 to 128 unreserved characters.");
675
704
  }
676
705
  return await tokenResponse(platform, link, request, await link.exchangeCode({
677
706
  ...client,
678
707
  code,
679
708
  redirectUri,
680
- codeChallenge: pkceChallenge(verifier),
709
+ codeChallenge: pkceChallenge(verifier!),
681
710
  }));
682
711
  }
683
712
  if (grantType === "refresh_token") {
@@ -1074,6 +1103,90 @@ function oauthError(
1074
1103
  );
1075
1104
  }
1076
1105
 
1106
+ /**
1107
+ * Plaid's `/link/token/create`: the app's server, with its client id and
1108
+ * secret, makes a short-lived token that carries what Link offers. The page
1109
+ * opens Link with it and gets back a code, which the server redeems with its
1110
+ * secret alone: no state or PKCE for the app to keep. JSON body:
1111
+ * `client_id`, `secret` (or HTTP Basic), and optionally `redirect_uri` (one
1112
+ * the app registered; default its first), `plans`, `client`, `key_providers`
1113
+ * (arrays), `purposes` ({ any_app, claude_code, muse_code }), and `grant_id`
1114
+ * for update mode.
1115
+ */
1116
+ async function createLinkToken(link: LinkPlatform, request: Request): Promise<Response> {
1117
+ let body: Record<string, unknown>;
1118
+ try {
1119
+ body = await parseJsonRequest(request);
1120
+ } catch {
1121
+ return oauthError("invalid_request", "The request body must be a JSON object.");
1122
+ }
1123
+ const named = clientFrom(request, new URLSearchParams(stringFields(body)));
1124
+ const clientSecret = named?.clientSecret ?? (typeof body.secret === "string" ? body.secret : undefined);
1125
+ if (named === null || !clientSecret) return oauthError("invalid_request", "client_id and secret are required.");
1126
+ const app = await link.authenticateClient({ clientId: named.clientId, clientSecret });
1127
+ const list = (name: string) => {
1128
+ const value = body[name];
1129
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string").join(" ") : typeof value === "string" ? value : "";
1130
+ };
1131
+ const purposes = typeof body.purposes === "object" && body.purposes !== null ? body.purposes as Record<string, unknown> : {};
1132
+ const fields: Record<string, string> = {
1133
+ client_id: app.clientId,
1134
+ redirect_uri: typeof body.redirect_uri === "string" ? body.redirect_uri : app.redirectUris[0] ?? "",
1135
+ ...(list("plans") ? { plans: list("plans") } : {}),
1136
+ ...(list("client") ? { client: list("client") } : {}),
1137
+ ...(list("key_providers") ? { key_providers: list("key_providers") } : {}),
1138
+ ...(typeof body.grant_id === "string" ? { grant_id: body.grant_id } : {}),
1139
+ ...Object.fromEntries(PLAN_AUDIENCES.flatMap((audience) =>
1140
+ typeof purposes[audience] === "string" ? [[`purpose_${audience}`, purposes[audience] as string]] : []
1141
+ )),
1142
+ };
1143
+ // Exactly a registered URI, which the code exchange tries; then the same
1144
+ // checks the approval page makes, so a bad request fails here.
1145
+ if (!app.redirectUris.includes(fields.redirect_uri!)) {
1146
+ return oauthError("invalid_request", "redirect_uri must be exactly one the app registered.");
1147
+ }
1148
+ const checked = await authorizeRequest(link, new URLSearchParams({
1149
+ ...fields,
1150
+ response_type: "code",
1151
+ code_challenge: linkTokenChallenge(link, app.clientId),
1152
+ code_challenge_method: "S256",
1153
+ }));
1154
+ if (checked instanceof Response) return oauthError("invalid_request", await errorText(checked));
1155
+ const expiration = new Date(Date.now() + LINK_TOKEN_SECONDS * 1000);
1156
+ return Response.json(
1157
+ {
1158
+ link_token: `${LINK_TOKEN_PREFIX}${signedValue(link.approval.sessionSecret(), "link_token", fields, LINK_TOKEN_SECONDS)}`,
1159
+ expiration: expiration.toISOString(),
1160
+ },
1161
+ { headers: { "Cache-Control": "no-store" } },
1162
+ );
1163
+ }
1164
+
1165
+ // The authorize fields a link token carries, or null for a bad or expired one.
1166
+ function readLinkToken(link: LinkPlatform, token: string): Record<string, string> | null {
1167
+ if (!token.startsWith(LINK_TOKEN_PREFIX)) return null;
1168
+ const value = readSignedValue(token.slice(LINK_TOKEN_PREFIX.length), link.approval.sessionSecret(), "link_token");
1169
+ if (value === null) return null;
1170
+ const { exp: _, ...fields } = value;
1171
+ return stringFields(fields);
1172
+ }
1173
+
1174
+ // The PKCE challenge every link-token code for a client carries: the client's
1175
+ // secret, not a verifier, proves the code at the exchange.
1176
+ function linkTokenChallenge(link: LinkPlatform, clientId: string): string {
1177
+ return pkceChallenge(sign(link.approval.sessionSecret(), `link_token_pkce\0${clientId}`));
1178
+ }
1179
+
1180
+ // What a refused approval request says: the text of its page.
1181
+ async function errorText(response: Response): Promise<string> {
1182
+ const message = /<p>([^<]*)<\/p>/.exec(await response.text())?.[1];
1183
+ return message === undefined ? "The link token request is invalid." : unescapeHtml(message);
1184
+ }
1185
+
1186
+ function unescapeHtml(text: string): string {
1187
+ return text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&#39;", "'").replaceAll("&amp;", "&");
1188
+ }
1189
+
1077
1190
  type AuthorizeRequest = {
1078
1191
  app: LinkApp;
1079
1192
  redirectUri: string;
@@ -1104,10 +1217,27 @@ function listParam(value: string | null): string[] {
1104
1217
  * redirected (RFC 6749 section 4.1.2.1).
1105
1218
  */
1106
1219
  async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Promise<AuthorizeRequest | Response> {
1220
+ const linkToken = params.get("link_token");
1221
+ if (linkToken !== null) {
1222
+ const fields = readLinkToken(link, linkToken);
1223
+ if (fields === null) {
1224
+ return page("Link Expired", `<div class="body"><h1>Link Expired</h1><p>Go back to the app and connect again.</p></div>`, { status: 400 });
1225
+ }
1226
+ // The token's request, with the challenge its code redeems by and the
1227
+ // token itself as the state the app's window matches the result to.
1228
+ params = new URLSearchParams({
1229
+ ...fields,
1230
+ response_type: "code",
1231
+ code_challenge: linkTokenChallenge(link, fields.client_id ?? ""),
1232
+ code_challenge_method: "S256",
1233
+ state: linkToken,
1234
+ ...(params.get("response_mode") !== null ? { response_mode: params.get("response_mode")! } : {}),
1235
+ });
1236
+ }
1107
1237
  const clientId = params.get("client_id") ?? "";
1108
1238
  const redirectUri = params.get("redirect_uri") ?? "";
1109
1239
  const app = clientId ? await link.app(clientId) : null;
1110
- if (app === null || !app.redirectUris.includes(redirectUri)) {
1240
+ if (app === null || !registeredRedirect(app.redirectUris, redirectUri)) {
1111
1241
  return page("Unknown App", `<div class="body"><h1>Unknown App</h1><p>This link request names an app or redirect URI Dari does not know.</p></div>`, { status: 400 });
1112
1242
  }
1113
1243
  const state = params.get("state");
@@ -1205,7 +1335,7 @@ async function grantToUpdate(
1205
1335
  return grant;
1206
1336
  }
1207
1337
 
1208
- type GrantToUpdate = { credentialIds: string[]; budget: LinkBudget[] };
1338
+ type GrantToUpdate = { credentialIds: string[]; budget: LinkBudget[]; limits: LinkLimit[] };
1209
1339
 
1210
1340
  async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSearchParams): Promise<Response> {
1211
1341
  const approval = link.approval;
@@ -1290,6 +1420,8 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1290
1420
  if (!credentialIds.every((id) => usable.has(id))) {
1291
1421
  return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
1292
1422
  }
1423
+ const limits = limitsFromForm(form, credentialIds);
1424
+ if (limits === null) return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
1293
1425
  try {
1294
1426
  const { code } = await approval.approve({
1295
1427
  subject: session.subject,
@@ -1298,8 +1430,8 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1298
1430
  redirectUri: authorize.redirectUri,
1299
1431
  codeChallenge: authorize.codeChallenge,
1300
1432
  credentialIds,
1301
- // The user sets a limit where they manage the connection, not here.
1302
1433
  budget: current?.budget ?? [],
1434
+ limits,
1303
1435
  });
1304
1436
  return redirect(back, { code }, [endConnect]);
1305
1437
  } catch (error) {
@@ -1371,6 +1503,28 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
1371
1503
  );
1372
1504
  }
1373
1505
 
1506
+ const LIMITS_ERROR = "Each plan limit is a percent above 0 and at most 100, and each key limit a dollar amount; leave it empty for none.";
1507
+
1508
+ // The limits typed into a form: `pct_<id>` a percent of a plan, `usd_<id>`
1509
+ // dollars a month; empty means none. Only for `only`'s plans when given; null
1510
+ // when one is not a valid limit.
1511
+ function limitsFromForm(form: URLSearchParams, only?: readonly string[]): LinkLimit[] | null {
1512
+ return validLimits([...form.entries()].flatMap(([field, raw]) => {
1513
+ const value = raw.replace(/[\s,$%]/g, "");
1514
+ const kind = field.slice(0, 4);
1515
+ const id = field.slice(4);
1516
+ if ((kind !== "usd_" && kind !== "pct_") || value === "" || (only !== undefined && !only.includes(id))) return [];
1517
+ const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
1518
+ return [{ credential_id: id, [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
1519
+ }));
1520
+ }
1521
+
1522
+ // A limit field for one plan or key, as the connections page and consent share.
1523
+ function limitInput(plan: LinkSubscription, id: string, label: string, value: number | undefined): string {
1524
+ const key = plan.apiKeyProvider !== undefined;
1525
+ return `<input id="${id}" type="text" inputmode="decimal" name="${key ? "usd" : "pct"}_${escapeHtml(plan.id)}" value="${value ?? ""}" placeholder="${key ? "$ / Month" : "% Of Plan"}" aria-label="${escapeHtml(label)} ${key ? "Monthly Limit ($)" : "Most Of Plan (%)"}" autocomplete="off">`;
1526
+ }
1527
+
1374
1528
  function connectionCard(connection: LinkConnection, csrf: string): string {
1375
1529
  const names = connection.subscriptions.map(planName);
1376
1530
  // A plan's account tells it apart only when the app shares two of the same name.
@@ -1422,16 +1576,8 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
1422
1576
  return back;
1423
1577
  }
1424
1578
  if (decision === "limits") {
1425
- const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
1426
- const value = raw.replace(/[\s,$%]/g, "");
1427
- const kind = field.slice(0, 4);
1428
- if ((kind !== "usd_" && kind !== "pct_") || value === "") return [];
1429
- const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
1430
- return [{ credential_id: field.slice(4), [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
1431
- }));
1432
- if (limits === null) {
1433
- return await connectionsPage(approval, request, "Each plan limit is a percent above 0 and at most 100, and each key limit a dollar amount; leave it empty for none.");
1434
- }
1579
+ const limits = limitsFromForm(form);
1580
+ if (limits === null) return await connectionsPage(approval, request, LIMITS_ERROR);
1435
1581
  await approval.setLimits(session.subject, grantId, limits);
1436
1582
  return back;
1437
1583
  }
@@ -1573,21 +1719,24 @@ async function signedIn(approval: LinkApprovalPage, request: Request, params: UR
1573
1719
  function readSigned(request: Request, secret: string, cookie: string): Record<string, unknown> | null {
1574
1720
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
1575
1721
  const [name, ...rest] = part.trim().split("=");
1576
- if (name !== cookie) continue;
1577
- const [payload, signature] = rest.join("=").split(".");
1578
- if (!payload || !signature || !sameText(signature, sign(secret, `${cookie}\0${payload}`))) return null;
1579
- try {
1580
- const value: unknown = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1581
- if (typeof value !== "object" || value === null) return null;
1582
- const exp = (value as { exp?: unknown }).exp;
1583
- return typeof exp === "number" && exp > Date.now() ? value as Record<string, unknown> : null;
1584
- } catch {
1585
- return null;
1586
- }
1722
+ if (name === cookie) return readSignedValue(rest.join("="), secret, cookie);
1587
1723
  }
1588
1724
  return null;
1589
1725
  }
1590
1726
 
1727
+ function readSignedValue(signed: string, secret: string, name: string): Record<string, unknown> | null {
1728
+ const [payload, signature] = signed.split(".");
1729
+ if (!payload || !signature || !sameText(signature, sign(secret, `${name}\0${payload}`))) return null;
1730
+ try {
1731
+ const value: unknown = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1732
+ if (typeof value !== "object" || value === null) return null;
1733
+ const exp = (value as { exp?: unknown }).exp;
1734
+ return typeof exp === "number" && exp > Date.now() ? value as Record<string, unknown> : null;
1735
+ } catch {
1736
+ return null;
1737
+ }
1738
+ }
1739
+
1591
1740
  function signedValue(secret: string, cookie: string, value: Record<string, unknown>, seconds: number): string {
1592
1741
  const payload = Buffer.from(JSON.stringify({ ...value, exp: Date.now() + seconds * 1000 })).toString("base64url");
1593
1742
  return `${payload}.${sign(secret, `${cookie}\0${payload}`)}`;
@@ -1838,10 +1987,19 @@ function choosePage(
1838
1987
  error,
1839
1988
  body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1840
1989
  <input type="hidden" name="csrf" value="${session.csrf}">
1990
+ <!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
1991
+ <button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
1841
1992
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1993
+ <details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
1994
+ ${plans.map((plan) => {
1995
+ const set = current?.limits.find((limit) => limit.credentialId === plan.id);
1996
+ const label = plan.apiKeyProvider === undefined ? KINDS[plan.provider as SubscriptionKind].name : plan.name;
1997
+ return `<div class="limit">${logo(plan.apiKeyProvider ?? plan.provider, label)}<label class="grow" for="limit_${escapeHtml(plan.id)}"><strong>${escapeHtml(label)}</strong><small>${escapeHtml(planLabel(plan))}</small></label>${limitInput(plan, `limit_${escapeHtml(plan.id)}`, label, set?.maxPercent ?? set?.monthlyUsd)}</div>`;
1998
+ }).join("\n")}
1999
+ </details>
1842
2000
  <div class="actions"><button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button><span><a class="btn ghost" href="${CONNECTIONS_PATH}" target="_blank" rel="noopener">Manage</a>${session.account ? SIGN_OUT : ""}</span></div>`,
1843
2001
  footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1844
- <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
2002
+ <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit or yours.</p>`,
1845
2003
  });
1846
2004
  }
1847
2005
 
@@ -1945,6 +2103,14 @@ function page(
1945
2103
  body: string,
1946
2104
  options: { status?: number; cookies?: string[]; scriptNonce?: string; event?: PageEvent; refresh?: number } = {},
1947
2105
  ): Response {
2106
+ // Every page: a pressed button shows it is working until the next page loads.
2107
+ const busyNonce = options.scriptNonce ?? randomUUID();
2108
+ body += `\n<script nonce="${busyNonce}">document.addEventListener("submit", (event) => {
2109
+ const button = event.submitter;
2110
+ if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
2111
+ setTimeout(() => { button.disabled = true; button.setAttribute("aria-busy", "true"); button.prepend(Object.assign(document.createElement("span"), { className: "spin" })); });
2112
+ });</script>`;
2113
+ options = { ...options, scriptNonce: busyNonce };
1948
2114
  if (options.event !== undefined) {
1949
2115
  const nonce = options.scriptNonce ?? randomUUID();
1950
2116
  // `<` is escaped so the JSON cannot close the script element.
@@ -2,6 +2,8 @@
2
2
  tell its user what to do.
3
3
 
4
4
  401, the token itself is dead:
5
+ - `authentication_error`: the gateway knows no such token (malformed,
6
+ never issued, or deleted). The app must link again.
5
7
  - `link_token_expired`: refresh the access token (or mint a new child
6
8
  token) and retry.
7
9
  - `grant_revoked`: the grant is gone; `revoked_by` says who ended it
@@ -10,8 +12,9 @@
10
12
 
11
13
  424, the grant's subscriptions cannot serve the request:
12
14
  - `subscription_exhausted`: the plans that can serve this client are at
13
- their usage limits; `resets_at` (and Retry-After) says when the first one
14
- is back, when that is known.
15
+ their usage limits, whether the gateway knew before the request or the
16
+ provider refused it; `resets_at` (ISO 8601, and Retry-After) says when the
17
+ first one is back, when that is known.
15
18
  - `grant_budget_exhausted`: the grant used the most tokens the user
16
19
  allowed it in a window (per five hours or per week), or every plan and
17
20
  key it shares is at its monthly spend limit; `resets_at` (and
@@ -78,6 +78,33 @@ export type LinkTokenAuth =
78
78
  /** A registered app as stored: with the hash of a confidential client's secret. */
79
79
  export type LinkAppRecord = LinkApp & { clientSecretHash: string | null };
80
80
 
81
+ const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"];
82
+
83
+ /**
84
+ * Whether an app registered this redirect URI. A loopback one matches on any
85
+ * port (RFC 8252 section 7.3), so a CLI can listen on whatever port is free.
86
+ */
87
+ export function registeredRedirect(redirectUris: readonly string[], redirectUri: string): boolean {
88
+ if (redirectUris.includes(redirectUri)) return true;
89
+ let url: URL;
90
+ try {
91
+ url = new URL(redirectUri);
92
+ } catch {
93
+ return false;
94
+ }
95
+ if (url.protocol !== "http:" || !LOOPBACK_HOSTS.includes(url.hostname)) return false;
96
+ url.port = "";
97
+ return redirectUris.some((registered) => {
98
+ try {
99
+ const candidate = new URL(registered);
100
+ candidate.port = "";
101
+ return candidate.toString() === url.toString();
102
+ } catch {
103
+ return false;
104
+ }
105
+ });
106
+ }
107
+
81
108
  /** A stored token with the grant it belongs to. Times are epoch milliseconds. */
82
109
  export type LinkTokenRecord = {
83
110
  kind: LinkTokenKind;
@@ -223,6 +250,9 @@ export function linkGrants(repo: LinkRepo) {
223
250
  /** What a presented access or child token is, or null when it is neither. */
224
251
  authenticate,
225
252
 
253
+ /** The app a client id and secret prove; throws `invalid_client` otherwise. */
254
+ authenticateClient: client,
255
+
226
256
  /** Redeem a code once: the grant's first tokens. */
227
257
  async exchangeCode(request: LinkCodeExchange, now = new Date()): Promise<LinkTokens> {
228
258
  await client(request);