@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.
@@ -156,6 +156,20 @@ export declare function authorizeUrl(args: AuthorizeOptions): Promise<{
156
156
  codeVerifier: string;
157
157
  state: string;
158
158
  }>;
159
+ /**
160
+ * On your server: a link token for one user's `DariLink.open`, as Plaid's
161
+ * `/link/token/create`. It carries what Link offers and lasts four hours.
162
+ * `redirectUri` defaults to the first one the app registered; `grantId`
163
+ * opens Link on that grant to change its plans (update mode).
164
+ */
165
+ export declare function createLinkToken(args: Client & {
166
+ clientSecret: string;
167
+ } & Omit<AuthorizeOptions, "gatewayUrl" | "clientId" | "redirectUri" | "state" | "responseMode"> & {
168
+ redirectUri?: string;
169
+ }): Promise<{
170
+ linkToken: string;
171
+ expiration: string;
172
+ }>;
159
173
  export type AuthorizeOptions = {
160
174
  gatewayUrl: string;
161
175
  clientId: string;
@@ -228,13 +242,23 @@ export type LinkExit = {
228
242
  error: string;
229
243
  step: LinkStep | null;
230
244
  };
231
- export type OpenLinkOptions = AuthorizeOptions & {
232
- codeChallenge?: string;
245
+ type LinkCallbacks = {
233
246
  fetch?: Fetch;
234
247
  window?: LinkBrowser;
235
248
  onEvent?: (step: LinkStep) => void;
236
249
  onExit?: (exit: LinkExit) => void;
237
250
  };
251
+ /**
252
+ * `{ gatewayUrl, linkToken }` with a token from `createLinkToken` (a server
253
+ * app); or the authorize options themselves, for an app with no server.
254
+ */
255
+ export type OpenLinkOptions = ({
256
+ gatewayUrl: string;
257
+ linkToken: string;
258
+ } & LinkCallbacks) | PublicLinkOptions;
259
+ type PublicLinkOptions = AuthorizeOptions & LinkCallbacks & {
260
+ codeChallenge?: string;
261
+ };
238
262
  /**
239
263
  * Open Dari's approval page in a popup and resolve with the code once the
240
264
  * user approves. Call it from a click handler, so the browser allows the
@@ -297,11 +321,15 @@ export declare const DariLink: {
297
321
  callback: typeof completeLink;
298
322
  renderButton: typeof renderButton;
299
323
  };
300
- /** Redeem the code from the approval redirect for the grant's first tokens. */
324
+ /**
325
+ * Redeem the code `DariLink.open` returned for the grant's first tokens. A
326
+ * code from a link token needs only your client secret; one from an
327
+ * authorize URL also needs its `redirectUri` and `codeVerifier`.
328
+ */
301
329
  export declare function exchange(args: Client & {
302
- redirectUri: string;
303
330
  code: string;
304
- codeVerifier: string;
331
+ redirectUri?: string;
332
+ codeVerifier?: string;
305
333
  }): Promise<LinkTokenSet>;
306
334
  /**
307
335
  * A new access token. A public client's refresh token rotates: the one passed
@@ -350,18 +378,18 @@ export declare function linkFetch(args: Client & LinkTokens & {
350
378
  export type LinkUsageTotals = {
351
379
  requests: number;
352
380
  errors: number;
353
- input_tokens: number;
354
- output_tokens: number;
355
- cache_read_tokens: number;
356
- cache_write_tokens: number;
381
+ inputTokens: number;
382
+ outputTokens: number;
383
+ cacheReadTokens: number;
384
+ cacheWriteTokens: number;
357
385
  };
358
386
  export type LinkUsage = LinkUsageTotals & {
359
- complete_through: string | null;
360
- by_model: Array<LinkUsageTotals & {
387
+ completeThrough: string | null;
388
+ byModel: Array<LinkUsageTotals & {
361
389
  model: string;
362
390
  thinking: string | null;
363
391
  }>;
364
- by_tag?: Array<LinkUsageTotals & {
392
+ byTag?: Array<LinkUsageTotals & {
365
393
  value: string | null;
366
394
  }>;
367
395
  };
@@ -110,6 +110,30 @@ export async function authorizeUrl(args) {
110
110
  const { codeVerifier, codeChallenge, state } = await createAuthorization(args.state);
111
111
  return { url: authorizationUrl({ ...args, codeChallenge, state }), codeVerifier, state };
112
112
  }
113
+ /**
114
+ * On your server: a link token for one user's `DariLink.open`, as Plaid's
115
+ * `/link/token/create`. It carries what Link offers and lasts four hours.
116
+ * `redirectUri` defaults to the first one the app registered; `grantId`
117
+ * opens Link on that grant to change its plans (update mode).
118
+ */
119
+ export async function createLinkToken(args) {
120
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/v1/link/link_token/create"), {
121
+ method: "POST",
122
+ headers: { "content-type": "application/json" },
123
+ body: JSON.stringify({
124
+ client_id: args.clientId,
125
+ secret: args.clientSecret,
126
+ ...(args.redirectUri ? { redirect_uri: args.redirectUri } : {}),
127
+ ...(args.plans?.length ? { plans: args.plans } : {}),
128
+ ...(args.clients?.length ? { client: args.clients } : {}),
129
+ ...(args.keyProviders?.length ? { key_providers: args.keyProviders } : {}),
130
+ ...(args.purposes ? { purposes: args.purposes } : {}),
131
+ ...(args.grantId ? { grant_id: args.grantId } : {}),
132
+ }),
133
+ });
134
+ const body = await json(response);
135
+ return { linkToken: String(body.link_token), expiration: String(body.expiration) };
136
+ }
113
137
  /**
114
138
  * A fresh PKCE pair and state, made on your server: keep `codeVerifier` (and
115
139
  * `state`) with the user's session, and hand the browser only `codeChallenge`
@@ -172,7 +196,7 @@ export async function openLink(options, browserOverride) {
172
196
  ?? globalThis;
173
197
  // Making PKCE in the page needs Web Crypto, which browsers give only to
174
198
  // https (or localhost) pages; a challenge from the server needs none.
175
- const insecure = (args) => args.codeChallenge === undefined && (browser.isSecureContext === false || globalThis.crypto?.subtle === undefined);
199
+ const insecure = (args) => !("linkToken" in args) && args.codeChallenge === undefined && (browser.isSecureContext === false || globalThis.crypto?.subtle === undefined);
176
200
  const insecureError = () => new LinkError("insecure_context", "Connect with Dari needs a secure page (https, or localhost) to make its PKCE pair, or a codeChallenge and state from your server.", 0);
177
201
  if (typeof options !== "function" && insecure(options)) {
178
202
  options.onExit?.({ error: "insecure_context", step: null });
@@ -196,16 +220,7 @@ export async function openLink(options, browserOverride) {
196
220
  args.onExit?.({ error: "insecure_context", step: null });
197
221
  throw insecureError();
198
222
  }
199
- const supplied = args.codeChallenge;
200
- if (supplied !== undefined && args.state === undefined) {
201
- throw new LinkError("invalid_request", "Pass the state your server made with the codeChallenge.", 0);
202
- }
203
- [request, origin] = await Promise.all([
204
- supplied !== undefined
205
- ? { url: authorizationUrl({ ...args, codeChallenge: supplied, state: args.state, responseMode: "web_message" }), codeVerifier: null, state: args.state }
206
- : authorizeUrl({ ...args, responseMode: "web_message" }),
207
- approvalOrigin(args),
208
- ]);
223
+ [request, origin] = await Promise.all([linkRequest(args), approvalOrigin(args)]);
209
224
  }
210
225
  catch (error) {
211
226
  popup.close();
@@ -272,6 +287,26 @@ export async function openLink(options, browserOverride) {
272
287
  popup.location.href = request.url;
273
288
  });
274
289
  }
290
+ // The approval URL to open, and the state its result comes back with.
291
+ async function linkRequest(args) {
292
+ if ("linkToken" in args) {
293
+ const url = new URL(endpoint(args.gatewayUrl, "/v1/link/authorize"));
294
+ url.search = new URLSearchParams({ link_token: args.linkToken, response_mode: "web_message" }).toString();
295
+ // The gateway returns the link token as the state.
296
+ return { url: url.toString(), codeVerifier: null, state: args.linkToken };
297
+ }
298
+ const supplied = args.codeChallenge;
299
+ if (supplied === undefined)
300
+ return await authorizeUrl({ ...args, responseMode: "web_message" });
301
+ if (args.state === undefined) {
302
+ throw new LinkError("invalid_request", "Pass the state your server made with the codeChallenge.", 0);
303
+ }
304
+ return {
305
+ url: authorizationUrl({ ...args, codeChallenge: supplied, state: args.state, responseMode: "web_message" }),
306
+ codeVerifier: null,
307
+ state: args.state,
308
+ };
309
+ }
275
310
  /**
276
311
  * On your redirect URI's page: hand an approval that arrived there in the
277
312
  * popup to the window that called `DariLink.open`, and close the popup.
@@ -330,13 +365,17 @@ async function approvalOrigin(args) {
330
365
  const origin = (await json(response)).web_message_origin;
331
366
  return typeof origin === "string" ? origin : new URL(args.gatewayUrl).origin;
332
367
  }
333
- /** Redeem the code from the approval redirect for the grant's first tokens. */
368
+ /**
369
+ * Redeem the code `DariLink.open` returned for the grant's first tokens. A
370
+ * code from a link token needs only your client secret; one from an
371
+ * authorize URL also needs its `redirectUri` and `codeVerifier`.
372
+ */
334
373
  export async function exchange(args) {
335
374
  return tokenSet(await tokenCall(args, {
336
375
  grant_type: "authorization_code",
337
- redirect_uri: args.redirectUri,
338
376
  code: args.code,
339
- code_verifier: args.codeVerifier,
377
+ ...(args.redirectUri ? { redirect_uri: args.redirectUri } : {}),
378
+ ...(args.codeVerifier ? { code_verifier: args.codeVerifier } : {}),
340
379
  }));
341
380
  }
