@mupt-ai/dari-gateway 1.0.311 → 1.0.313

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 (127) hide show
  1. package/README.md +279 -2
  2. package/dist/context/provider_prompt_accounting.js +7 -0
  3. package/dist/context/routing_context.js +4 -1
  4. package/dist/http/handler.d.ts +2 -1
  5. package/dist/http/handler.js +12 -2
  6. package/dist/ingress/anthropic_messages.js +15 -3
  7. package/dist/ingress/chat_completions.js +6 -1
  8. package/dist/ingress/codex.js +2 -2
  9. package/dist/ingress/link.d.ts +24 -0
  10. package/dist/ingress/link.js +1519 -0
  11. package/dist/ingress/link_assets.d.ts +14 -0
  12. package/dist/ingress/link_assets.js +49 -0
  13. package/dist/ingress/link_font.d.ts +1 -0
  14. package/dist/ingress/link_font.js +6 -0
  15. package/dist/ingress/models.js +46 -2
  16. package/dist/interaction/types.d.ts +1 -0
  17. package/dist/link_client.d.ts +386 -0
  18. package/dist/link_client.js +579 -0
  19. package/dist/models/gateways.d.ts +2 -0
  20. package/dist/models/gateways.js +2 -0
  21. package/dist/models/link_errors.d.ts +30 -0
  22. package/dist/models/link_errors.js +120 -0
  23. package/dist/models/subscriptions.d.ts +8 -1
  24. package/dist/models/subscriptions.js +13 -2
  25. package/dist/platform/platform.d.ts +303 -1
  26. package/dist/protocol/input/router_model.d.ts +4 -0
  27. package/dist/protocol/input/router_model.js +31 -1
  28. package/dist/providers/execution.js +31 -5
  29. package/dist/providers/pi_options.js +57 -1
  30. package/dist/providers/provider_call.d.ts +4 -0
  31. package/dist/providers/provider_call.js +9 -2
  32. package/dist/providers/response_capture.d.ts +4 -1
  33. package/dist/providers/response_capture.js +81 -2
  34. package/dist/providers/stream_finalization.d.ts +1 -0
  35. package/dist/providers/subscription_limits.d.ts +15 -0
  36. package/dist/providers/subscription_limits.js +45 -0
  37. package/dist/runtime/explicit_model.js +16 -4
  38. package/dist/runtime/harness_identity/extract.js +20 -36
  39. package/dist/runtime/link_budget.d.ts +27 -0
  40. package/dist/runtime/link_budget.js +62 -0
  41. package/dist/runtime/link_grant_access.d.ts +7 -0
  42. package/dist/runtime/link_grant_access.js +99 -0
  43. package/dist/runtime/link_in_flight.d.ts +4 -0
  44. package/dist/runtime/link_in_flight.js +43 -0
  45. package/dist/runtime/prepare_routed_completion.js +5 -1
  46. package/dist/runtime/routed_runtime.js +8 -0
  47. package/dist/runtime/runtime_reporter.d.ts +1 -0
  48. package/dist/runtime/runtime_reporter.js +1 -0
  49. package/dist/self_host/config.d.ts +9 -0
  50. package/dist/self_host/config.js +11 -1
  51. package/dist/self_host/link_store.d.ts +167 -0
  52. package/dist/self_host/link_store.js +564 -0
  53. package/dist/self_host/main.d.ts +10 -3
  54. package/dist/self_host/main.js +19 -4
  55. package/dist/self_host/platform.d.ts +2 -2
  56. package/dist/self_host/platform.js +284 -10
  57. package/dist/self_host/resolve.d.ts +8 -0
  58. package/dist/self_host/resolve.js +146 -15
  59. package/dist/self_host/secret_box.d.ts +23 -0
  60. package/dist/self_host/secret_box.js +105 -0
  61. package/dist/self_host/stub_gateway.d.ts +60 -0
  62. package/dist/self_host/stub_gateway.js +397 -0
  63. package/dist/self_host/stub_main.d.ts +2 -0
  64. package/dist/self_host/stub_main.js +69 -0
  65. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  66. package/dist/self_host/subscription_test_gateway.js +25 -91
  67. package/dist/self_host/subscriptions/access.d.ts +5 -0
  68. package/dist/self_host/subscriptions/access.js +5 -1
  69. package/dist/self_host/subscriptions/http.js +8 -1
  70. package/dist/self_host/subscriptions/index.d.ts +5 -2
  71. package/dist/self_host/subscriptions/index.js +5 -2
  72. package/dist/self_host/subscriptions/store.d.ts +41 -16
  73. package/dist/self_host/subscriptions/store.js +136 -32
  74. package/dist/self_host/subscriptions/usage.d.ts +7 -0
  75. package/dist/self_host/subscriptions/usage.js +52 -0
  76. package/dist/telemetry/report.js +18 -0
  77. package/dist/types.d.ts +18 -0
  78. package/package.json +4 -3
  79. package/src/context/provider_prompt_accounting.ts +7 -0
  80. package/src/context/routing_context.ts +3 -1
  81. package/src/http/handler.ts +14 -2
  82. package/src/ingress/anthropic_messages.ts +19 -4
  83. package/src/ingress/chat_completions.ts +6 -1
  84. package/src/ingress/codex.ts +2 -2
  85. package/src/ingress/link.ts +1731 -0
  86. package/src/ingress/link_assets.ts +56 -0
  87. package/src/ingress/link_font.ts +9 -0
  88. package/src/ingress/models.ts +48 -2
  89. package/src/interaction/types.ts +4 -0
  90. package/src/link_client.ts +796 -0
  91. package/src/models/gateways.ts +3 -0
  92. package/src/models/link_errors.ts +157 -0
  93. package/src/models/subscriptions.ts +15 -1
  94. package/src/platform/platform.ts +330 -1
  95. package/src/protocol/input/router_model.ts +36 -1
  96. package/src/providers/execution.ts +31 -4
  97. package/src/providers/pi_options.ts +57 -1
  98. package/src/providers/provider_call.ts +20 -2
  99. package/src/providers/response_capture.ts +88 -2
  100. package/src/providers/stream_finalization.ts +1 -0
  101. package/src/providers/subscription_limits.ts +53 -0
  102. package/src/runtime/explicit_model.ts +21 -8
  103. package/src/runtime/harness_identity/extract.ts +21 -60
  104. package/src/runtime/link_budget.ts +75 -0
  105. package/src/runtime/link_grant_access.ts +116 -0
  106. package/src/runtime/link_in_flight.ts +46 -0
  107. package/src/runtime/prepare_routed_completion.ts +6 -1
  108. package/src/runtime/routed_runtime.ts +8 -0
  109. package/src/runtime/runtime_reporter.ts +3 -0
  110. package/src/self_host/config.ts +24 -1
  111. package/src/self_host/link_store.ts +782 -0
  112. package/src/self_host/main.ts +21 -4
  113. package/src/self_host/platform.ts +305 -11
  114. package/src/self_host/resolve.ts +172 -15
  115. package/src/self_host/secret_box.ts +112 -0
  116. package/src/self_host/stub_gateway.ts +497 -0
  117. package/src/self_host/stub_main.ts +72 -0
  118. package/src/self_host/subscription_test_gateway.ts +26 -95
  119. package/src/self_host/subscriptions/access.ts +10 -1
  120. package/src/self_host/subscriptions/http.ts +9 -1
  121. package/src/self_host/subscriptions/index.ts +6 -0
  122. package/src/self_host/subscriptions/store.ts +167 -36
  123. package/src/self_host/subscriptions/usage.ts +64 -0
  124. package/src/telemetry/report.ts +17 -1
  125. package/src/types.ts +26 -0
  126. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  127. package/dist/self_host/subscriptions/test_support.js +0 -34