342
381
  /**
@@ -461,7 +500,23 @@ export async function usage(args) {
461
500
  const query = params.toString();
462
501
  const fetcher = "fetcher" in args ? args.fetcher : linkFetch(args);
463
502
  const response = await fetcher(`/v1/link/usage${query ? `?${query}` : ""}`);
464
- return await json(response);
503
+ const payload = await json(response);
504
+ return {
505
+ ...usageTotals(payload),
506
+ completeThrough: payload.complete_through,
507
+ byModel: payload.by_model.map((row) => ({ ...usageTotals(row), model: row.model, thinking: row.thinking })),
508
+ ...(payload.by_tag === undefined ? {} : { byTag: payload.by_tag.map((row) => ({ ...usageTotals(row), value: row.value })) }),
509
+ };
510
+ }
511
+ function usageTotals(row) {
512
+ return {
513
+ requests: row.requests,
514
+ errors: row.errors,
515
+ inputTokens: row.input_tokens,
516
+ outputTokens: row.output_tokens,
517
+ cacheReadTokens: row.cache_read_tokens,
518
+ cacheWriteTokens: row.cache_write_tokens,
519
+ };
465
520
  }
466
521
  // The access tokens this process made from refresh tokens, by gateway,
467
522
  // client, and refresh token, and each one's refresh in flight.
@@ -66,6 +66,7 @@ import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
66
66
  import { gatewayFor } from "../models/gateways.js";
67
67
  import { budgetBody, limitsBody, spendBody, validBudget, validLimits } from "./budget.js";
68
68
  import { catalogModelFor } from "./grant_access.js";
69
+ import { registeredRedirect } from "./grants.js";
69
70
  import { requestTags } from "../runtime/request_tags.js";
70
71
  import { parseJsonRequest } from "../ingress/json.js";
71
72
  import { DARI_MARK, ICONS, linkLogo } from "./assets.js";
@@ -136,6 +137,10 @@ const API_KEY = "api_key";
136
137
  const OFFER_KINDS = [...PLAN_KINDS, API_KEY];
137
138
  const PLAN_AUDIENCES = ["any_app", "claude_code", "muse_code"];
138
139
  export const LINK_ROUTE_PREFIX = "/v1/link/";
140
+ const LINK_TOKEN_CREATE_PATH = "/v1/link/link_token/create";
141
+ const LINK_TOKEN_PREFIX = "link-";
142
+ // A link token is good this long, as long as Plaid's.
143
+ const LINK_TOKEN_SECONDS = 4 * 60 * 60;
139
144
  export const LINK_METADATA_PATH = "/.well-known/oauth-authorization-server";
140
145
  /** The PKCE S256 challenge for a code verifier. */