@@ -0,0 +1,1519 @@
1
+ /* Dari Link: OAuth 2.0 authorization code grants with PKCE (S256) that let an
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.
6
+
7
+ - GET /.well-known/oauth-authorization-server metadata (RFC 8414)
8
+ - 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
12
+ - POST /v1/link/authorize each step of the page: connect a plan, then
13
+ approve or deny; returns `code`
14
+ or `error` to the app: on its redirect URI,
15
+ or with `response_mode=web_message` posted
16
+ to the window that opened the page
17
+ - POST /v1/link/token `authorization_code`, `refresh_token`, and
18
+ token exchange for a child token (RFC 8693)
19
+ - POST /v1/link/revoke the app revokes its grant (RFC 7009)
20
+ - GET /v1/link/grant the grant a link access token belongs to
21
+ - GET /v1/link/usage what the grant's requests used, by tag and time
22
+ - POST /v1/link/apps register an app (bearer: the user's key)
23
+ - GET /v1/link/grants the user's grants
24
+ - DELETE /v1/link/grants/{id} the user revokes a grant and its tokens
25
+ - PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
26
+ budget: the most tokens the app may use per
27
+ five hours and per week
28
+
29
+ A confidential client authenticates at the token and revocation endpoints
30
+ with HTTP Basic (`client_id:client_secret`); a public one sends `client_id`
31
+ in the body.
32
+
33
+ The gateway's own approval page needs no account, like a bank link: the
34
+ 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. */
39
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
40
+ import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy-engine";
41
+ import { bearerToken } from "../http/auth.js";
42
+ import { errorResponse, HttpError } from "../http/errors.js";
43
+ import { SUBSCRIPTION_PLAN_LABELS } from "../models/link_errors.js";
44
+ import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
45
+ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
46
+ import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
47
+ import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
48
+ import { gatewayFor } from "../models/gateways.js";
49
+ import { budgetBody, validBudget } from "../runtime/link_budget.js";
50
+ import { catalogModelFor } from "../runtime/link_grant_access.js";
51
+ import { requestTags } from "../runtime/request_tags.js";
52
+ import { parseJsonRequest } from "./json.js";
53
+ import { DARI_MARK, ICONS, linkLogo } from "./link_assets.js";
54
+ import { GEIST_WOFF2 } from "./link_font.js";
55
+ const VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
56
+ // The base64url SHA-256 of a verifier.
57
+ const CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
58
+ const MAX_APP_NAME_CHARS = 100;
59
+ const MAX_REDIRECT_URIS = 10;
60
+ const MAX_REGISTRATION_BYTES = 8_192;
61
+ // Open registration is unauthenticated, so each gateway process takes at most
62
+ // this many per minute.
63
+ const MAX_REGISTRATIONS_PER_MINUTE = 20;
64
+ const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
65
+ const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
66
+ const MAX_TAG_KEY_CHARS = 64;
67
+ // Who the approval page's user is, for a year from their last plan.
68
+ const USER_COOKIE = "dari_link_user";
69
+ const USER_SECONDS = 365 * 24 * 60 * 60;
70
+ // A provider sign-in under way, for as long as providers keep one open.
71
+ const CONNECT_COOKIE = "dari_link_connect";
72
+ const CONNECT_SECONDS = 15 * 60;
73
+ // How often the page asks a provider whether the user approved its code.
74
+ const DEVICE_POLL_SECONDS = 5;
75
+ const AUTHORIZE_PATH = "/v1/link/authorize";
76
+ const CALLBACK_SCRIPT_PATH = "/v1/link/callback.js";
77
+ // The approval page's typeface.
78
+ const FONT_PATH = "/v1/link/geist.woff2";
79
+ const GRANT_ID = /^[A-Za-z0-9_-]{1,64}$/;
80
+ const USAGE_REQUEST_ROUTE = /^\/v1\/link\/usage\/requests\/([^/]{1,200})$/;
81
+ // `response_mode=web_message`: the result is posted to the window that opened
82
+ // the approval page, for an app that opens it as a popup.
83
+ const WEB_MESSAGE = "web_message";
84
+ /** The `type` of the message a `web_message` approval posts to its opener. */
85
+ export const LINK_MESSAGE_TYPE = "dari-link";
86
+ // A step the user reached in the popup; never a result.
87
+ export const LINK_EVENT_TYPE = "dari-link-event";
88
+ // The one scope: route model requests on the granted plans.
89
+ export const LINK_SCOPE = "route";
90
+ const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
91
+ const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
92
+ const CHILD_TOKEN_DEFAULT_SECONDS = 60 * 60;
93
+ const CHILD_TOKEN_MAX_SECONDS = 12 * 60 * 60;
94
+ const MAX_MODEL_CHARS = 200;
95
+ const MAX_PURPOSE_CHARS = 200;
96
+ const MAX_CHILD_MODELS = 16;
97
+ // Clients an app can say it runs with `client` on the authorize request.
98
+ // Claude Code and Muse Code plans serve only an app that runs those.
99
+ const CLIENTS = ["claude_code", "codex", "muse_code", "opencode", "pi", "openclaw", "hermes"];
100
+ const PLAN_KINDS = Object.keys(SUBSCRIPTION_PLAN_LABELS);
101
+ // An API key, as a kind an app asks for in `plans` and reads on a grant.
102
+ const API_KEY = "api_key";
103
+ const OFFER_KINDS = [...PLAN_KINDS, API_KEY];
104
+ const PLAN_AUDIENCES = ["any_app", "claude_code", "muse_code"];
105
+ export const LINK_ROUTE_PREFIX = "/v1/link/";
106
+ export const LINK_METADATA_PATH = "/.well-known/oauth-authorization-server";
107
+ /** The PKCE S256 challenge for a code verifier. */
108
+ export function pkceChallenge(verifier) {
109
+ return createHash("sha256").update(verifier).digest("base64url");
110
+ }
111
+ export async function handleLinkRequest(request, platform) {
112
+ const url = new URL(request.url);
113
+ const { pathname } = url;
114
+ const link = platform.link;
115
+ if (link === undefined)
116
+ return errorResponse(new HttpError(404, "Not found", "not_found"));
117
+ try {
118
+ if (pathname === LINK_METADATA_PATH && request.method === "GET") {
119
+ return withCors(Response.json(metadata(publicOrigin(request), link)));
120
+ }
121
+ if (pathname === CALLBACK_SCRIPT_PATH && request.method === "GET") {
122
+ return new Response(CALLBACK_SCRIPT, {
123
+ headers: { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "public, max-age=300" },
124
+ });
125
+ }
126
+ if (pathname === FONT_PATH && request.method === "GET") {
127
+ return new Response(GEIST_WOFF2, {
128
+ headers: { "Content-Type": "font/woff2", "Cache-Control": "public, max-age=31536000, immutable" },
129
+ });
130
+ }
131
+ if (pathname === AUTHORIZE_PATH && request.method === "GET") {
132
+ return await authorizePage(link, request, url.searchParams);
133
+ }
134
+ if (pathname === AUTHORIZE_PATH && request.method === "POST") {
135
+ return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
136
+ }
137
+ if (request.method === "OPTIONS" && (CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname))) {
138
+ return withCors(new Response(null, { status: 204 }));
139
+ }
140
+ if (pathname === "/v1/link/token" && request.method === "POST") {
141
+ return withCors(await oauthEndpoint(() => token(platform, link, request)));
142
+ }
143
+ if (pathname === "/v1/link/register" && request.method === "POST") {
144
+ return withCors(await registerClient(link, request));
145
+ }
146
+ if (pathname === "/v1/link/revoke" && request.method === "POST") {
147
+ return withCors(await oauthEndpoint(() => revoke(link, request)));
148
+ }
149
+ if (pathname === "/v1/link/grant" && request.method === "GET") {
150
+ return withCors(await grant(platform, link, request));
151
+ }
152
+ if (pathname === "/v1/link/usage" && request.method === "GET") {
153
+ return withCors(await usage(link, request, url.searchParams));
154
+ }
155
+ const requestUsage = USAGE_REQUEST_ROUTE.exec(pathname);
156
+ if (requestUsage !== null && request.method === "GET") {
157
+ return withCors(await usage(link, request, new URLSearchParams(), decodeURIComponent(requestUsage[1])));
158
+ }
159
+ if (pathname === "/v1/link/apps" && request.method === "POST") {
160
+ return await registerApp(link, request);
161
+ }
162
+ if (pathname === "/v1/link/grants" && request.method === "GET") {
163
+ const grants = await link.grants(bearerToken(request.headers));
164
+ return Response.json({
165
+ grants: grants.map((grant) => ({
166
+ id: grant.id,
167
+ client_id: grant.clientId,
168
+ app_name: grant.appName,
169
+ credential_ids: grant.credentialIds,
170
+ created_at: grant.createdAt,
171
+ budget: budgetBody(grant.budget),
172
+ })),
173
+ });
174
+ }
175
+ const budgetRoute = GRANT_BUDGET_ROUTE.exec(pathname);
176
+ if (budgetRoute !== null && request.method === "PUT") {
177
+ const grantId = decodeURIComponent(budgetRoute[1]);
178
+ const body = await parseJsonRequest(request);
179
+ const budget = validBudget(body?.budget);
180
+ if (budget === null) {
181
+ throw new HttpError(400, "budget must be a list of {window_minutes, max_tokens} with distinct window_minutes of 300 or 10080 and max_tokens a positive whole number; [] removes it.", "invalid_request_error", "budget");
182
+ }
183
+ if (!(await link.setBudget({ apiKey: bearerToken(request.headers), grantId, budget }))) {
184
+ throw new HttpError(404, `No grant ${grantId}.`, "not_found");
185
+ }
186
+ return Response.json({ id: grantId, budget: budgetBody(budget) });
187
+ }
188
+ const grantRoute = GRANT_ROUTE.exec(pathname);
189
+ if (grantRoute !== null && request.method === "DELETE") {
190
+ const grantId = decodeURIComponent(grantRoute[1]);
191
+ if (!(await link.revokeGrant({ apiKey: bearerToken(request.headers), grantId }))) {
192
+ throw new HttpError(404, `No grant ${grantId}.`, "not_found");
193
+ }
194
+ return Response.json({ id: grantId, revoked: true });
195
+ }
196
+ return errorResponse(new HttpError(404, "Not found", "not_found"));
197
+ }
198
+ catch (error) {
199
+ const response = linkErrorResponse(error);
200
+ return CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname) ? withCors(response) : response;
201
+ }
202
+ }
203
+ // A refusal keeps its own message; a failure says nothing of its cause but a
204
+ // request id, which the log line carries with the detail.
205
+ function linkErrorResponse(error) {
206
+ if (error instanceof HttpError && error.status < 500)
207
+ return errorResponse(error);
208
+ const requestId = randomUUID();
209
+ console.error(`dari link request ${requestId} failed`, error);
210
+ return errorResponse(new HttpError(error instanceof HttpError ? error.status : 500, `Dari Link request failed. Request id ${requestId}.`, error instanceof HttpError ? error.code : "link_request_failed", undefined, undefined, { request_id: requestId }));
211
+ }
212
+ function metadata(origin, link) {
213
+ return {
214
+ issuer: origin,
215
+ authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
216
+ response_modes_supported: ["query", WEB_MESSAGE],
217
+ // The origin a `web_message` result is posted from: the page that approves.
218
+ web_message_origin: "consentUrl" in link.approval ? new URL(link.approval.consentUrl).origin : origin,
219
+ token_endpoint: `${origin}/v1/link/token`,
220
+ registration_endpoint: `${origin}/v1/link/register`,
221
+ revocation_endpoint: `${origin}/v1/link/revoke`,
222
+ // A script for the redirect URI's page that hands an approval back to the
223
+ // window that opened the popup (see the README's callback contract).
224
+ callback_script: `${origin}${CALLBACK_SCRIPT_PATH}`,
225
+ // Where users manage the apps they connected; null when the platform has
226
+ // no signed-in app for it.
227
+ connected_apps_uri: "consentUrl" in link.approval ? link.approval.connectedAppsUrl : null,
228
+ response_types_supported: ["code"],
229
+ grant_types_supported: ["authorization_code", "refresh_token", TOKEN_EXCHANGE_GRANT],
230
+ code_challenge_methods_supported: ["S256"],
231
+ token_endpoint_auth_methods_supported: ["none", "client_secret_basic"],
232
+ revocation_endpoint_auth_methods_supported: ["none", "client_secret_basic"],
233
+ scopes_supported: [LINK_SCOPE],
234
+ };
235
+ }
236
+ // The origin apps reach the gateway at; a TLS-terminating proxy says https.
237
+ function publicOrigin(request) {
238
+ const url = new URL(request.url);
239
+ const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim();
240
+ return `${forwarded("x-forwarded-proto") === "https" ? "https:" : url.protocol}//${forwarded("x-forwarded-host") || url.host}`;
241
+ }
242
+ // A browser request sent by another site: Sec-Fetch-Site says so, and where a
243
+ // browser sends none, an Origin other than the gateway's.
244
+ function crossSite(request) {
245
+ const site = request.headers.get("sec-fetch-site");
246
+ if (site !== null)
247
+ return site !== "same-origin" && site !== "none";
248
+ const origin = request.headers.get("origin");
249
+ return origin !== null && origin !== publicOrigin(request);
250
+ }
251
+ // A malformed authorize request, shown on the page: it is the app's bug, and
252
+ // sending it to the redirect URI would make the gateway an open redirector for
253
+ // anyone who registers one.
254
+ function badRequest(description) {
255
+ return page("Invalid Request", `<div class="body"><h1>Invalid Request</h1><p>${escapeHtml(description)}</p></div>`, { status: 400 });
256
+ }
257
+ function isHttps(request) {
258
+ return publicOrigin(request).startsWith("https:");
259
+ }
260
+ async function registerApp(link, request) {
261
+ const apiKey = bearerToken(request.headers);
262
+ const body = await parseJsonRequest(request);
263
+ const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
264
+ throw new HttpError(400, message, "invalid_request_error", param);
265
+ });
266
+ if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
267
+ throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
268
+ }
269
+ const app = await link.registerApp({ apiKey, name, redirectUris, confidential: body.confidential === true });
270
+ return Response.json(
271
+ // The secret is shown this once; only its hash is stored.
272
+ { ...appBody(app), ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret }) }, { status: 201, headers: { "Cache-Control": "no-store" } });
273
+ }
274
+ let registrationWindow = { startedAt: 0, count: 0 };
275
+ // RFC 7591: any app registers itself with no key: a public client (PKCE, no
276
+ // secret), or with `client_secret_basic` a confidential one, whose secret is
277
+ // returned this once. Either way the user still approves every grant.
278
+ async function registerClient(link, request) {
279
+ const now = Date.now();
280
+ if (now - registrationWindow.startedAt >= 60_000)
281
+ registrationWindow = { startedAt: now, count: 0 };
282
+ if (registrationWindow.count >= MAX_REGISTRATIONS_PER_MINUTE) {
283
+ return Response.json({ error: "temporarily_unavailable", error_description: "Too many registrations. Retry in a minute." }, { status: 429, headers: { "Retry-After": "60" } });
284
+ }
285
+ const text = await request.text();
286
+ if (text.length > MAX_REGISTRATION_BYTES) {
287
+ return registrationError("invalid_client_metadata", `The registration must be at most ${MAX_REGISTRATION_BYTES} bytes.`);
288
+ }
289
+ let body;
290
+ try {
291
+ const parsed = JSON.parse(text);
292
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
293
+ throw new Error();
294
+ body = parsed;
295
+ }
296
+ catch {
297
+ return registrationError("invalid_client_metadata", "The registration must be a JSON object.");
298
+ }
299
+ const authMethod = body.token_endpoint_auth_method ?? "none";
300
+ if (authMethod !== "none" && authMethod !== "client_secret_basic") {
301
+ return registrationError("invalid_client_metadata", "token_endpoint_auth_method must be none (a public client) or client_secret_basic (a confidential client).");
302
+ }
303
+ let client;
304
+ try {
305
+ client = validClient(link, body.client_name, body.redirect_uris, (message, param) => {
306
+ throw new HttpError(400, message, param === "redirect_uris" ? "invalid_redirect_uri" : "invalid_client_metadata");
307
+ });
308
+ }
309
+ catch (error) {
310
+ if (error instanceof HttpError)
311
+ return registrationError(error.code, error.message);
312
+ throw error;
313
+ }
314
+ registrationWindow.count += 1;
315
+ const app = await link.registerApp({ ...client, confidential: authMethod === "client_secret_basic" });
316
+ return Response.json({
317
+ client_id: app.clientId,
318
+ // The secret is shown this once; only its hash is stored.
319
+ ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret, client_secret_expires_at: 0 }),
320
+ client_name: app.name,
321
+ redirect_uris: app.redirectUris,
322
+ client_id_issued_at: Math.floor(now / 1000),
323
+ token_endpoint_auth_method: authMethod,
324
+ grant_types: ["authorization_code", "refresh_token", TOKEN_EXCHANGE_GRANT],
325
+ response_types: ["code"],
326
+ scope: LINK_SCOPE,
327
+ }, { status: 201, headers: { "Cache-Control": "no-store" } });
328
+ }
329
+ function registrationError(error, description) {
330
+ return Response.json({ error, error_description: description }, { status: 400, headers: { "Cache-Control": "no-store" } });
331
+ }
332
+ function validClient(link, rawName, rawRedirectUris, refuse) {
333
+ const name = typeof rawName === "string" ? rawName.trim() : "";
334
+ if (!name || name.length > MAX_APP_NAME_CHARS)
335
+ refuse(`The name must be 1 to ${MAX_APP_NAME_CHARS} characters.`, "name");
336
+ if (!Array.isArray(rawRedirectUris)
337
+ || rawRedirectUris.length === 0
338
+ || rawRedirectUris.length > MAX_REDIRECT_URIS
339
+ || !rawRedirectUris.every((uri) => typeof uri === "string" && validRedirectUri(uri, link.httpRedirectHosts ?? []))) {
340
+ refuse(`redirect_uris must list 1 to ${MAX_REDIRECT_URIS} URIs, each https or http on localhost${(link.httpRedirectHosts ?? []).length > 0 ? " or an allowed dev host" : ""}, without a fragment.`, "redirect_uris");
341
+ }
342
+ return { name, redirectUris: [...new Set(rawRedirectUris)] };
343
+ }
344
+ function appBody(app) {
345
+ return {
346
+ client_id: app.clientId,
347
+ name: app.name,
348
+ redirect_uris: app.redirectUris,
349
+ token_endpoint_auth_method: app.confidential ? "client_secret_basic" : "none",
350
+ };
351
+ }
352
+ // Public clients redirect to their own HTTPS origin or to a loopback port;
353
+ // a self-hosted gateway may also allow http on hosts it lists (`*.suffix`
354
+ // matches any subdomain).
355
+ function validRedirectUri(value, httpHosts) {
356
+ let url;
357
+ try {
358
+ url = new URL(value);
359
+ }
360
+ catch {
361
+ return false;
362
+ }
363
+ if (url.hash !== "" || value.includes("#"))
364
+ return false;
365
+ if (url.protocol === "https:")
366
+ return true;
367
+ if (url.protocol !== "http:")
368
+ return false;
369
+ return ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
370
+ || httpHosts.some((host) => host.startsWith("*.") ? url.hostname.endsWith(host.slice(1)) : url.hostname === host);
371
+ }
372
+ // A form or JSON body as form fields.
373
+ async function formBody(request) {
374
+ const contentType = request.headers.get("content-type") ?? "";
375
+ try {
376
+ return contentType.includes("application/json")
377
+ ? new URLSearchParams(stringFields(await parseJsonRequest(request)))
378
+ : new URLSearchParams(await request.text());
379
+ }
380
+ catch {
381
+ return null;
382
+ }
383
+ }
384
+ // The client a token or revocation request is from: HTTP Basic for a
385
+ // confidential client (RFC 6749 section 2.3.1), else `client_id` in the body.
386
+ function clientFrom(request, body) {
387
+ const named = body.get("client_id") ?? "";
388
+ const authorization = request.headers.get("authorization") ?? "";
389
+ if (!/^basic /i.test(authorization))
390
+ return named ? { clientId: named } : null;
391
+ let clientId;
392
+ let clientSecret;
393
+ try {
394
+ const decoded = Buffer.from(authorization.slice(6).trim(), "base64").toString("utf8");
395
+ const separator = decoded.indexOf(":");
396
+ if (separator < 0)
397
+ throw new Error();
398
+ clientId = decodeURIComponent(decoded.slice(0, separator));
399
+ clientSecret = decodeURIComponent(decoded.slice(separator + 1));
400
+ }
401
+ catch {
402
+ throw invalidClient();
403
+ }
404
+ if (!clientId || (named && named !== clientId))
405
+ throw invalidClient();
406
+ return { clientId, ...(clientSecret ? { clientSecret } : {}) };
407
+ }
408
+ function invalidClient() {
409
+ return new HttpError(401, "Unknown client, or a missing or wrong client secret.", "invalid_client");
410
+ }
411
+ // Token endpoint (RFC 6749 section 5): form or JSON body, OAuth error shape.
412
+ async function token(platform, link, request) {
413
+ const body = await formBody(request);
414
+ if (body === null)
415
+ return oauthError("invalid_request", "The request body must be a form or a JSON object.");
416
+ const client = clientFrom(request, body);
417
+ if (client === null)
418
+ return oauthError("invalid_request", "client_id is required.");
419
+ const grantType = body.get("grant_type");
420
+ if (grantType === "authorization_code") {
421
+ const code = body.get("code") ?? "";
422
+ const redirectUri = body.get("redirect_uri") ?? "";
423
+ const verifier = body.get("code_verifier") ?? "";
424
+ if (!code || !redirectUri)
425
+ return oauthError("invalid_request", "code and redirect_uri are required.");
426
+ if (!VERIFIER.test(verifier)) {
427
+ return oauthError("invalid_request", "code_verifier must be 43 to 128 unreserved characters.");
428
+ }
429
+ return await tokenResponse(platform, link, await link.exchangeCode({
430
+ ...client,
431
+ code,
432
+ redirectUri,
433
+ codeChallenge: pkceChallenge(verifier),
434
+ }));
435
+ }
436
+ if (grantType === "refresh_token") {
437
+ const refreshToken = body.get("refresh_token") ?? "";
438
+ if (!refreshToken)
439
+ return oauthError("invalid_request", "refresh_token is required.");
440
+ return await tokenResponse(platform, link, await link.refresh({ ...client, refreshToken }));
441
+ }
442
+ if (grantType === TOKEN_EXCHANGE_GRANT)
443
+ return await childToken(platform, link, client, body);
444
+ return oauthError("unsupported_grant_type", `grant_type must be authorization_code, refresh_token, or ${TOKEN_EXCHANGE_GRANT}.`);
445
+ }
446
+ /**
447
+ * RFC 8693: trade the grant's access token for a child token that serves only
448
+ * the models it names, for a sandbox or worker that must hold nothing more.
449
+ * `model` is required and repeats (up to 16); `thinking` pins the level each
450
+ * is served at (see below); `expires_in` is 60 seconds to 12 hours (default
451
+ * 1 hour); `tags` labels its requests like the X-Dari-Tags header. Every
452
+ * model is checked at mint: one the grant cannot serve refuses the whole
453
+ * mint with `invalid_target`.
454
+ */
455
+ async function childToken(platform, link, client, body) {
456
+ const subjectToken = body.get("subject_token") ?? "";
457
+ if (!subjectToken || body.get("subject_token_type") !== ACCESS_TOKEN_TYPE) {
458
+ return oauthError("invalid_request", `subject_token is required, with subject_token_type ${ACCESS_TOKEN_TYPE}.`);
459
+ }
460
+ // `model` repeats for each model; `thinking` is absent (none pinned), given
461
+ // once (pinned for every model), or given once per model in order, with
462
+ // `default` leaving that model unpinned.
463
+ const names = body.getAll("model").map((named) => explicitModelId(named) ?? named);
464
+ if (names.length === 0 || names.length > MAX_CHILD_MODELS || names.some((name) => !name || name.length > MAX_MODEL_CHARS)) {
465
+ return oauthError("invalid_request", `model is required, 1 to ${MAX_CHILD_MODELS} times: catalog models such as dari/model/openai/gpt-5.5.`);
466
+ }
467
+ const levels = body.getAll("thinking");
468
+ if (levels.length > 1 && levels.length !== names.length) {
469
+ return oauthError("invalid_request", "Give thinking once for every model, or once per model in the same order.");
470
+ }
471
+ const thinkingFor = (index) => {
472
+ const level = levels.length === 0 ? undefined : levels.length === 1 ? levels[0] : levels[index];
473
+ return level === "default" ? undefined : level;
474
+ };
475
+ if (names.some((_, index) => {
476
+ const level = thinkingFor(index);
477
+ return level !== undefined && !isReasoningEffort(level);
478
+ })) {
479
+ return oauthError("invalid_request", "thinking must be a thinking level, such as low or high, or default.");
480
+ }
481
+ const expiresIn = body.has("expires_in") ? Number(body.get("expires_in")) : CHILD_TOKEN_DEFAULT_SECONDS;
482
+ if (!Number.isInteger(expiresIn) || expiresIn < 60 || expiresIn > CHILD_TOKEN_MAX_SECONDS) {
483
+ return oauthError("invalid_request", `expires_in must be 60 to ${CHILD_TOKEN_MAX_SECONDS} seconds.`);
484
+ }
485
+ let tags;
486
+ try {
487
+ tags = requestTags(body.get("tags"));
488
+ }
489
+ catch {
490
+ return oauthError("invalid_request", "tags must be comma-separated key=value pairs.");
491
+ }
492
+ // The grant must hold a plan for the model's provider; whether that plan
493
+ // can serve is decided on each request.
494
+ const detail = await grantOf(link, subjectToken);
495
+ if (detail === null) {
496
+ return oauthError("invalid_grant", "subject_token must be a live access token of this client's grant.");
497
+ }
498
+ // The model must be one the grant serves some client now, by the names a
499
+ // request may use (a catalog id, its bare form, or a dated snapshot), at a
500
+ // level it offers.
501
+ const served = await Promise.all([undefined, ...detail.subscriptions.map((plan) => subscriptionClient(plan.provider))]
502
+ .map(async (harness) => await servedRouter(platform, subjectToken, harness)));
503
+ const servable = [...new Set(served.flatMap((router) => router?.link_models ?? []))];
504
+ // A gateway the grant holds a key for serves any model of its own, by full id.
505
+ const gateways = new Set(served.flatMap((router) => Object.keys(router?.link_key_gateways ?? {})));
506
+ const gatewayModel = (name) => {
507
+ const id = name.toLowerCase();
508
+ const gateway = id.split("/")[0];
509
+ return gateways.has(gateway) && id.length > gateway.length + 1 ? id : null;
510
+ };
511
+ const models = [];
512
+ for (const [index, name] of names.entries()) {
513
+ const model = catalogModelFor(name, servable) ?? gatewayModel(name);
514
+ if (model === null) {
515
+ return oauthError("invalid_target", `This grant serves no model '${name}' now. GET /v1/link/grant lists its models.`);
516
+ }
517
+ if (models.some((entry) => entry.model === model)) {
518
+ return oauthError("invalid_target", `'${model}' is named twice.`);
519
+ }
520
+ const thinking = thinkingFor(index);
521
+ const offered = CANONICAL_MODELS.find((entry) => entry.id === model)?.thinking_levels;
522
+ if (thinking !== undefined && offered !== undefined && !offered.includes(thinking)) {
523
+ return oauthError("invalid_target", `'${model}' has no thinking level '${thinking}'; it offers ${offered.join(", ")}.`);
524
+ }
525
+ models.push({ model, ...(thinking === undefined ? {} : { thinking }) });
526
+ }
527
+ const child = await link.exchangeToken({ ...client, subjectToken, models, expiresIn, tags });
528
+ return Response.json({
529
+ access_token: child.accessToken,
530
+ issued_token_type: ACCESS_TOKEN_TYPE,
531
+ token_type: "Bearer",
532
+ expires_in: child.expiresIn,
533
+ grant_id: child.grantId,
534
+ models: models.map((entry) => ({ model: explicitModelSlug(entry.model), thinking: entry.thinking ?? null })),
535
+ ...(Object.keys(tags).length === 0 ? {} : { tags }),
536
+ }, { headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });
537
+ }
538
+ // The grant a subject token belongs to, or null when the token is dead or is
539
+ // not a grant's access token.
540
+ async function grantOf(link, accessToken) {
541
+ try {
542
+ return await link.grant(accessToken);
543
+ }
544
+ catch (error) {
545
+ if (error instanceof HttpError && (error.status === 401 || error.status === 403))
546
+ return null;
547
+ throw error;
548
+ }
549
+ }
550
+ // RFC 7009: the app ends its own grant, as when its user disconnects there.
551
+ // The response is 200 whether or not the token was live.
552
+ async function revoke(link, request) {
553
+ const body = await formBody(request);
554
+ if (body === null)
555
+ return oauthError("invalid_request", "The request body must be a form or a JSON object.");
556
+ const client = clientFrom(request, body);
557
+ const presented = body.get("token") ?? "";
558
+ if (client === null || !presented)
559
+ return oauthError("invalid_request", "client_id and token are required.");
560
+ await link.revokeToken({ ...client, token: presented });
561
+ return new Response(null, { status: 200, headers: { "Cache-Control": "no-store" } });
562
+ }
563
+ async function grant(platform, link, request) {
564
+ const accessToken = bearerToken(request.headers);
565
+ const detail = await link.grant(accessToken);
566
+ return Response.json(await grantBody(platform, accessToken, detail), { headers: { "Cache-Control": "no-store" } });
567
+ }
568
+ /**
569
+ * What the grant's requests used, child tokens' included: `tag=k=v`
570
+ * (repeatable; every one must match) and `since`/`until` (ISO 8601) filter.
571
+ * Input tokens exclude cache reads and writes whatever the protocol.
572
+ */
573
+ async function usage(link, request, params, requestId) {
574
+ const accessToken = bearerToken(request.headers);
575
+ const tags = {};
576
+ for (const pair of params.getAll("tag")) {
577
+ const at = pair.indexOf("=");
578
+ const key = pair.slice(0, at).trim();
579
+ if (at <= 0 || !key)
580
+ throw new HttpError(400, "Each tag filter must be key=value.", "invalid_request_error", "tag");
581
+ tags[key] = pair.slice(at + 1).trim();
582
+ }
583
+ const time = (name) => {
584
+ const value = params.get(name);
585
+ if (value === null)
586
+ return undefined;
587
+ const date = new Date(value);
588
+ if (Number.isNaN(date.getTime())) {
589
+ throw new HttpError(400, `${name} must be an ISO 8601 time.`, "invalid_request_error", name);
590
+ }
591
+ return date;
592
+ };
593
+ const since = time("since");
594
+ const until = time("until");
595
+ // `group_by=tag:<key>` also totals the requests by that tag's values.
596
+ const groupBy = params.get("group_by");
597
+ const groupByTag = groupBy === null ? undefined : groupBy.startsWith("tag:") ? groupBy.slice(4).trim() : "";
598
+ if (groupByTag !== undefined && (groupByTag === "" || groupByTag.length > MAX_TAG_KEY_CHARS)) {
599
+ throw new HttpError(400, "group_by must be tag:<key>.", "invalid_request_error", "group_by");
600
+ }
601
+ const result = await link.usage({
602
+ accessToken,
603
+ tags,
604
+ ...(since === undefined ? {} : { since }),
605
+ ...(until === undefined ? {} : { until }),
606
+ ...(groupByTag === undefined ? {} : { groupByTag }),
607
+ ...(requestId === undefined ? {} : { requestId }),
608
+ });
609
+ // One request's usage (its `X-Request-Id`) is a 404 until it is recorded,
610
+ // a moment after its response ends.
611
+ if (requestId !== undefined && result.requests === 0) {
612
+ throw new HttpError(404, `No recorded request ${requestId} of this grant yet.`, "not_found");
613
+ }
614
+ const totals = (value) => ({
615
+ requests: value.requests,
616
+ errors: value.errors,
617
+ input_tokens: value.inputTokens,
618
+ output_tokens: value.outputTokens,
619
+ cache_read_tokens: value.cacheReadTokens,
620
+ cache_write_tokens: value.cacheWriteTokens,
621
+ });
622
+ return Response.json({
623
+ ...totals(result),
624
+ complete_through: result.completeThrough,
625
+ by_model: result.byModel.map((entry) => ({ model: entry.model, thinking: entry.thinking, ...totals(entry) })),
626
+ ...(result.byTag === undefined
627
+ ? {}
628
+ : { by_tag: result.byTag.map((entry) => ({ value: entry.value, ...totals(entry) })) }),
629
+ }, { headers: { "Cache-Control": "no-store" } });
630
+ }
631
+ function stringFields(body) {
632
+ return Object.fromEntries(Object.entries(body).flatMap(([key, value]) => typeof value === "string" ? [[key, value]] : typeof value === "number" ? [[key, String(value)]] : []));
633
+ }
634
+ async function tokenResponse(platform, link, tokens) {
635
+ return Response.json({
636
+ access_token: tokens.accessToken,
637
+ token_type: "Bearer",
638
+ expires_in: tokens.expiresIn,
639
+ refresh_token: tokens.refreshToken,
640
+ ...(await grantBody(platform, tokens.accessToken, await link.grant(tokens.accessToken))),
641
+ }, { headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });
642
+ }
643
+ /**
644
+ * What a grant lets its app do: each granted plan, which clients it serves,
645
+ * its quota, and the models it serves now, by the names a request uses.
646
+ * `models` is what a plain API client (anything but Claude Code or Muse Code)
647
+ * can name, and `routes` whether `dari/routing` serves it.
648
+ */
649
+ async function grantBody(platform, accessToken, detail) {
650
+ const approval = platform.link?.approval;
651
+ const now = Date.now();
652
+ const kinds = detail.subscriptions
653
+ .filter((subscription) => subscription.apiKeyProvider === undefined)
654
+ .map((subscription) => subscription.provider);
655
+ const clients = new Set([undefined, ...kinds.map(subscriptionClient)]);
656
+ const served = new Map();
657
+ for (const client of clients)
658
+ served.set(client, await servedRouter(platform, accessToken, client));
659
+ const models = (router) => router?.link_models ?? router?.enabled_models ?? [];
660
+ const plain = served.get(undefined);
661
+ return {
662
+ grant_id: detail.id,
663
+ client_id: detail.clientId,
664
+ app_name: detail.appName,
665
+ created_at: detail.createdAt,
666
+ scope: LINK_SCOPE,
667
+ // Each budget window: the tokens the grant used in it and its cap.
668
+ budget: detail.budget.map((standing) => ({
669
+ window_minutes: standing.windowMinutes,
670
+ max_tokens: standing.maxTokens,
671
+ used_tokens: standing.usedTokens,
672
+ resets_at: standing.resetsAt,
673
+ })),
674
+ // `budget_limit` while a window is at its cap, until `available_at`.
675
+ ...grantState(detail.budget),
676
+ // The Dari account that approved the grant, when accounts have one.
677
+ user: detail.user,
678
+ // Where the user manages this grant; null without a signed-in app.
679
+ manage_url: approval !== undefined && "consentUrl" in approval ? manageUrl(approval.connectedAppsUrl, detail.id) : null,
680
+ plans: detail.subscriptions.map((subscription) => {
681
+ // An API key serves its provider's models to any app.
682
+ const keyFor = subscription.apiKeyProvider;
683
+ const kind = subscription.provider;
684
+ const client = keyFor === undefined ? subscriptionClient(kind) : undefined;
685
+ return {
686
+ ...planState(subscription, now),
687
+ id: subscription.id,
688
+ kind: keyFor === undefined ? kind : API_KEY,
689
+ // What to call it on screen: "Claude", "ChatGPT", "OpenRouter".
690
+ title: keyFor === undefined ? KINDS[kind]?.name ?? kind : subscription.name,
691
+ ...(keyFor === undefined ? {} : { provider: keyFor }),
692
+ // A gateway key serves any model named with this prefix; `models` lists none.
693
+ ...(keyFor !== undefined && gatewayFor(keyFor) !== undefined ? { model_prefix: `${keyFor}/` } : {}),
694
+ plan: keyFor === undefined ? SUBSCRIPTION_PLAN_LABELS[kind] ?? kind : `${subscription.name} API Key`,
695
+ label: planLabel(subscription),
696
+ account_email: subscription.accountEmail,
697
+ serves: client === undefined ? "any_app" : `${client}_only`,
698
+ unavailable_until: subscription.unavailableUntil,
699
+ usage: subscription.usage.map((window) => ({
700
+ window_minutes: window.minutes,
701
+ utilization: window.utilization,
702
+ resets_at: window.resetsAt,
703
+ })),
704
+ models: models(served.get(client))
705
+ .filter((model) => providerForModel(model) === (keyFor ?? subscriptionModelProvider(kind)))
706
+ .map(namedModel),
707
+ };
708
+ }),
709
+ models: models(plain).map(namedModel),
710
+ routes: (plain?.enabled_models.length ?? 0) > 0,
711
+ };
712
+ }
713
+ function manageUrl(connectedAppsUrl, grantId) {
714
+ const url = new URL(connectedAppsUrl);
715
+ url.searchParams.set("grant", grantId);
716
+ return url.toString();
717
+ }
718
+ /** The latest of some times, or null for none. */
719
+ function latest(times) {
720
+ return times.reduce((last, time) => last === null || Date.parse(time) > Date.parse(last) ? time : last, null);
721
+ }
722
+ /**
723
+ * Whether a granted plan serves the app now. `plan_limit`: the plan is at its
724
+ * own usage limit, available again at `available_at` (null when ready or not
725
+ * known).
726
+ */
727
+ function planState(subscription, now) {
728
+ const planTimes = [
729
+ ...(subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? [subscription.unavailableUntil] : []),
730
+ ...subscription.usage.filter((window) => window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
731
+ ];
732
+ return planTimes.length > 0 ? { state: "plan_limit", available_at: latest(planTimes) } : { state: "ready", available_at: null };
733
+ }
734
+ /** Whether the grant is within its budget: `budget_limit` until every window at its cap rolls on. */
735
+ function grantState(budget) {
736
+ const times = budget.flatMap((standing) => standing.resetsAt === null ? [] : [standing.resetsAt]);
737
+ return times.length > 0 ? { state: "budget_limit", available_at: latest(times) } : { state: "ready", available_at: null };
738
+ }
739
+ // A model as a request names it, with its catalog display name.
740
+ function namedModel(model) {
741
+ return { id: explicitModelSlug(model), name: canonicalModelName(model) };
742
+ }
743
+ // A person's name for a plan: their label, else the account, else the plan.
744
+ function planLabel(subscription) {
745
+ if (subscription.apiKeyProvider !== undefined)
746
+ return subscription.label ?? subscription.name;
747
+ const kind = subscription.provider;
748
+ return subscription.label ?? subscription.accountEmail ?? SUBSCRIPTION_PLAN_LABELS[kind] ?? kind;
749
+ }
750
+ // What the default router serves this token for a client right now.
751
+ async function servedRouter(platform, accessToken, clientHarness) {
752
+ try {
753
+ return await platform.resolveRouter({
754
+ routerId: DEFAULT_ROUTER_ALIAS,
755
+ apiKey: accessToken,
756
+ provisional: true,
757
+ ...(clientHarness ? { clientHarness } : {}),
758
+ });
759
+ }
760
+ catch (error) {
761
+ if (error instanceof HttpError && error.status === 424)
762
+ return null;
763
+ throw error;
764
+ }
765
+ }
766
+ /**
767
+ * An OAuth endpoint's refusals in the OAuth error shape. `invalid_client` is
768
+ * a 401 (RFC 6749 section 5.2), and `refresh_race` is an `invalid_grant` whose
769
+ * `error_code` tells a lost rotation race from a dead refresh token.
770
+ */
771
+ async function oauthEndpoint(respond) {
772
+ try {
773
+ return await respond();
774
+ }
775
+ catch (error) {
776
+ if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "invalid_client"))
777
+ throw error;
778
+ if (error.code === "invalid_client") {
779
+ return oauthError("invalid_client", error.message, 401, { "WWW-Authenticate": 'Basic realm="dari-link"' });
780
+ }
781
+ if (error.code === "refresh_race")
782
+ return oauthError("invalid_grant", error.message, 400, {}, "refresh_race");
783
+ return oauthError(error.code, error.message);
784
+ }
785
+ }
786
+ function oauthError(error, description, status = 400, headers = {}, errorCode) {
787
+ return Response.json({ error, ...(errorCode === undefined ? {} : { error_code: errorCode }), error_description: description }, { status, headers: { "Cache-Control": "no-store", ...headers } });
788
+ }
789
+ // A space- or comma-separated list parameter.
790
+ function listParam(value) {
791
+ return [...new Set((value ?? "").split(/[\s,]+/).filter(Boolean))];
792
+ }
793
+ /**
794
+ * The validated authorization request, or the response that ends it. Until
795
+ * the client and redirect URI check out, errors are shown on the page, never
796
+ * redirected (RFC 6749 section 4.1.2.1).
797
+ */
798
+ async function authorizeRequest(link, params) {
799
+ const clientId = params.get("client_id") ?? "";
800
+ const redirectUri = params.get("redirect_uri") ?? "";
801
+ const app = clientId ? await link.app(clientId) : null;
802
+ if (app === null || !app.redirectUris.includes(redirectUri)) {
803
+ 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 });
804
+ }
805
+ const state = params.get("state");
806
+ const responseMode = params.get("response_mode");
807
+ const webMessage = responseMode === WEB_MESSAGE;
808
+ if (responseMode !== null && responseMode !== "query" && !webMessage) {
809
+ return badRequest(`response_mode is query or ${WEB_MESSAGE}.`);
810
+ }
811
+ if (params.get("response_type") !== "code") {
812
+ return badRequest("response_type must be code.");
813
+ }
814
+ const codeChallenge = params.get("code_challenge") ?? "";
815
+ if (params.get("code_challenge_method") !== "S256" || !CHALLENGE.test(codeChallenge)) {
816
+ return badRequest("PKCE with code_challenge_method=S256 is required.");
817
+ }
818
+ const scope = params.get("scope");
819
+ if (scope !== null && scope.trim() !== "" && scope.trim() !== LINK_SCOPE) {
820
+ return badRequest(`The only scope is ${LINK_SCOPE}.`);
821
+ }
822
+ const clients = listParam(params.get("client"));
823
+ if (!clients.every((client) => CLIENTS.includes(client))) {
824
+ return badRequest(`client lists the clients the app runs: ${CLIENTS.join(", ")}.`);
825
+ }
826
+ const plans = listParam(params.get("plans"));
827
+ if (!plans.every((plan) => OFFER_KINDS.includes(plan))) {
828
+ return badRequest(`plans lists the kinds to offer: ${OFFER_KINDS.join(", ")}.`);
829
+ }
830
+ const keyProviders = listParam(params.get("key_providers"));
831
+ if (!keyProviders.every((provider) => /^[a-z0-9-]{1,64}$/.test(provider))) {
832
+ return badRequest("key_providers lists the providers whose API keys the app can use, such as anthropic openrouter.");
833
+ }
834
+ const purposes = {};
835
+ for (const audience of PLAN_AUDIENCES) {
836
+ const purpose = params.get(`purpose_${audience}`)?.trim();
837
+ if (purpose)
838
+ purposes[audience] = purpose.slice(0, MAX_PURPOSE_CHARS);
839
+ }
840
+ const grantId = params.get("grant_id");
841
+ if (grantId !== null && !GRANT_ID.test(grantId)) {
842
+ return badRequest("grant_id names one of the user's grants for this app.");
843
+ }
844
+ return {
845
+ app,
846
+ redirectUri,
847
+ state,
848
+ webMessage,
849
+ codeChallenge,
850
+ clients: clients,
851
+ plans: plans.length === 0 ? null : plans,
852
+ keyProviders: keyProviders.length === 0 ? null : keyProviders,
853
+ purposes,
854
+ grantId,
855
+ };
856
+ }
857
+ async function authorizePage(link, request, params) {
858
+ const authorize = await authorizeRequest(link, params);
859
+ if (authorize instanceof Response)
860
+ return authorize;
861
+ const approval = link.approval;
862
+ if ("consentUrl" in approval) {
863
+ // The platform's own page signs the user in and approves; it gets the
864
+ // request as validated here.
865
+ return new Response(null, {
866
+ status: 303,
867
+ headers: { Location: `${approval.consentUrl}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" },
868
+ });
869
+ }
870
+ const secret = approval.sessionSecret();
871
+ const session = sessionFrom(request, secret);
872
+ const connect = session === null ? null : connectFrom(request, secret);
873
+ if (session !== null && connect !== null) {
874
+ // A provider that gave the user a code to enter is asked whether they approved.
875
+ return connect.userCode === null
876
+ ? providerPage(authorize, connect)
877
+ : await finishConnect(approval, request, authorize, session, connect, "");
878
+ }
879
+ return await homePage(approval, authorize, session);
880
+ }
881
+ // Where the user stands without a sign-in under way: choosing among the plans
882
+ // they connected, or at the start.
883
+ async function homePage(approval, authorize, session) {
884
+ const current = await grantToUpdate(approval, authorize, session);
885
+ if (current instanceof Response)
886
+ return current;
887
+ if (session === null)
888
+ return introPage(approval, authorize);
889
+ const subscriptions = await approval.subscriptions(session.subject);
890
+ return shareable(authorize, subscriptions).length > 0
891
+ ? choosePage(authorize, session, subscriptions, current)
892
+ : introPage(approval, authorize);
893
+ }
894
+ // In update mode, the grant being changed. A grant this browser's user does
895
+ // not hold (another browser, cleared cookies) starts a new connection instead,
896
+ // as Plaid Link does.
897
+ async function grantToUpdate(approval, authorize, session) {
898
+ if (authorize.grantId === null)
899
+ return null;
900
+ const grant = session === null ? null : await approval.grant(session.subject, authorize.grantId, authorize.app.clientId);
901
+ if (grant === null)
902
+ authorize.grantId = null;
903
+ return grant;
904
+ }
905
+ async function authorizeSubmit(link, request, form) {
906
+ // A platform with its own consent page takes no approval here.
907
+ if ("consentUrl" in link.approval)
908
+ return errorResponse(new HttpError(404, "Not found", "not_found"));
909
+ const approval = link.approval;
910
+ // Only the page itself submits here: another site's form would otherwise
911
+ // arrive without the user's cookie and replace it with a new identity.
912
+ if (crossSite(request)) {
913
+ return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open Dari Link from the app again.</p></div>`, { status: 403 });
914
+ }
915
+ const authorize = await authorizeRequest(link, form);
916
+ if (authorize instanceof Response)
917
+ return authorize;
918
+ const back = { redirectUri: authorize.redirectUri, state: authorize.state, webMessage: authorize.webMessage };
919
+ const secret = approval.sessionSecret();
920
+ const session = sessionFrom(request, secret);
921
+ const endConnect = clearCookie(request, CONNECT_COOKIE);
922
+ // A plan's or a key provider's row on the select page is its own submit button.
923
+ const kind = form.get("connect");
924
+ const keyProvider = keyProviders(approval, authorize).find((provider) => provider.id === (form.get("key") ?? form.get("key_provider")));
925
+ if (form.get("key") !== null && form.get("decision") === null) {
926
+ return keyProvider === undefined
927
+ ? selectPage(approval, authorize, "Choose a provider to add a key for.", [endConnect])
928
+ : keyPage(authorize, keyProvider, undefined, [endConnect]);
929
+ }
930
+ const decision = kind !== null ? "connect" : form.get("decision");
931
+ if (decision === "deny")
932
+ return redirect(back, { error: "access_denied" }, [endConnect]);
933
+ if (decision === "select")
934
+ return selectPage(approval, authorize, undefined, [endConnect]);
935
+ if (decision === "connect") {
936
+ if (!connectKinds(approval, authorize).includes(kind)) {
937
+ return selectPage(approval, authorize, "Choose a subscription to connect.", [endConnect]);
938
+ }
939
+ // A first plan makes the user: an opaque subject the cookie remembers.
940
+ const subject = session?.subject ?? `lu_${randomUUID().replaceAll("-", "")}`;
941
+ let started;
942
+ try {
943
+ started = await approval.startConnect(subject, kind);
944
+ }
945
+ catch (error) {
946
+ if (!(error instanceof HttpError))
947
+ throw error;
948
+ // A gateway that cannot take subscriptions says why; anything else is the provider.
949
+ const reason = error.code === "link_not_configured" ? error.message : `Could not reach ${KINDS[kind].at}. Try again.`;
950
+ return selectPage(approval, authorize, reason, [endConnect]);
951
+ }
952
+ return seeAuthorize(authorize, [
953
+ signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS),
954
+ signedCookie(request, secret, CONNECT_COOKIE, { session: started.session, kind, url: started.authorizationUrl, code: started.userCode }, CONNECT_SECONDS),
955
+ ]);
956
+ }
957
+ if (decision === "add_key") {
958
+ if (keyProvider === undefined)
959
+ return selectPage(approval, authorize, "Choose a provider to add a key for.", [endConnect]);
960
+ const apiKey = form.get("api_key")?.trim() ?? "";
961
+ if (!apiKey)
962
+ return keyPage(authorize, keyProvider, `Paste your ${keyProvider.name} API key.`);
963
+ const subject = session?.subject ?? `lu_${randomUUID().replaceAll("-", "")}`;
964
+ try {
965
+ await approval.addKey(subject, keyProvider.id, apiKey);
966
+ }
967
+ catch (error) {
968
+ if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "link_not_configured"))
969
+ throw error;
970
+ return keyPage(authorize, keyProvider, error.message);
971
+ }
972
+ return seeAuthorize(authorize, [signedCookie(request, secret, USER_COOKIE, { sub: subject }, USER_SECONDS), endConnect]);
973
+ }
974
+ const connect = session === null ? null : connectFrom(request, secret);
975
+ if (decision === "complete" && session !== null && connect !== null) {
976
+ return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
977
+ }
978
+ // Removing a plan or key asks once, then deletes what Dari stored for it.
979
+ const removing = form.get("remove") ?? form.get("remove_id");
980
+ if (removing !== null && session !== null) {
981
+ const subscription = (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
982
+ if (subscription !== undefined && decision !== "remove")
983
+ return removePage(authorize, session, subscription);
984
+ if (subscription !== undefined && sameText(form.get("csrf") ?? "", session.csrf))
985
+ await approval.remove(session.subject, removing);
986
+ return seeAuthorize(authorize, [endConnect]);
987
+ }
988
+ // Anything else goes back to where the user stands.
989
+ if (decision !== "approve" || session === null)
990
+ return seeAuthorize(authorize, [endConnect]);
991
+ if (!sameText(form.get("csrf") ?? "", session.csrf)) {
992
+ return page("Approval Expired", `<div class="body"><h1>Approval Expired</h1><p>This approval is no longer valid. Go back to the app and start again.</p></div>`, { status: 403 });
993
+ }
994
+ const current = await grantToUpdate(approval, authorize, session);
995
+ if (current instanceof Response)
996
+ return current;
997
+ const subscriptions = await approval.subscriptions(session.subject);
998
+ const credentialIds = [...new Set(form.getAll("credential_id"))];
999
+ if (credentialIds.length === 0)
1000
+ return choosePage(authorize, session, subscriptions, current, "Choose at least one subscription.");
1001
+ const usable = new Set(shareable(authorize, subscriptions).map((subscription) => subscription.id));
1002
+ if (!credentialIds.every((id) => usable.has(id))) {
1003
+ return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
1004
+ }
1005
+ try {
1006
+ const { code } = await approval.approve({
1007
+ subject: session.subject,
1008
+ ...(authorize.grantId !== null ? { grantId: authorize.grantId } : {}),
1009
+ clientId: authorize.app.clientId,
1010
+ redirectUri: authorize.redirectUri,
1011
+ codeChallenge: authorize.codeChallenge,
1012
+ credentialIds,
1013
+ // The user sets a limit where they manage the connection, not here.
1014
+ budget: current?.budget ?? [],
1015
+ });
1016
+ return redirect(back, { code }, [endConnect]);
1017
+ }
1018
+ catch (error) {
1019
+ if (error instanceof HttpError && error.status === 400) {
1020
+ return choosePage(authorize, session, subscriptions, current, error.message);
1021
+ }
1022
+ throw error;
1023
+ }
1024
+ }
1025
+ // Finish a provider sign-in: with the code the user pasted, or by asking the
1026
+ // provider whether the user approved the code it gave them.
1027
+ async function finishConnect(approval, request, authorize, session, connect, authorizationResponse) {
1028
+ const endConnect = clearCookie(request, CONNECT_COOKIE);
1029
+ let connected;
1030
+ try {
1031
+ connected = await approval.completeConnect(session.subject, connect.session, authorizationResponse);
1032
+ }
1033
+ catch (error) {
1034
+ if (!(error instanceof HttpError) || error.status !== 400)
1035
+ throw error;
1036
+ // A pasted code can be pasted again; a sign-in the provider ended starts over.
1037
+ return connect.userCode === null
1038
+ ? providerPage(authorize, connect, error.message)
1039
+ : selectPage(approval, authorize, error.message, [endConnect]);
1040
+ }
1041
+ return connected === null ? providerPage(authorize, connect) : seeAuthorize(authorize, [endConnect]);
1042
+ }
1043
+ // Back to the approval page by GET, so no form is left to resubmit.
1044
+ function seeAuthorize(authorize, cookies) {
1045
+ const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
1046
+ for (const cookie of cookies)
1047
+ headers.append("Set-Cookie", cookie);
1048
+ return new Response(null, { status: 303, headers });
1049
+ }
1050
+ // A plan limited to one client serves the app only when the app runs it.
1051
+ function usableBy(kind, clients) {
1052
+ const only = subscriptionClient(kind);
1053
+ return only === undefined || clients.includes(only);
1054
+ }
1055
+ // The kinds of plan the user can connect for this app: those it asked for and can use.
1056
+ function connectKinds(approval, authorize) {
1057
+ return approval.connectable.filter((kind) => (authorize.plans === null || authorize.plans.includes(kind)) && usableBy(kind, authorize.clients));
1058
+ }
1059
+ // Whose API key the user can add for this app: none when it asked only for
1060
+ // plans, and only the providers it named when it named some.
1061
+ function keyProviders(approval, authorize) {
1062
+ if (authorize.plans !== null && !authorize.plans.includes(API_KEY))
1063
+ return [];
1064
+ return approval.keyProviders.filter((provider) => authorize.keyProviders === null || authorize.keyProviders.includes(provider.id));
1065
+ }
1066
+ // The user's plans and API keys the app asked for and can use. A key serves any app.
1067
+ function shareable(authorize, subscriptions) {
1068
+ return subscriptions.filter((subscription) => {
1069
+ if (subscription.apiKeyProvider !== undefined) {
1070
+ return (authorize.plans === null || authorize.plans.includes(API_KEY))
1071
+ && (authorize.keyProviders === null || authorize.keyProviders.includes(subscription.apiKeyProvider));
1072
+ }
1073
+ const kind = subscription.provider;
1074
+ return (authorize.plans === null || authorize.plans.includes(kind)) && usableBy(kind, authorize.clients);
1075
+ });
1076
+ }
1077
+ function sessionFrom(request, secret) {
1078
+ const subject = readSigned(request, secret, USER_COOKIE)?.sub;
1079
+ return typeof subject === "string" ? { subject, csrf: sign(secret, `csrf\0${subject}`) } : null;
1080
+ }
1081
+ function connectFrom(request, secret) {
1082
+ const value = readSigned(request, secret, CONNECT_COOKIE);
1083
+ if (value === null || typeof value.session !== "string" || typeof value.url !== "string"
1084
+ || !PLAN_KINDS.includes(value.kind)) {
1085
+ return null;
1086
+ }
1087
+ return {
1088
+ session: value.session,
1089
+ kind: value.kind,
1090
+ url: value.url,
1091
+ userCode: typeof value.code === "string" ? value.code : null,
1092
+ };
1093
+ }
1094
+ // A signed cookie's payload: `<payload>.<HMAC-SHA256>`, where the payload
1095
+ // holds the value and when it ends.
1096
+ function readSigned(request, secret, cookie) {
1097
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
1098
+ const [name, ...rest] = part.trim().split("=");
1099
+ if (name !== cookie)
1100
+ continue;
1101
+ const [payload, signature] = rest.join("=").split(".");
1102
+ if (!payload || !signature || !sameText(signature, sign(secret, `${cookie}\0${payload}`)))
1103
+ return null;
1104
+ try {
1105
+ const value = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1106
+ if (typeof value !== "object" || value === null)
1107
+ return null;
1108
+ const exp = value.exp;
1109
+ return typeof exp === "number" && exp > Date.now() ? value : null;
1110
+ }
1111
+ catch {
1112
+ return null;
1113
+ }
1114
+ }
1115
+ return null;
1116
+ }
1117
+ function signedValue(secret, cookie, value, seconds) {
1118
+ const payload = Buffer.from(JSON.stringify({ ...value, exp: Date.now() + seconds * 1000 })).toString("base64url");
1119
+ return `${payload}.${sign(secret, `${cookie}\0${payload}`)}`;
1120
+ }
1121
+ function signedCookie(request, secret, cookie, value, seconds) {
1122
+ return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${AUTHORIZE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1123
+ }
1124
+ function clearCookie(request, cookie) {
1125
+ return `${cookie}=; Path=${AUTHORIZE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
1126
+ }
1127
+ /**
1128
+ * The `Cookie` header value that makes a request this user's on the approval
1129
+ * page, for a platform's own tooling (the stub gateway approves with it).
1130
+ */
1131
+ export function linkUserCookie(secret, subject) {
1132
+ return `${USER_COOKIE}=${signedValue(secret, USER_COOKIE, { sub: subject }, USER_SECONDS)}`;
1133
+ }
1134
+ function sign(secret, value) {
1135
+ return createHmac("sha256", secret).update(value).digest("base64url");
1136
+ }
1137
+ function sameText(a, b) {
1138
+ return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
1139
+ }
1140
+ // Return the result to the app: on its redirect URI, or posted to the window
1141
+ // that opened this page, which only the redirect URI's origin can read.
1142
+ function redirect(back, params, cookies = []) {
1143
+ if (back.webMessage) {
1144
+ const message = { type: LINK_MESSAGE_TYPE, ...params, ...(back.state !== null ? { state: back.state } : {}) };
1145
+ const nonce = randomUUID();
1146
+ // `<` is escaped so the JSON cannot close the script element.
1147
+ // Without an opener (a sign-in can sever it), the result goes to the
1148
+ // redirect URI, whose page hands it on with `DariLink.callback()`.
1149
+ const json = JSON.stringify([message, new URL(back.redirectUri).origin, queryRedirect(back, params)])
1150
+ .replaceAll("<", "\\u003c");
1151
+ const connected = "code" in params;
1152
+ return page(connected ? "Success" : "Returning To The App", `<div class="body center">${connected ? `<span class="done">${ICONS.check}</span><h1>Success</h1><p>You are connected.` : `<h1>Returning To The App</h1><p>`} You can close this window.</p></div>
1153
+ <script nonce="${nonce}">const [message, origin, fallback] = ${json};
1154
+ if (window.opener) { window.opener.postMessage(message, origin); window.close(); } else { window.location.replace(fallback); }</script>`, { cookies, scriptNonce: nonce });
1155
+ }
1156
+ const headers = new Headers({ Location: queryRedirect(back, params), "Cache-Control": "no-store" });
1157
+ for (const cookie of cookies)
1158
+ headers.append("Set-Cookie", cookie);
1159
+ return new Response(null, { status: 303, headers });
1160
+ }
1161
+ // The redirect URI with the result in its query.
1162
+ function queryRedirect(back, params) {
1163
+ const url = new URL(back.redirectUri);
1164
+ for (const [name, value] of Object.entries(params))
1165
+ url.searchParams.set(name, value);
1166
+ if (back.state !== null)
1167
+ url.searchParams.set("state", back.state);
1168
+ return url.toString();
1169
+ }
1170
+ function eventFor(authorize, step) {
1171
+ if (!authorize.webMessage)
1172
+ return undefined;
1173
+ return {
1174
+ message: { type: LINK_EVENT_TYPE, version: "1", event: step, ...(authorize.state !== null ? { state: authorize.state } : {}) },
1175
+ origin: new URL(authorize.redirectUri).origin,
1176
+ };
1177
+ }
1178
+ // How a kind of plan reads on the page, and whose sign-in connects it.
1179
+ const KINDS = {
1180
+ anthropic_claude_code: { name: "Claude", plan: "Pro, Max or Ultra plan", at: "Claude" },
1181
+ openai_codex: { name: "ChatGPT", plan: "Plus or Pro plan", at: "OpenAI" },
1182
+ meta_muse: { name: "Meta Muse", plan: "Muse Code plan", at: "Meta" },
1183
+ opencode_go: { name: "OpenCode Go", plan: "Go plan", at: "OpenCode" },
1184
+ };
1185
+ // The first page a new user sees: what connecting means, and one button.
1186
+ function introPage(approval, authorize) {
1187
+ const app = escapeHtml(authorize.app.name);
1188
+ const kinds = connectKinds(approval, authorize);
1189
+ const keys = keyProviders(approval, authorize);
1190
+ if (kinds.length === 0 && keys.length === 0) {
1191
+ return page(`Connect ${authorize.app.name}`, `<div class="body"><h1>Nothing To Connect</h1><p><strong>${app}</strong> asks for a kind of subscription Dari cannot connect here.</p></div>`, { event: eventFor(authorize, "connect_subscription") });
1192
+ }
1193
+ const names = [...kinds.map((kind) => KINDS[kind].name), ...(keys.length > 0 ? ["an API key"] : [])];
1194
+ const ways = names.length > 1 ? `${names.slice(0, -1).join(", ")} or ${names.at(-1)}` : names[0];
1195
+ return pane(authorize, {
1196
+ title: `Connect ${authorize.app.name}`,
1197
+ step: "connect_subscription",
1198
+ body: `<div class="pair"><span class="tile">${escapeHtml(authorize.app.name.trim().charAt(0).toUpperCase())}</span><span class="join"></span>${DARI_MARK}</div>
1199
+ <h1 class="lead">${app} Uses Dari To Connect Your AI ${kinds.length > 0 ? "Subscriptions" : "API Keys"}</h1>
1200
+ <p class="returns">Returns to ${escapeHtml(new URL(authorize.redirectUri).host)}</p>
1201
+ <ul class="points">
1202
+ <li>${ICONS.zap}<div><strong>Connect In Seconds</strong><p>${kinds.length > 0 ? `Use what you already pay for: ${escapeHtml(ways)}.` : "Add the API key you already have."}</p></div></li>
1203
+ <li>${ICONS.shield}<div><strong>You Stay In Control</strong><p>${app} can only send model requests on what you share. It sees each shared plan's account email, never a key or your other plans, and you can disconnect it any time.</p></div></li>
1204
+ </ul>`,
1205
+ footer: `<button class="btn primary" type="submit" name="decision" value="select">Continue</button>`,
1206
+ });
1207
+ }
1208
+ // What to connect, as a grid of tiles: each kind of plan starts its
1209
+ // provider's sign-in, and each provider below takes an API key.
1210
+ function selectPage(approval, authorize, error, cookies = []) {
1211
+ const plans = connectKinds(approval, authorize).map((kind) => `<button class="option" type="submit" name="connect" value="${kind}" formnovalidate>${logo(kind, KINDS[kind].name)}<span><strong>${KINDS[kind].name}</strong><small>${KINDS[kind].plan}</small></span></button>`);
1212
+ const keys = keyProviders(approval, authorize).map((provider) => `<button class="option slim" type="submit" name="key" value="${escapeHtml(provider.id)}" formnovalidate>${logo(provider.id, provider.name)}<strong>${escapeHtml(provider.name)}</strong></button>`);
1213
+ return pane(authorize, {
1214
+ title: `Connect ${authorize.app.name}`,
1215
+ step: "connect_subscription",
1216
+ back: "home",
1217
+ error,
1218
+ cookies,
1219
+ body: `<h1>${plans.length === 0 ? "Add An API Key" : keys.length === 0 ? "Select Your Subscription" : "Choose What To Connect"}</h1>
1220
+ ${plans.length > 0 ? `${keys.length > 0 ? `<p class="label">Subscriptions</p>\n` : ""}<div class="grid">\n${plans.join("\n")}\n</div>` : ""}
1221
+ ${keys.length > 0 ? `${plans.length > 0 ? `<p class="label">API Keys</p>\n` : ""}<div class="grid">\n${keys.join("\n")}\n</div>` : ""}`,
1222
+ });
1223
+ }
1224
+ // One provider's API key, pasted once.
1225
+ function keyPage(authorize, provider, error, cookies = []) {
1226
+ const name = escapeHtml(provider.name);
1227
+ return pane(authorize, {
1228
+ title: `Add Your ${provider.name} API Key`,
1229
+ step: "connect_subscription",
1230
+ back: "select",
1231
+ error,
1232
+ cookies,
1233
+ body: `<span class="who">${logo(provider.id, provider.name)}</span>
1234
+ <h1>Add Your ${name} API Key</h1>
1235
+ <input type="hidden" name="key_provider" value="${escapeHtml(provider.id)}">
1236
+ <label class="field" for="api_key">API Key</label>
1237
+ <input id="api_key" type="password" name="api_key" autocomplete="off" spellcheck="false" placeholder="Paste Key" required>
1238
+ <p class="hint">Dari keeps the key and uses it only for the apps you allow. ${escapeHtml(authorize.app.name)} never sees it.</p>`,
1239
+ footer: `<button class="btn primary" type="submit" name="decision" value="add_key">Continue</button>`,
1240
+ });
1241
+ }
1242
+ // The provider's sign-in: a link to it, and the code to bring back or take there.
1243
+ function providerPage(authorize, connect, error) {
1244
+ const { name, at } = KINDS[connect.kind];
1245
+ const open = (style) => `<a class="btn ${style}" href="${escapeHtml(connect.url)}" target="_blank" rel="noopener noreferrer">Open ${name}${ICONS.external}</a>`;
1246
+ const head = `<span class="who">${logo(connect.kind, name)}</span>
1247
+ <h1>Sign In To ${name}</h1>`;
1248
+ if (connect.userCode === null) {
1249
+ return pane(authorize, {
1250
+ title: `Sign In To ${name}`,
1251
+ step: "connect_subscription",
1252
+ back: "select",
1253
+ error,
1254
+ body: `${head}
1255
+ <div class="step"><span class="n">1</span><div><p>Sign in at ${at} and approve.</p>${open("outline")}</div></div>
1256
+ <div class="step"><span class="n">2</span><div><label for="authorization_response">Paste the code ${at} shows you.</label><input id="authorization_response" type="text" name="authorization_response" autocomplete="off" spellcheck="false" placeholder="Paste Code" required></div></div>`,
1257
+ footer: `<button class="btn primary" type="submit" name="decision" value="complete">Continue</button>`,
1258
+ });
1259
+ }
1260
+ return pane(authorize, {
1261
+ title: `Sign In To ${name}`,
1262
+ step: "connect_subscription",
1263
+ back: "select",
1264
+ error,
1265
+ refresh: DEVICE_POLL_SECONDS,
1266
+ body: `${head}
1267
+ <p>Enter this code at ${at} to approve.</p>
1268
+ <p class="code">${escapeHtml(connect.userCode)}</p>
1269
+ <p class="wait"><span class="spin"></span>Waiting for your approval. This window continues on its own.</p>`,
1270
+ footer: open("primary"),
1271
+ });
1272
+ }
1273
+ // The user's plans and keys, ticked: one button shares them with the app.
1274
+ function choosePage(authorize, session, subscriptions, current, error) {
1275
+ const app = escapeHtml(authorize.app.name);
1276
+ const plans = shareable(authorize, subscriptions);
1277
+ // A new connection starts with every plan ticked; an update, with the plans it shares now.
1278
+ const ticked = new Set(current?.credentialIds ?? plans.map((plan) => plan.id));
1279
+ return pane(authorize, {
1280
+ title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
1281
+ step: "choose_plans",
1282
+ error,
1283
+ body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1284
+ <input type="hidden" name="csrf" value="${session.csrf}">
1285
+ ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1286
+ <button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>`,
1287
+ footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1288
+ <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
1289
+ });
1290
+ }
1291
+ // What the user is about to delete, and the one button that deletes it.
1292
+ function removePage(authorize, session, subscription) {
1293
+ const key = subscription.apiKeyProvider;
1294
+ const name = key === undefined ? KINDS[subscription.provider]?.name ?? subscription.name : subscription.name;
1295
+ return pane(authorize, {
1296
+ title: `Remove ${name}`,
1297
+ step: "choose_plans",
1298
+ back: "home",
1299
+ body: `<span class="who">${logo(key ?? subscription.provider, name)}</span>
1300
+ <h1>Remove ${escapeHtml(name)}${key === undefined ? "" : " API Key"}</h1>
1301
+ <p>${escapeHtml(planLabel(subscription))}</p>
1302
+ <p>Dari deletes ${key === undefined ? "the sign-in it holds for this plan" : "this key"}. Every app you shared it with stops using it.</p>
1303
+ <input type="hidden" name="csrf" value="${session.csrf}">
1304
+ <input type="hidden" name="remove_id" value="${escapeHtml(subscription.id)}">`,
1305
+ footer: `<button class="btn danger" type="submit" name="decision" value="remove">Remove</button>`,
1306
+ });
1307
+ }
1308
+ function planOption(authorize, subscription, ticked) {
1309
+ const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}><button class="nav drop" type="submit" name="remove" value="${escapeHtml(subscription.id)}" formnovalidate aria-label="Remove">${ICONS.trash}</button>`;
1310
+ if (subscription.apiKeyProvider !== undefined) {
1311
+ return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key &middot; ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
1312
+ }
1313
+ const kind = subscription.provider;
1314
+ const only = subscriptionClient(kind);
1315
+ const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1316
+ const binding = subscription.usage.reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1317
+ const notes = [
1318
+ planLabel(subscription),
1319
+ ...(subscription.unavailableUntil
1320
+ ? [`At its usage limit until ${new Date(subscription.unavailableUntil).toUTCString()}`]
1321
+ : binding !== null
1322
+ ? [`${Math.round(binding.utilization * 100)}% of its quota used`]
1323
+ : []),
1324
+ ...(purpose ? [`${authorize.app.name} says: ${purpose.replace(/[.\s]+$/, "")}`] : []),
1325
+ ];
1326
+ return `<label class="option pick">${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong><small>${notes.map(escapeHtml).join(" &middot; ")}</small></span>${box}</label>`;
1327
+ }
1328
+ // A provider's mark, or without one the first letter of its name.
1329
+ function logo(id, name) {
1330
+ return linkLogo(id) ?? `<span class="logo letter">${escapeHtml(name.trim().charAt(0).toUpperCase())}</span>`;
1331
+ }
1332
+ function authorizeFields(authorize) {
1333
+ return {
1334
+ response_type: "code",
1335
+ client_id: authorize.app.clientId,
1336
+ redirect_uri: authorize.redirectUri,
1337
+ code_challenge: authorize.codeChallenge,
1338
+ code_challenge_method: "S256",
1339
+ ...(authorize.state !== null ? { state: authorize.state } : {}),
1340
+ ...(authorize.webMessage ? { response_mode: WEB_MESSAGE } : {}),
1341
+ ...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
1342
+ ...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
1343
+ ...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
1344
+ ...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
1345
+ ...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
1346
+ };
1347
+ }
1348
+ function authorizeQuery(authorize) {
1349
+ return new URLSearchParams(authorizeFields(authorize)).toString();
1350
+ }
1351
+ function hiddenFields(authorize) {
1352
+ return Object.entries(authorizeFields(authorize))
1353
+ .map(([name, value]) => `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`)
1354
+ .join("\n");
1355
+ }
1356
+ /**
1357
+ * One step of the approval, as a form: its content, the button that moves on,
1358
+ * and Back and Close in the header. Back and Close come last in the form, so
1359
+ * Enter in a field presses the step's own button.
1360
+ */
1361
+ function pane(authorize, options) {
1362
+ return page(options.title, `<form method="post" action="${AUTHORIZE_PATH}">
1363
+ ${hiddenFields(authorize)}
1364
+ <div class="body">
1365
+ ${options.body}
1366
+ ${options.error === undefined ? "" : `<p role="alert">${escapeHtml(options.error)}</p>`}
1367
+ </div>
1368
+ ${options.footer === undefined ? "" : `<div class="foot">${options.footer}</div>`}
1369
+ ${options.back === undefined ? "" : `<button class="nav back" type="submit" name="decision" value="${options.back}" formnovalidate aria-label="Back">${ICONS.back}</button>`}
1370
+ <button class="nav close" type="submit" name="decision" value="deny" formnovalidate aria-label="Close">${ICONS.close}</button>
1371
+ </form>`, { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh });
1372
+ }
1373
+ function page(title, body, options = {}) {
1374
+ if (options.event !== undefined) {
1375
+ const nonce = options.scriptNonce ?? randomUUID();
1376
+ // `<` is escaped so the JSON cannot close the script element.
1377
+ const json = JSON.stringify([options.event.message, options.event.origin]).replaceAll("<", "\\u003c");
1378
+ body += `\n<script nonce="${nonce}">const [event, eventOrigin] = ${json};
1379
+ if (window.opener) window.opener.postMessage(event, eventOrigin);</script>`;
1380
+ options = { ...options, scriptNonce: nonce };
1381
+ }
1382
+ const html = `<!doctype html>
1383
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
1384
+ ${options.refresh === undefined ? "" : `<meta http-equiv="refresh" content="${options.refresh}">\n`}<title>${escapeHtml(title)}</title>
1385
+ <style>${PAGE_STYLE}</style>
1386
+ </head><body><main><section><header>${DARI_MARK}</header>
1387
+ ${body}
1388
+ </section></main></body></html>`;
1389
+ const headers = new Headers({
1390
+ "Content-Type": "text/html; charset=utf-8",
1391
+ "Cache-Control": "no-store",
1392
+ "Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
1393
+ "X-Frame-Options": "DENY",
1394
+ "Referrer-Policy": "no-referrer",
1395
+ });
1396
+ for (const cookie of options.cookies ?? [])
1397
+ headers.append("Set-Cookie", cookie);
1398
+ return new Response(html, { status: options.status ?? 200, headers });
1399
+ }
1400
+ // Dari's look, by its own tokens: a charcoal sheet set in Geist, ink for the
1401
+ // one main button, hairline rules, rounded controls, and mint only for focus
1402
+ // and success. In a popup the sheet is the window; in a wider tab it is a
1403
+ // dialog on the page. One step shows at a time, its button at the bottom.
1404
+ const PAGE_STYLE = `@font-face{font-family:Geist;src:url(${FONT_PATH}) format("woff2");font-weight:100 900;font-display:swap}
1405
+ :root{color-scheme:dark;--page:#141415;--card:#19191a;--ink:#ededed;--muted:#b9b9bd;--faint:#808087;--rule:#303031;--edge:#404041;--mint:#8ee6bd;--hover:rgba(237,237,237,.05)}
1406
+ *{box-sizing:border-box}
1407
+ html,body{height:100%}
1408
+ body{margin:0;background:var(--card);color:var(--ink);font:450 14px/1.5 Geist,ui-sans-serif,system-ui,sans-serif;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
1409
+ main{min-height:100%;display:flex}
1410
+ section{position:relative;flex:1;display:flex;flex-direction:column;background:var(--card);min-width:0}
1411
+ @media (min-width:560px){body{background:var(--page)}main{align-items:center;justify-content:center;padding:24px}
1412
+ section{flex:none;width:400px;min-height:620px;border:1px solid var(--rule);border-radius:8px;box-shadow:0 25px 50px -12px rgba(0,0,0,.5);overflow:hidden}}
1413
+ header{flex:none;height:52px;display:flex;align-items:center;justify-content:center;border-bottom:1px solid var(--rule)}
1414
+ .mark{width:24px;height:24px}
1415
+ form{flex:1;display:flex;flex-direction:column;min-height:0}
1416
+ .body{flex:1;padding:28px 24px 16px}
1417
+ .foot{flex:none;padding:8px 24px 24px}
1418
+ .center{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding-bottom:64px}
1419
+ h1{font-size:20px;font-weight:550;letter-spacing:-.02em;line-height:1.3;margin:0 0 20px}
1420
+ p{color:var(--muted);margin:0 0 16px}strong{color:var(--ink);font-weight:550}
1421
+ small{display:block;color:var(--faint);font-size:12px;line-height:1.4;overflow-wrap:anywhere}
1422
+ .icon{flex:none;width:16px;height:16px}.logo{flex:none;width:20px;height:20px;color:var(--ink)}
1423
+ .letter{display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--edge);border-radius:4px;font-size:12px;font-weight:550}
1424
+ .pair{display:flex;align-items:center;justify-content:center;gap:12px;margin:20px 0 28px}
1425
+ .pair .mark{width:48px;height:48px}
1426
+ .tile{display:inline-flex;align-items:center;justify-content:center;width:48px;height:48px;border:1px solid var(--edge);border-radius:6px;background:var(--page);font-size:20px;font-weight:550}
1427
+ .join{width:28px;border-top:1px dashed var(--edge)}
1428
+ .lead{text-align:center;margin-bottom:28px}
1429
+ .returns{text-align:center;color:var(--faint);font-size:12px;margin:-20px 0 24px}
1430
+ .points{list-style:none;margin:0;padding:0;border-top:1px solid var(--rule)}
1431
+ .points li{display:flex;gap:12px;padding:16px 0;border-bottom:1px solid var(--rule)}
1432
+ .points .icon{margin-top:3px;color:var(--faint)}.points p{margin:2px 0 0;font-size:13px}
1433
+ .label{color:var(--faint);font-size:12px;margin:20px 0 8px}h1+.label{margin-top:0}
1434
+ .grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
1435
+ .option{display:flex;flex-direction:column;align-items:flex-start;gap:12px;min-width:0;padding:14px 12px 12px;border:1px solid var(--rule);border-radius:6px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;transition:border-color .15s,background-color .15s}
1436
+ .option:hover,.option:has(input:checked){border-color:rgba(237,237,237,.4);background:var(--hover)}
1437
+ .option strong{display:block;font-size:14px;line-height:1.35}
1438
+ .option.slim{flex-direction:row;align-items:center;gap:10px;padding:10px 12px}.slim .logo{width:16px;height:16px}.slim strong{font-size:13px}
1439
+ .option.pick{flex-direction:row;align-items:center;margin:0 0 8px;padding:12px}.grow{flex:1;min-width:0}
1440
+ input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:16px;height:16px;margin:0;border:1px solid rgba(237,237,237,.3);border-radius:4px;background:transparent;cursor:pointer}
1441
+ input[type=checkbox]:checked{border-color:var(--ink);background:var(--ink)}
1442
+ input[type=checkbox]:checked::after{content:"";width:8px;height:4px;margin-top:-2px;border:solid var(--page);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1443
+ .who{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;margin:0 0 16px;border:1px solid var(--rule);border-radius:6px;background:var(--page)}
1444
+ .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
1445
+ .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
1446
+ .field{display:block;font-size:13px;font-weight:550;margin:0 0 8px}
1447
+ input[type=text],input[type=password]{display:block;width:100%;height:36px;padding:0 12px;border:1px solid var(--edge);border-radius:6px;background:var(--page);color:var(--ink);font:13px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
1448
+ input::placeholder{color:var(--faint);font-family:Geist,ui-sans-serif,system-ui,sans-serif}
1449
+ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px solid var(--mint);border-color:var(--mint)}
1450
+ .hint{color:var(--faint);font-size:12px;margin:10px 0 0}
1451
+ .code{margin:0 0 16px;padding:18px 12px;border:1px solid var(--rule);border-radius:8px;background:rgba(237,237,237,.03);color:var(--ink);font:550 20px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.1em;text-align:center;user-select:all}
1452
+ .wait{display:flex;align-items:center;gap:10px;font-size:13px}
1453
+ .spin{flex:none;width:14px;height:14px;border:2px solid var(--edge);border-top-color:var(--ink);border-radius:50%;animation:spin .8s linear infinite}
1454
+ @keyframes spin{to{transform:rotate(360deg)}}
1455
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:36px;padding:0 16px;border-radius:6px;border:1px solid transparent;background:transparent;color:var(--ink);font:550 14px Geist,ui-sans-serif,system-ui,sans-serif;text-decoration:none;white-space:nowrap;cursor:pointer;transition:background-color .15s,border-color .15s}
1456
+ .btn.primary{width:100%;height:44px;font-size:15px;border-color:var(--ink);background:var(--ink);color:var(--page)}.btn.primary:hover{background:rgba(237,237,237,.9)}
1457
+ .btn.danger{width:100%;height:44px;font-size:15px;border-color:#d64548;background:#d64548;color:#fafafa}.btn.danger:hover{background:rgba(214,69,72,.9)}
1458
+ .nav.drop{position:static;flex:none;width:28px;height:28px;margin:0 -4px 0 0;color:var(--faint)}
1459
+ .btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
1460
+ .btn.ghost{height:32px;margin:4px 0 0 -8px;padding:0 10px 0 8px;font-size:13px;color:var(--muted)}.btn.ghost:hover{background:rgba(237,237,237,.06);color:var(--ink)}
1461
+ .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1462
+ .nav{position:absolute;top:10px;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--muted);cursor:pointer}
1463
+ .nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
1464
+ .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}
1465
+ a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
1466
+ [role=alert]{margin:16px 0 0;padding:10px 12px;border:1px solid rgba(214,69,72,.5);border-radius:6px;background:rgba(214,69,72,.1);color:var(--ink);font-size:13px}
1467
+ ::selection{background:var(--mint);color:var(--page)}`;
1468
+ function escapeHtml(value) {
1469
+ return value
1470
+ .replaceAll("&", "&amp;")
1471
+ .replaceAll("<", "&lt;")
1472
+ .replaceAll(">", "&gt;")
1473
+ .replaceAll('"', "&quot;")
1474
+ .replaceAll("'", "&#39;");
1475
+ }
1476
+ /**
1477
+ * Endpoints browser apps call from their own origin. None reads cookies or
1478
+ * other ambient credentials (the verifier, refresh token, or bearer token is
1479
+ * the credential), so any origin may call them.
1480
+ */
1481
+ const CORS_PATHS = new Set([
1482
+ "/v1/link/token",
1483
+ "/v1/link/register",
1484
+ "/v1/link/revoke",
1485
+ "/v1/link/grant",
1486
+ "/v1/link/usage",
1487
+ LINK_METADATA_PATH,
1488
+ ]);
1489
+ function withCors(response) {
1490
+ response.headers.set("Access-Control-Allow-Origin", "*");
1491
+ response.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
1492
+ response.headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
1493
+ response.headers.set("Access-Control-Max-Age", "600");
1494
+ return response;
1495
+ }
1496
+ /**
1497
+ * Served at /v1/link/callback.js for the redirect URI's page, which a strict
1498
+ * CSP may keep from bundling `DariLink.callback()`: when the page's query holds
1499
+ * a Dari Link result (`state` with `code`, or `error`), it posts
1500
+ * `{type: "dari-link", state, code}` or `{type: "dari-link", state, error,
1501
+ * error_description}` on the `dari-link` BroadcastChannel, where the window
1502
+ * that called `DariLink.open` listens, and closes the popup. Both the channel
1503
+ * name and the message shape are stable.
1504
+ */
1505
+ const CALLBACK_SCRIPT = `(function () {
1506
+ var params = new URLSearchParams(window.location.search);
1507
+ var state = params.get("state");
1508
+ var code = params.get("code");
1509
+ var error = params.get("error");
1510
+ if (state === null || (code === null && error === null) || typeof BroadcastChannel === "undefined") return;
1511
+ var message = code !== null
1512
+ ? { type: "dari-link", state: state, code: code }
1513
+ : { type: "dari-link", state: state, error: error, error_description: params.get("error_description") || undefined };
1514
+ var channel = new BroadcastChannel("dari-link");
1515
+ channel.postMessage(message);
1516
+ channel.close();
1517
+ window.close();
1518
+ })();
1519
+ `;