141
146
  export function pkceChallenge(verifier) {
@@ -182,6 +187,9 @@ export async function handleLinkRequest(request, platform) {
182
187
  if (pathname === "/v1/link/token" && request.method === "POST") {
183
188
  return withCors(await oauthEndpoint(() => token(platform, link, request)));
184
189
  }
190
+ if (pathname === LINK_TOKEN_CREATE_PATH && request.method === "POST") {
191
+ return await oauthEndpoint(() => createLinkToken(link, request));
192
+ }
185
193
  if (pathname === "/v1/link/register" && request.method === "POST") {
186
194
  return withCors(await registerClient(link, request));
187
195
  }
@@ -592,11 +600,33 @@ async function token(platform, link, request) {
592
600
  const grantType = body.get("grant_type");
593
601
  if (grantType === "authorization_code") {
594
602
  const code = body.get("code") ?? "";
603
+ const verifier = body.get("code_verifier");
604
+ if (!code)
605
+ return oauthError("invalid_request", "code is required.");
606
+ if (verifier === null && client.clientSecret !== undefined) {
607
+ // A code from a link token: the client's secret proves it, as Plaid's
608
+ // public token exchange does. It was approved on one of the app's
609
+ // redirect URIs, which the link token named.
610
+ const app = await link.authenticateClient(client);
611
+ const codeChallenge = linkTokenChallenge(link, app.clientId);
612
+ let failure = new HttpError(400, "The authorization code is invalid, expired, or already used.", "invalid_grant");
613
+ for (const redirectUri of app.redirectUris) {
614
+ let tokens;
615
+ try {
616
+ tokens = await link.exchangeCode({ ...client, code, redirectUri, codeChallenge });
617
+ }
618
+ catch (error) {
619
+ failure = error;
620
+ continue;
621
+ }
622
+ return await tokenResponse(platform, link, request, tokens);
623
+ }
624
+ throw failure;
625
+ }
595
626
  const redirectUri = body.get("redirect_uri") ?? "";
596
- const verifier = body.get("code_verifier") ?? "";
597
- if (!code || !redirectUri)
598
- return oauthError("invalid_request", "code and redirect_uri are required.");
599
- if (!VERIFIER.test(verifier)) {
627
+ if (!redirectUri)
628
+ return oauthError("invalid_request", "redirect_uri is required with code_verifier.");
629
+ if (!VERIFIER.test(verifier ?? "")) {
600
630
  return oauthError("invalid_request", "code_verifier must be 43 to 128 unreserved characters.");
601
631
  }
602
632
  return await tokenResponse(platform, link, request, await link.exchangeCode({
@@ -954,6 +984,85 @@ async function oauthEndpoint(respond) {
954
984
  function oauthError(error, description, status = 400, headers = {}, errorCode) {
955
985
  return Response.json({ error, ...(errorCode === undefined ? {} : { error_code: errorCode }), error_description: description }, { status, headers: { "Cache-Control": "no-store", ...headers } });
956
986
  }
987
+ /**
988
+ * Plaid's `/link/token/create`: the app's server, with its client id and
989
+ * secret, makes a short-lived token that carries what Link offers. The page
990
+ * opens Link with it and gets back a code, which the server redeems with its
991
+ * secret alone: no state or PKCE for the app to keep. JSON body:
992
+ * `client_id`, `secret` (or HTTP Basic), and optionally `redirect_uri` (one
993
+ * the app registered; default its first), `plans`, `client`, `key_providers`
994
+ * (arrays), `purposes` ({ any_app, claude_code, muse_code }), and `grant_id`
995
+ * for update mode.
996
+ */
997
+ async function createLinkToken(link, request) {
998
+ let body;
999
+ try {
1000
+ body = await parseJsonRequest(request);
1001
+ }
1002
+ catch {
1003
+ return oauthError("invalid_request", "The request body must be a JSON object.");
1004
+ }
1005
+ const named = clientFrom(request, new URLSearchParams(stringFields(body)));
1006
+ const clientSecret = named?.clientSecret ?? (typeof body.secret === "string" ? body.secret : undefined);
1007
+ if (named === null || !clientSecret)
1008
+ return oauthError("invalid_request", "client_id and secret are required.");
1009
+ const app = await link.authenticateClient({ clientId: named.clientId, clientSecret });
1010
+ const list = (name) => {
1011
+ const value = body[name];
1012
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string").join(" ") : typeof value === "string" ? value : "";
1013
+ };
1014
+ const purposes = typeof body.purposes === "object" && body.purposes !== null ? body.purposes : {};
1015
+ const fields = {
1016
+ client_id: app.clientId,
1017
+ redirect_uri: typeof body.redirect_uri === "string" ? body.redirect_uri : app.redirectUris[0] ?? "",
1018
+ ...(list("plans") ? { plans: list("plans") } : {}),
1019
+ ...(list("client") ? { client: list("client") } : {}),
1020
+ ...(list("key_providers") ? { key_providers: list("key_providers") } : {}),
1021
+ ...(typeof body.grant_id === "string" ? { grant_id: body.grant_id } : {}),
1022
+ ...Object.fromEntries(PLAN_AUDIENCES.flatMap((audience) => typeof purposes[audience] === "string" ? [[`purpose_${audience}`, purposes[audience]]] : [])),
1023
+ };
1024
+ // Exactly a registered URI, which the code exchange tries; then the same
1025
+ // checks the approval page makes, so a bad request fails here.
1026
+ if (!app.redirectUris.includes(fields.redirect_uri)) {
1027
+ return oauthError("invalid_request", "redirect_uri must be exactly one the app registered.");
1028
+ }
1029
+ const checked = await authorizeRequest(link, new URLSearchParams({
1030
+ ...fields,
1031
+ response_type: "code",
1032
+ code_challenge: linkTokenChallenge(link, app.clientId),
1033
+ code_challenge_method: "S256",
1034
+ }));
1035
+ if (checked instanceof Response)
1036
+ return oauthError("invalid_request", await errorText(checked));
1037
+ const expiration = new Date(Date.now() + LINK_TOKEN_SECONDS * 1000);
1038
+ return Response.json({
1039
+ link_token: `${LINK_TOKEN_PREFIX}${signedValue(link.approval.sessionSecret(), "link_token", fields, LINK_TOKEN_SECONDS)}`,
1040
+ expiration: expiration.toISOString(),
1041
+ }, { headers: { "Cache-Control": "no-store" } });
1042
+ }
1043
+ // The authorize fields a link token carries, or null for a bad or expired one.
1044
+ function readLinkToken(link, token) {
1045
+ if (!token.startsWith(LINK_TOKEN_PREFIX))
1046
+ return null;
1047
+ const value = readSignedValue(token.slice(LINK_TOKEN_PREFIX.length), link.approval.sessionSecret(), "link_token");
1048
+ if (value === null)
1049
+ return null;
1050
+ const { exp: _, ...fields } = value;
1051
+ return stringFields(fields);
1052
+ }
1053
+ // The PKCE challenge every link-token code for a client carries: the client's
1054
+ // secret, not a verifier, proves the code at the exchange.
1055
+ function linkTokenChallenge(link, clientId) {
1056
+ return pkceChallenge(sign(link.approval.sessionSecret(), `link_token_pkce\0${clientId}`));
1057
+ }
1058
+ // What a refused approval request says: the text of its page.
1059
+ async function errorText(response) {
1060
+ const message = /<p>([^<]*)<\/p>/.exec(await response.text())?.[1];
1061
+ return message === undefined ? "The link token request is invalid." : unescapeHtml(message);
1062
+ }
1063
+ function unescapeHtml(text) {
1064
+ return text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&#39;", "'").replaceAll("&amp;", "&");
1065
+ }
957
1066
  // A space- or comma-separated list parameter.
958
1067
  function listParam(value) {
959
1068
  return [...new Set((value ?? "").split(/[\s,]+/).filter(Boolean))];
@@ -964,10 +1073,27 @@ function listParam(value) {
964
1073
  * redirected (RFC 6749 section 4.1.2.1).
965
1074
  */
966
1075
  async function authorizeRequest(link, params) {
1076
+ const linkToken = params.get("link_token");
1077
+ if (linkToken !== null) {
1078
+ const fields = readLinkToken(link, linkToken);
1079
+ if (fields === null) {
1080
+ return page("Link Expired", `<div class="body"><h1>Link Expired</h1><p>Go back to the app and connect again.</p></div>`, { status: 400 });
1081
+ }
1082
+ // The token's request, with the challenge its code redeems by and the
1083
+ // token itself as the state the app's window matches the result to.
1084
+ params = new URLSearchParams({
1085
+ ...fields,
1086
+ response_type: "code",
1087
+ code_challenge: linkTokenChallenge(link, fields.client_id ?? ""),
1088
+ code_challenge_method: "S256",
1089
+ state: linkToken,
1090
+ ...(params.get("response_mode") !== null ? { response_mode: params.get("response_mode") } : {}),
1091
+ });
1092
+ }
967
1093
  const clientId = params.get("client_id") ?? "";
968
1094
  const redirectUri = params.get("redirect_uri") ?? "";
969
1095
  const app = clientId ? await link.app(clientId) : null;
970
- if (app === null || !app.redirectUris.includes(redirectUri)) {
1096
+ if (app === null || !registeredRedirect(app.redirectUris, redirectUri)) {
971
1097
  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 });
972
1098
  }
973
1099
  const state = params.get("state");
@@ -1153,6 +1279,9 @@ async function authorizeSubmit(link, request, form) {
1153
1279
  if (!credentialIds.every((id) => usable.has(id))) {
1154
1280
  return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
1155
1281
  }
1282
+ const limits = limitsFromForm(form, credentialIds);
1283
+ if (limits === null)
1284
+ return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
1156
1285
  try {
1157
1286
  const { code } = await approval.approve({
1158
1287
  subject: session.subject,
@@ -1161,8 +1290,8 @@ async function authorizeSubmit(link, request, form) {
1161
1290
  redirectUri: authorize.redirectUri,
1162
1291
  codeChallenge: authorize.codeChallenge,
1163
1292
  credentialIds,
1164
- // The user sets a limit where they manage the connection, not here.
1165
1293
  budget: current?.budget ?? [],
1294
+ limits,
1166
1295
  });
1167
1296
  return redirect(back, { code }, [endConnect]);
1168
1297
  }
@@ -1224,6 +1353,26 @@ ${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${plan
1224
1353
  ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${SIGN_OUT}</form>` : ""}
1225
1354
  </div>`);
1226
1355
  }
1356
+ 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.";
1357
+ // The limits typed into a form: `pct_<id>` a percent of a plan, `usd_<id>`
1358
+ // dollars a month; empty means none. Only for `only`'s plans when given; null
1359
+ // when one is not a valid limit.
1360
+ function limitsFromForm(form, only) {
1361
+ return validLimits([...form.entries()].flatMap(([field, raw]) => {
1362
+ const value = raw.replace(/[\s,$%]/g, "");
1363
+ const kind = field.slice(0, 4);
1364
+ const id = field.slice(4);
1365
+ if ((kind !== "usd_" && kind !== "pct_") || value === "" || (only !== undefined && !only.includes(id)))
1366
+ return [];
1367
+ const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
1368
+ return [{ credential_id: id, [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
1369
+ }));
1370
+ }
1371
+ // A limit field for one plan or key, as the connections page and consent share.
1372
+ function limitInput(plan, id, label, value) {
1373
+ const key = plan.apiKeyProvider !== undefined;
1374
+ 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">`;
1375
+ }
1227
1376
  function connectionCard(connection, csrf) {
1228
1377
  const names = connection.subscriptions.map(planName);
1229
1378
  // A plan's account tells it apart only when the app shares two of the same name.
@@ -1275,17 +1424,9 @@ async function connectionsSubmit(approval, request, form) {
1275
1424
  return back;
1276
1425
  }
1277
1426
  if (decision === "limits") {
1278
- const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
1279
- const value = raw.replace(/[\s,$%]/g, "");
1280
- const kind = field.slice(0, 4);
1281
- if ((kind !== "usd_" && kind !== "pct_") || value === "")
1282
- return [];
1283
- const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
1284
- return [{ credential_id: field.slice(4), [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
1285
- }));
1286
- if (limits === null) {
1287
- 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.");
1288
- }
1427
+ const limits = limitsFromForm(form);
1428
+ if (limits === null)
1429
+ return await connectionsPage(approval, request, LIMITS_ERROR);
1289
1430
  await approval.setLimits(session.subject, grantId, limits);
1290
1431
  return back;
1291
1432
  }
@@ -1407,24 +1548,26 @@ async function signedIn(approval, request, params) {
1407
1548
  function readSigned(request, secret, cookie) {
1408
1549
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
1409
1550
  const [name, ...rest] = part.trim().split("=");
1410
- if (name !== cookie)
1411
- continue;
1412
- const [payload, signature] = rest.join("=").split(".");
1413
- if (!payload || !signature || !sameText(signature, sign(secret, `${cookie}\0${payload}`)))
1414
- return null;
1415
- try {
1416
- const value = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1417
- if (typeof value !== "object" || value === null)
1418
- return null;
1419
- const exp = value.exp;
1420
- return typeof exp === "number" && exp > Date.now() ? value : null;
1421
- }
1422
- catch {
1423
- return null;
1424
- }
1551
+ if (name === cookie)
1552
+ return readSignedValue(rest.join("="), secret, cookie);
1425
1553
  }
1426
1554
  return null;
1427
1555
  }
1556
+ function readSignedValue(signed, secret, name) {
1557
+ const [payload, signature] = signed.split(".");
1558
+ if (!payload || !signature || !sameText(signature, sign(secret, `${name}\0${payload}`)))
1559
+ return null;
1560
+ try {
1561
+ const value = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1562
+ if (typeof value !== "object" || value === null)
1563
+ return null;
1564
+ const exp = value.exp;
1565
+ return typeof exp === "number" && exp > Date.now() ? value : null;
1566
+ }
1567
+ catch {
1568
+ return null;
1569
+ }
1570
+ }
1428
1571
  function signedValue(secret, cookie, value, seconds) {
1429
1572
  const payload = Buffer.from(JSON.stringify({ ...value, exp: Date.now() + seconds * 1000 })).toString("base64url");
1430
1573
  return `${payload}.${sign(secret, `${cookie}\0${payload}`)}`;
@@ -1632,10 +1775,19 @@ function choosePage(authorize, session, subscriptions, current, error) {
1632
1775
  error,
1633
1776
  body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1634
1777
  <input type="hidden" name="csrf" value="${session.csrf}">
1778
+ <!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
1779
+ <button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
1635
1780
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1781
+ <details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
1782
+ ${plans.map((plan) => {
1783
+ const set = current?.limits.find((limit) => limit.credentialId === plan.id);
1784
+ const label = plan.apiKeyProvider === undefined ? KINDS[plan.provider].name : plan.name;
1785
+ 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>`;
1786
+ }).join("\n")}
1787
+ </details>
1636
1788
  <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>`,
1637
1789
  footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1638
- <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
1790
+ <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>`,
1639
1791
  });
1640
1792
  }
1641
1793
  function planOption(authorize, subscription, ticked) {
@@ -1712,6 +1864,14 @@ ${options.back === undefined ? "" : `<button class="nav back" type="submit" name
1712
1864
  </form>`, { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh });
1713
1865
  }
1714
1866
  function page(title, body, options = {}) {
1867
+ // Every page: a pressed button shows it is working until the next page loads.
1868
+ const busyNonce = options.scriptNonce ?? randomUUID();
1869
+ body += `\n<script nonce="${busyNonce}">document.addEventListener("submit", (event) => {
1870
+ const button = event.submitter;
1871
+ if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
1872
+ setTimeout(() => { button.disabled = true; button.setAttribute("aria-busy", "true"); button.prepend(Object.assign(document.createElement("span"), { className: "spin" })); });
1873
+ });</script>`;
1874
+ options = { ...options, scriptNonce: busyNonce };
1715
1875
  if (options.event !== undefined) {
1716
1876
  const nonce = options.scriptNonce ?? randomUUID();
1717
1877
  // `<` 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
@@ -36,6 +36,11 @@ export type LinkTokenAuth = {
36
36
  export type LinkAppRecord = LinkApp & {
37
37
  clientSecretHash: string | null;
38
38
  };
39
+ /**
40
+ * Whether an app registered this redirect URI. A loopback one matches on any
41
+ * port (RFC 8252 section 7.3), so a CLI can listen on whatever port is free.
42
+ */
43
+ export declare function registeredRedirect(redirectUris: readonly string[], redirectUri: string): boolean;
39
44
  /** A stored token with the grant it belongs to. Times are epoch milliseconds. */
40
45
  export type LinkTokenRecord = {
41
46
  kind: LinkTokenKind;
@@ -117,6 +122,8 @@ export type LinkRepo = {
117
122
  export declare function linkGrants(repo: LinkRepo): {
118
123
  /** What a presented access or child token is, or null when it is neither. */
119
124
  authenticate: (token: string, now?: Date) => Promise<LinkTokenAuth | null>;
125
+ /** The app a client id and secret prove; throws `invalid_client` otherwise. */
126
+ authenticateClient: ({ clientId, clientSecret }: LinkClient) => Promise<LinkAppRecord>;
120
127
  /** Redeem a code once: the grant's first tokens. */
121
128
  exchangeCode(request: LinkCodeExchange, now?: Date): Promise<LinkTokens>;
122
129
  /**
@@ -31,6 +31,35 @@ export const LINK_TOKEN_RETENTION_MS = 24 * 60 * 60_000;
31
31
  export const LINK_REFRESH_TOKEN_PREFIX = "dlk_rt_";
32
32
  export const LINK_CODE_PREFIX = "dlk_code_";
33
33
  export const LINK_CLIENT_SECRET_PREFIX = "dlk_cs_";
34
+ const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"];
35
+ /**
36
+ * Whether an app registered this redirect URI. A loopback one matches on any
37
+ * port (RFC 8252 section 7.3), so a CLI can listen on whatever port is free.
38
+ */
39
+ export function registeredRedirect(redirectUris, redirectUri) {
40
+ if (redirectUris.includes(redirectUri))
41
+ return true;
42
+ let url;
43
+ try {
44
+ url = new URL(redirectUri);
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ if (url.protocol !== "http:" || !LOOPBACK_HOSTS.includes(url.hostname))
50
+ return false;
51
+ url.port = "";
52
+ return redirectUris.some((registered) => {
53
+ try {
54
+ const candidate = new URL(registered);
55
+ candidate.port = "";
56
+ return candidate.toString() === url.toString();
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ });
62
+ }
34
63
  /** The token protocol over a platform's storage. `now` is for tests. */
35
64
  export function linkGrants(repo) {
36
65
  const client = async ({ clientId, clientSecret }) => {
@@ -74,6 +103,8 @@ export function linkGrants(repo) {
74
103
  return {
75
104
  /** What a presented access or child token is, or null when it is neither. */
76
105
  authenticate,
106
+ /** The app a client id and secret prove; throws `invalid_client` otherwise. */
107
+ authenticateClient: client,
77
108
  /** Redeem a code once: the grant's first tokens. */
78
109
  async exchangeCode(request, now = new Date()) {
79
110
  await client(request);
@@ -37,6 +37,7 @@ export type LinkStore = LinkRepo & {
37
37
  codeExpiresAt: number;
38
38
  credentialIds: string[];
39
39
  budget: LinkBudget[];
40
+ limits: LinkLimit[];
40
41
  now: number;
41
42
  }): MaybePromise<string | null>;
42
43
  /**