@mupt-ai/dari-gateway 1.0.312 → 1.0.314

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +276 -2
  2. package/dist/context/routing_context.js +4 -1
  3. package/dist/http/handler.d.ts +2 -1
  4. package/dist/http/handler.js +12 -2
  5. package/dist/ingress/anthropic_messages.js +15 -3
  6. package/dist/ingress/chat_completions.js +6 -1
  7. package/dist/ingress/codex.js +2 -2
  8. package/dist/ingress/models.js +46 -2
  9. package/dist/interaction/types.d.ts +1 -0
  10. package/dist/link/assets.d.ts +14 -0
  11. package/dist/link/assets.js +49 -0
  12. package/dist/link/budget.d.ts +27 -0
  13. package/dist/link/budget.js +62 -0
  14. package/dist/link/client.d.ts +382 -0
  15. package/dist/link/client.js +578 -0
  16. package/dist/link/endpoints.d.ts +23 -0
  17. package/dist/link/endpoints.js +1615 -0
  18. package/dist/link/errors.d.ts +30 -0
  19. package/dist/link/errors.js +120 -0
  20. package/dist/link/font.d.ts +1 -0
  21. package/dist/link/font.js +6 -0
  22. package/dist/link/grant_access.d.ts +7 -0
  23. package/dist/link/grant_access.js +99 -0
  24. package/dist/link/grants.d.ts +151 -0
  25. package/dist/link/grants.js +275 -0
  26. package/dist/link/in_flight.d.ts +4 -0
  27. package/dist/link/in_flight.js +43 -0
  28. package/dist/link/key_providers.d.ts +6 -0
  29. package/dist/link/key_providers.js +21 -0
  30. package/dist/link/self_hosted.d.ts +3 -0
  31. package/dist/link/self_hosted.js +166 -0
  32. package/dist/link/service.d.ts +85 -0
  33. package/dist/link/service.js +187 -0
  34. package/dist/link/sqlite_store.d.ts +74 -0
  35. package/dist/link/sqlite_store.js +381 -0
  36. package/dist/models/canonical_models.json +19 -0
  37. package/dist/models/gateways.d.ts +2 -0
  38. package/dist/models/gateways.js +2 -0
  39. package/dist/models/subscriptions.d.ts +8 -1
  40. package/dist/models/subscriptions.js +13 -2
  41. package/dist/platform/platform.d.ts +298 -1
  42. package/dist/protocol/input/router_model.d.ts +4 -0
  43. package/dist/protocol/input/router_model.js +31 -1
  44. package/dist/providers/execution.js +24 -2
  45. package/dist/providers/pi_options.js +57 -1
  46. package/dist/providers/provider_call.d.ts +4 -0
  47. package/dist/providers/provider_call.js +4 -1
  48. package/dist/providers/stream_finalization.d.ts +1 -0
  49. package/dist/runtime/explicit_model.js +16 -4
  50. package/dist/runtime/harness_identity/extract.js +20 -36
  51. package/dist/runtime/prepare_routed_completion.js +5 -1
  52. package/dist/runtime/routed_runtime.js +8 -0
  53. package/dist/runtime/runtime_reporter.d.ts +1 -0
  54. package/dist/runtime/runtime_reporter.js +1 -0
  55. package/dist/self_host/config.d.ts +9 -0
  56. package/dist/self_host/config.js +11 -1
  57. package/dist/self_host/main.d.ts +10 -3
  58. package/dist/self_host/main.js +19 -4
  59. package/dist/self_host/platform.d.ts +2 -2
  60. package/dist/self_host/platform.js +36 -7
  61. package/dist/self_host/resolve.d.ts +8 -0
  62. package/dist/self_host/resolve.js +130 -15
  63. package/dist/self_host/secret_box.d.ts +23 -0
  64. package/dist/self_host/secret_box.js +105 -0
  65. package/dist/self_host/stub_gateway.d.ts +60 -0
  66. package/dist/self_host/stub_gateway.js +397 -0
  67. package/dist/self_host/stub_main.d.ts +2 -0
  68. package/dist/self_host/stub_main.js +69 -0
  69. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  70. package/dist/self_host/subscription_test_gateway.js +25 -91
  71. package/dist/self_host/subscriptions/http.js +3 -2
  72. package/dist/self_host/subscriptions/index.d.ts +2 -2
  73. package/dist/self_host/subscriptions/index.js +2 -2
  74. package/dist/self_host/subscriptions/store.d.ts +41 -16
  75. package/dist/self_host/subscriptions/store.js +136 -32
  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/routing_context.ts +3 -1
  80. package/src/http/handler.ts +14 -2
  81. package/src/ingress/anthropic_messages.ts +19 -4
  82. package/src/ingress/chat_completions.ts +6 -1
  83. package/src/ingress/codex.ts +2 -2
  84. package/src/ingress/models.ts +48 -2
  85. package/src/interaction/types.ts +4 -0
  86. package/src/link/assets.ts +56 -0
  87. package/src/link/budget.ts +75 -0
  88. package/src/link/client.ts +793 -0
  89. package/src/link/endpoints.ts +1834 -0
  90. package/src/link/errors.ts +157 -0
  91. package/src/link/font.ts +9 -0
  92. package/src/link/grant_access.ts +116 -0
  93. package/src/link/grants.ts +436 -0
  94. package/src/link/in_flight.ts +46 -0
  95. package/src/link/key_providers.ts +25 -0
  96. package/src/link/self_hosted.ts +186 -0
  97. package/src/link/service.ts +281 -0
  98. package/src/link/sqlite_store.ts +512 -0
  99. package/src/models/canonical_models.json +19 -0
  100. package/src/models/gateways.ts +3 -0
  101. package/src/models/subscriptions.ts +15 -1
  102. package/src/platform/platform.ts +324 -1
  103. package/src/protocol/input/router_model.ts +36 -1
  104. package/src/providers/execution.ts +24 -2
  105. package/src/providers/pi_options.ts +57 -1
  106. package/src/providers/provider_call.ts +15 -1
  107. package/src/providers/stream_finalization.ts +1 -0
  108. package/src/runtime/explicit_model.ts +21 -8
  109. package/src/runtime/harness_identity/extract.ts +21 -60
  110. package/src/runtime/prepare_routed_completion.ts +6 -1
  111. package/src/runtime/routed_runtime.ts +8 -0
  112. package/src/runtime/runtime_reporter.ts +3 -0
  113. package/src/self_host/config.ts +24 -1
  114. package/src/self_host/main.ts +21 -4
  115. package/src/self_host/platform.ts +40 -8
  116. package/src/self_host/resolve.ts +157 -15
  117. package/src/self_host/secret_box.ts +112 -0
  118. package/src/self_host/stub_gateway.ts +497 -0
  119. package/src/self_host/stub_main.ts +72 -0
  120. package/src/self_host/subscription_test_gateway.ts +26 -95
  121. package/src/self_host/subscriptions/http.ts +3 -2
  122. package/src/self_host/subscriptions/index.ts +3 -0
  123. package/src/self_host/subscriptions/store.ts +167 -36
  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,578 @@
1
+ /**
2
+ * A small Dari Link client for apps: register, send the user to approve,
3
+ * exchange the code, and call the gateway with tokens that refresh
4
+ * themselves. It uses only `fetch` and Web Crypto, so it runs in browsers,
5
+ * Node, Bun, and Deno.
6
+ *
7
+ * In a browser, one button does the approval: `DariLink.open` opens Dari in a
8
+ * popup, the user signs in, picks plans, and approves, and the popup closes.
9
+ *
10
+ * ```ts
11
+ * import { DariLink } from "@mupt-ai/dari-gateway/link/client";
12
+ *
13
+ * button.onclick = async () => {
14
+ * const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
15
+ * await fetch("/api/dari/exchange", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
+ * };
17
+ * ```
18
+ *
19
+ * Without a popup, send the user to the approval URL yourself:
20
+ *
21
+ * ```ts
22
+ * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
23
+ *
24
+ * const { url, codeVerifier, state } = await authorizeUrl({ gatewayUrl, clientId, redirectUri });
25
+ * // Keep codeVerifier and state with the user's session, send them to `url`;
26
+ * // on the redirect back, check `state`, then:
27
+ * await db.save(user, await exchange({ gatewayUrl, clientId, redirectUri, code, codeVerifier }));
28
+ * const gatewayFetch = linkFetch({
29
+ * gatewayUrl,
30
+ * clientId,
31
+ * loadTokens: () => db.load(user),
32
+ * saveTokens: (next) => db.save(user, next),
33
+ * });
34
+ * await gatewayFetch("/v1/chat/completions", {
35
+ * method: "POST",
36
+ * headers: { "content-type": "application/json" },
37
+ * body: JSON.stringify({ model: "dari/routing", messages }),
38
+ * });
39
+ * ```
40
+ *
41
+ * A server keeps a secret: register it as a confidential client
42
+ * (`registerClient({ confidential: true })`, or Settings → Dari Link Apps on
43
+ * hosted Dari) and pass `clientSecret` to every
44
+ * call. Its refresh token then never rotates, so any number of processes can
45
+ * refresh the same grant. A public client's refresh token rotates on every
46
+ * use; `linkFetch` reads the tokens from your storage on each call, so
47
+ * processes that share that storage share the rotation.
48
+ */
49
+ /**
50
+ * A refused Dari Link call. `code` is the most specific error code: an OAuth
51
+ * error such as `invalid_grant` (the grant is gone: the user must link
52
+ * again), `refresh_race`, or a gateway code such as `grant_revoked`. `detail`
53
+ * holds what came with it, such as `revoked_by` or `request_id`.
54
+ */
55
+ // Plain fields, not parameter properties: this file uses only erasable
56
+ // TypeScript, so Node's type stripping can run it as is.
57
+ export class LinkError extends Error {
58
+ code;
59
+ status;
60
+ detail;
61
+ constructor(code, message, status, detail = {}) {
62
+ super(message);
63
+ this.name = "LinkError";
64
+ this.code = code;
65
+ this.status = status;
66
+ this.detail = detail;
67
+ }
68
+ }
69
+ // Access tokens are refreshed this long before they expire.
70
+ const REFRESH_EARLY_MS = 60_000;
71
+ /**
72
+ * Register an app openly (RFC 7591). A public client gets a client id; with
73
+ * `confidential`, a server also gets its client secret, returned this once:
74
+ * keep it in your secret manager.
75
+ */
76
+ export async function registerClient(args) {
77
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/v1/link/register"), {
78
+ method: "POST",
79
+ headers: { "content-type": "application/json" },
80
+ body: JSON.stringify({
81
+ client_name: args.clientName,
82
+ redirect_uris: args.redirectUris,
83
+ ...(args.confidential ? { token_endpoint_auth_method: "client_secret_basic" } : {}),
84
+ }),
85
+ });
86
+ const body = await json(response);
87
+ return {
88
+ clientId: String(body.client_id),
89
+ ...(typeof body.client_secret === "string" ? { clientSecret: body.client_secret } : {}),
90
+ };
91
+ }
92
+ /**
93
+ * The approval URL to send the user to, with a fresh PKCE verifier and state.
94
+ * `clients` names the clients the app runs, such as `claude_code`, so the
95
+ * user can grant plans that serve only those. `plans` limits the page to
96
+ * those plan kinds, such as `openai_codex`. `purposes` says what the app does
97
+ * with each audience's plans, shown beside them. `grantId` (update mode)
98
+ * opens the page on that existing grant: the user changes its plans in place,
99
+ * its id and tokens stay, and the new code redeems for more tokens of it.
100
+ */
101
+ export async function authorizeUrl(args) {
102
+ const { codeVerifier, codeChallenge, state } = await createAuthorization(args.state);
103
+ return { url: authorizationUrl({ ...args, codeChallenge, state }), codeVerifier, state };
104
+ }
105
+ /**
106
+ * A fresh PKCE pair and state, made on your server: keep `codeVerifier` (and
107
+ * `state`) with the user's session, and hand the browser only `codeChallenge`
108
+ * and `state` for `DariLink.open`. The verifier then never reaches the page,
109
+ * and the page needs no Web Crypto.
110
+ */
111
+ export async function createAuthorization(state) {
112
+ const codeVerifier = randomToken(32);
113
+ return { codeVerifier, codeChallenge: await pkceChallenge(codeVerifier), state: state ?? randomToken(16) };
114
+ }
115
+ // The approval URL for a PKCE challenge and state made elsewhere.
116
+ function authorizationUrl(args) {
117
+ const url = new URL(endpoint(args.gatewayUrl, "/v1/link/authorize"));
118
+ url.search = new URLSearchParams({
119
+ response_type: "code",
120
+ client_id: args.clientId,
121
+ redirect_uri: args.redirectUri,
122
+ state: args.state,
123
+ code_challenge: args.codeChallenge,
124
+ code_challenge_method: "S256",
125
+ scope: "route",
126
+ ...(args.responseMode === "web_message" ? { response_mode: "web_message" } : {}),
127
+ ...(args.clients?.length ? { client: args.clients.join(" ") } : {}),
128
+ ...(args.plans?.length ? { plans: args.plans.join(" ") } : {}),
129
+ ...(args.keyProviders?.length ? { key_providers: args.keyProviders.join(" ") } : {}),
130
+ ...(args.grantId ? { grant_id: args.grantId } : {}),
131
+ ...Object.fromEntries(Object.entries(args.purposes ?? {}).flatMap(([audience, purpose]) => purpose ? [[`purpose_${audience}`, purpose]] : [])),
132
+ }).toString();
133
+ return url.toString();
134
+ }
135
+ const POPUP_WIDTH = 460;
136
+ const POPUP_HEIGHT = 720;
137
+ const POPUP_POLL_MS = 400;
138
+ // A closed popup may have just handed its result to `completeLink`.
139
+ const POPUP_CLOSED_GRACE_MS = 300;
140
+ const LINK_CHANNEL = "dari-link";
141
+ const STEPS = ["connect_subscription", "choose_plans"];
142
+ /**
143
+ * Open Dari's approval page in a popup and resolve with the code once the
144
+ * user approves. Call it from a click handler, so the browser allows the
145
+ * popup. Send `code` and `codeVerifier` to your server to `exchange`.
146
+ *
147
+ * The options may be a function returning them (a promise is fine): it is
148
+ * awaited only after the popup opens, so fetching a client id or state from
149
+ * your server first does not get the popup blocked.
150
+ *
151
+ * Rejects with a `LinkError`: `popup_blocked`, `popup_closed` when the user
152
+ * closes it, or the OAuth error the page returned, such as `access_denied`.
153
+ * The result is accepted only from the popup and from the gateway's approval
154
+ * origin, and only with the state this call made.
155
+ *
156
+ * A popup that signed the user in along the way can lose its link to this
157
+ * window; the approval then lands on your redirect URI inside the popup. Call
158
+ * `DariLink.callback()` on that page (or load `/v1/link/callback.js` there)
159
+ * and this call still resolves.
160
+ */
161
+ export async function openLink(options, browserOverride) {
162
+ const browser = browserOverride
163
+ ?? (typeof options === "function" ? undefined : options.window)
164
+ ?? globalThis;
165
+ // Making PKCE in the page needs Web Crypto, which browsers give only to
166
+ // https (or localhost) pages; a challenge from the server needs none.
167
+ const insecure = (args) => args.codeChallenge === undefined && (browser.isSecureContext === false || globalThis.crypto?.subtle === undefined);
168
+ const insecureError = () => new LinkError("insecure_context", "Connect with Dari needs a secure page (https, or localhost) to make its PKCE pair, or a codeChallenge and state from your server.", 0);
169
+ if (typeof options !== "function" && insecure(options)) {
170
+ options.onExit?.({ error: "insecure_context", step: null });
171
+ throw insecureError();
172
+ }
173
+ const left = (browser.screenX ?? 0) + Math.max(0, ((browser.outerWidth ?? POPUP_WIDTH) - POPUP_WIDTH) / 2);
174
+ const top = (browser.screenY ?? 0) + Math.max(0, ((browser.outerHeight ?? POPUP_HEIGHT) - POPUP_HEIGHT) / 2);
175
+ // Opened before anything is awaited, while the click still allows it.
176
+ const popup = browser.open("about:blank", "dari-link", `popup=yes,width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${Math.round(left)},top=${Math.round(top)}`);
177
+ if (popup === null) {
178
+ if (typeof options !== "function")
179
+ options.onExit?.({ error: "popup_blocked", step: null });
180
+ throw new LinkError("popup_blocked", "Allow pop-ups for this site, then connect again.", 0);
181
+ }
182
+ let args;
183
+ let request;
184
+ let origin;
185
+ try {
186
+ args = typeof options === "function" ? await options() : options;
187
+ if (insecure(args)) {
188
+ args.onExit?.({ error: "insecure_context", step: null });
189
+ throw insecureError();
190
+ }
191
+ const supplied = args.codeChallenge;
192
+ if (supplied !== undefined && args.state === undefined) {
193
+ throw new LinkError("invalid_request", "Pass the state your server made with the codeChallenge.", 0);
194
+ }
195
+ [request, origin] = await Promise.all([
196
+ supplied !== undefined
197
+ ? { url: authorizationUrl({ ...args, codeChallenge: supplied, state: args.state, responseMode: "web_message" }), codeVerifier: null, state: args.state }
198
+ : authorizeUrl({ ...args, responseMode: "web_message" }),
199
+ approvalOrigin(args),
200
+ ]);
201
+ }
202
+ catch (error) {
203
+ popup.close();
204
+ throw error;
205
+ }
206
+ return await new Promise((resolve, reject) => {
207
+ const channel = browser.BroadcastChannel ? new browser.BroadcastChannel(LINK_CHANNEL) : null;
208
+ let settled = false;
209
+ let step = null;
210
+ const fail = (error, exitStep) => {
211
+ args.onExit?.({ error: error.code, step: exitStep });
212
+ reject(error);
213
+ };
214
+ const finish = (settle) => {
215
+ if (settled)
216
+ return;
217
+ settled = true;
218
+ browser.removeEventListener("message", onMessage);
219
+ channel?.close();
220
+ clearInterval(poll);
221
+ settle();
222
+ };
223
+ const onMessage = (event) => {
224
+ if (event.source === popup && event.origin === origin)
225
+ accept(event.data);
226
+ };
227
+ const accept = (data) => {
228
+ const message = data;
229
+ if (typeof message !== "object" || message === null || message.state !== request.state)
230
+ return;
231
+ // A step the user reached, not a result.
232
+ if (message.type === "dari-link-event") {
233
+ if (STEPS.includes(message.event)) {
234
+ step = message.event;
235
+ args.onEvent?.(step);
236
+ }
237
+ return;
238
+ }
239
+ // Only a result ends the flow; anything else is ignored.
240
+ if (message.type !== "dari-link" || (typeof message.code !== "string" && typeof message.error !== "string"))
241
+ return;
242
+ finish(() => {
243
+ if (typeof message.code === "string") {
244
+ resolve({ code: message.code, state: request.state, codeVerifier: request.codeVerifier });
245
+ }
246
+ else {
247
+ const code = typeof message.error === "string" ? message.error : "invalid_request";
248
+ fail(new LinkError(code, typeof message.error_description === "string" ? message.error_description : `Dari Link was not approved: ${code}.`, 0), code === "access_denied" ? "denied" : step);
249
+ }
250
+ });
251
+ if (!popup.closed)
252
+ popup.close();
253
+ };
254
+ const poll = setInterval(() => {
255
+ if (!popup.closed)
256
+ return;
257
+ clearInterval(poll);
258
+ setTimeout(() => finish(() => fail(new LinkError("popup_closed", "The Dari window was closed before approving.", 0), step)), POPUP_CLOSED_GRACE_MS);
259
+ }, POPUP_POLL_MS);
260
+ browser.addEventListener("message", onMessage);
261
+ // Only this origin's windows share the channel.
262
+ if (channel)
263
+ channel.onmessage = (event) => accept(event.data);
264
+ popup.location.href = request.url;
265
+ });
266
+ }
267
+ /**
268
+ * On your redirect URI's page: hand an approval that arrived there in the
269
+ * popup to the window that called `DariLink.open`, and close the popup.
270
+ * Returns false when the page holds no Dari Link result.
271
+ */
272
+ export function completeLink(args = {}) {
273
+ const browser = args.window ?? globalThis;
274
+ const params = new URLSearchParams(browser.location?.search ?? "");
275
+ const state = params.get("state");
276
+ const code = params.get("code");
277
+ const error = params.get("error");
278
+ if (state === null || (code === null && error === null) || !browser.BroadcastChannel)
279
+ return false;
280
+ const channel = new browser.BroadcastChannel(LINK_CHANNEL);
281
+ channel.postMessage({
282
+ type: "dari-link",
283
+ state,
284
+ ...(code !== null ? { code } : { error, error_description: params.get("error_description") ?? undefined }),
285
+ });
286
+ channel.close();
287
+ browser.close?.();
288
+ return true;
289
+ }
290
+ /** The Dari mark: a white turtle on a black disc, square, scalable. */
291
+ export const DARI_MARK_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="20" height="20" aria-hidden="true">'
292
+ + '<circle cx="512" cy="512" r="462" fill="#000"/><g fill="#fff">'
293
+ + '<path d="M227.174 643.267C309.13 501.04 353.3 382.247 461.711 379.747c100.278 6.927 172.975 162.686 217.376 263.52h110.942c-81.304-117.797-196.325-301.555-326.906-303.36-166.044-4.954-236.495 312.426-235.949 303.36"/>'
294
+ + '<path d="M657.933 552.765h177.78V487.33l-224.079 18.712 44.162 15.727zM327.444 446.849h14.02v89.346h-14.02zM368.884 403.285h13.92v129.377h-13.92zM413.178 382.234h13.886v144.712h-13.886zm48.935-4.033h13.886v144.712h-13.886zM512.336 410.531v118.442h13.887V423.498a300 300 0 0 0-13.887-12.967M593.563 507.768l-329.946 33.841-85.683 11.157h444.87c-9.563-15.205-19.29-30.327-29.241-44.998"/>'
295
+ + "</g></svg>";
296
+ /**
297
+ * Render the standard "Connect with Dari" button into `container` and call
298
+ * `onClick` (which should call `DariLink.open`) when it is pressed. `dark`
299
+ * (the default) is for light pages: black button, white text; `light` is for
300
+ * dark pages. The button is 40px tall with the mark at 20px; see the README's
301
+ * button guidelines.
302
+ */
303
+ export function renderButton(container, options) {
304
+ const dark = (options.theme ?? "dark") === "dark";
305
+ const label = (options.label ?? "Connect with Dari")
306
+ .replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
307
+ container.innerHTML = `<button type="button" data-dari-link style="display:inline-flex;align-items:center;gap:8px;height:40px;padding:0 16px 0 12px;`
308
+ + `border-radius:8px;border:1px solid ${dark ? "#000" : "#d4d4d8"};background:${dark ? "#000" : "#fff"};color:${dark ? "#fff" : "#000"};`
309
+ + `font:500 14px/1 system-ui,-apple-system,sans-serif;cursor:pointer">${DARI_MARK_SVG.replace('fill="#000"', `fill="${dark ? "#fff" : "#000"}"`).replace('<g fill="#fff">', `<g fill="${dark ? "#000" : "#fff"}">`)}${label}</button>`;
310
+ container.querySelector("button[data-dari-link]")?.addEventListener("click", options.onClick);
311
+ }
312
+ /**
313
+ * `DariLink.open(...)` is the one call a "Connect with Dari" button makes;
314
+ * `DariLink.callback()` goes on the redirect URI's page; `DariLink.renderButton`
315
+ * draws the button.
316
+ */
317
+ export const DariLink = { open: openLink, callback: completeLink, renderButton };
318
+ // The origin the approval page posts its result from, as the gateway's
319
+ // metadata names it: the gateway's public origin.
320
+ async function approvalOrigin(args) {
321
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/.well-known/oauth-authorization-server"));
322
+ const origin = (await json(response)).web_message_origin;
323
+ return typeof origin === "string" ? origin : new URL(args.gatewayUrl).origin;
324
+ }
325
+ /** Redeem the code from the approval redirect for the grant's first tokens. */
326
+ export async function exchange(args) {
327
+ return tokenSet(await tokenCall(args, {
328
+ grant_type: "authorization_code",
329
+ redirect_uri: args.redirectUri,
330
+ code: args.code,
331
+ code_verifier: args.codeVerifier,
332
+ }));
333
+ }
334
+ /**
335
+ * A new access token. A public client's refresh token rotates: the one passed
336
+ * in stops working. A confidential client's stays the same.
337
+ */
338
+ export async function refresh(args) {
339
+ return tokenSet(await tokenCall(args, { grant_type: "refresh_token", refresh_token: args.refreshToken }));
340
+ }
341
+ /**
342
+ * Mint a child token for a sandbox or worker, from the grant's access token
343
+ * or from your token storage (refreshed as `linkFetch` does): it serves only
344
+ * its models (each at one thinking level when pinned) for up to twelve
345
+ * hours, cannot refresh, mint, or read the grant, and dies with the grant.
346
+ */
347
+ export async function childToken(args) {
348
+ const pinned = args.models.some((entry) => entry.thinking);
349
+ const mint = async (accessToken) => await tokenCall(args, [
350
+ ["grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"],
351
+ ["subject_token", accessToken],
352
+ ["subject_token_type", "urn:ietf:params:oauth:token-type:access_token"],
353
+ ...args.models.map((entry) => ["model", entry.model]),
354
+ // One level per model, in order, when any is pinned.
355
+ ...(pinned ? args.models.map((entry) => ["thinking", entry.thinking || "default"]) : []),
356
+ ...(args.expiresIn === undefined ? [] : [["expires_in", String(args.expiresIn)]]),
357
+ ...(args.tags && Object.keys(args.tags).length > 0
358
+ ? [["tags", Object.entries(args.tags).map(([key, value]) => `${key}=${value}`).join(",")]]
359
+ : []),
360
+ ]);
361
+ let payload;
362
+ if ("accessToken" in args) {
363
+ payload = await mint(args.accessToken);
364
+ }
365
+ else {
366
+ // From storage, refreshing the grant's access token as linkFetch does.
367
+ const source = tokenSource(args);
368
+ const tokens = await source.fresh();
369
+ try {
370
+ payload = await mint(tokens.accessToken);
371
+ }
372
+ catch (error) {
373
+ if (!(error instanceof LinkError && error.code === "invalid_grant"))
374
+ throw error;
375
+ payload = await mint((await source.rotate(tokens)).accessToken);
376
+ }
377
+ }
378
+ return {
379
+ accessToken: String(payload.access_token),
380
+ expiresAt: Date.now() + Number(payload.expires_in) * 1000,
381
+ models: payload.models,
382
+ };
383
+ }
384
+ /** End the grant a token belongs to, as when the user disconnects in the app. */
385
+ export async function revoke(args) {
386
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/v1/link/revoke"), {
387
+ method: "POST",
388
+ headers: clientHeaders(args),
389
+ body: new URLSearchParams({ client_id: args.clientId, token: args.token }),
390
+ });
391
+ if (!response.ok)
392
+ await json(response);
393
+ }
394
+ /**
395
+ * A fetch for the gateway on one grant: paths resolve against `gatewayUrl`
396
+ * and the access token is attached. Your storage is the source of truth: the
397
+ * tokens are read with `loadTokens` on every call, refreshed shortly before
398
+ * they expire and once after a 401 for an expired token, and every new token
399
+ * set reaches `saveTokens` before use. Concurrent calls in a process share
400
+ * one refresh. A grant that is gone throws LinkError with code
401
+ * `invalid_grant` from the refresh, and a revoked access token's 401
402
+ * (`grant_revoked`) is returned as it is: either way the user is unlinked and
403
+ * must link again. With no tokens stored it throws `not_linked`.
404
+ */
405
+ export function linkFetch(args) {
406
+ const fetchImpl = args.fetch ?? fetch;
407
+ const source = tokenSource(args);
408
+ const call = (tokens, input, init) => {
409
+ const headers = new Headers(init?.headers);
410
+ headers.set("authorization", `Bearer ${tokens.accessToken}`);
411
+ return fetchImpl(endpoint(args.gatewayUrl, input), { ...init, headers });
412
+ };
413
+ return async (input, init) => {
414
+ const tokens = await source.fresh();
415
+ const response = await call(tokens, input, init);
416
+ if (response.status !== 401 || !replayable(init?.body))
417
+ return response;
418
+ // A revoked grant cannot be refreshed back to life.
419
+ if ((await errorCode(response.clone())) === "grant_revoked")
420
+ return response;
421
+ return await call(await source.rotate(tokens), input, init);
422
+ };
423
+ }
424
+ /**
425
+ * What the grant's requests used, child tokens' included: only requests
426
+ * carrying every given tag (X-Dari-Tags or a child token's tags), received
427
+ * in [since, until), and with `groupByTag` also totalled per value of that
428
+ * tag. Pass the `linkFetch` your app already uses as `fetcher` so this shares
429
+ * its refresh; otherwise pass the client and token storage.
430
+ */
431
+ export async function usage(args) {
432
+ const params = new URLSearchParams();
433
+ for (const [key, value] of Object.entries(args.tags ?? {}))
434
+ params.append("tag", `${key}=${value}`);
435
+ if (args.since)
436
+ params.set("since", args.since.toISOString());
437
+ if (args.until)
438
+ params.set("until", args.until.toISOString());
439
+ if (args.groupByTag)
440
+ params.set("group_by", `tag:${args.groupByTag}`);
441
+ const query = params.toString();
442
+ const fetcher = "fetcher" in args ? args.fetcher : linkFetch(args);
443
+ const response = await fetcher(`/v1/link/usage${query ? `?${query}` : ""}`);
444
+ return await json(response);
445
+ }
446
+ // One grant's tokens from storage: fresh ones, refreshed shortly before they
447
+ // expire, and a rotation that concurrent callers share.
448
+ function tokenSource(args) {
449
+ const now = args.now ?? Date.now;
450
+ const load = async () => {
451
+ const stored = await args.loadTokens();
452
+ if (stored === null)
453
+ throw new LinkError("not_linked", "This user has not linked a Dari Link grant.", 0);
454
+ return stored;
455
+ };
456
+ let refreshing = null;
457
+ const rotate = (stale) => {
458
+ refreshing ??= (async () => {
459
+ try {
460
+ // Another call or process may have refreshed since `stale` was read.
461
+ const stored = await load();
462
+ if (stored.accessToken !== stale.accessToken)
463
+ return stored;
464
+ try {
465
+ const next = await refresh({ ...args, refreshToken: stored.refreshToken });
466
+ await args.saveTokens(next);
467
+ return next;
468
+ }
469
+ catch (error) {
470
+ // Another process rotated this refresh token a moment ago and is
471
+ // saving what it received.
472
+ if (error instanceof LinkError && error.code === "refresh_race")
473
+ return await load();
474
+ throw error;
475
+ }
476
+ }
477
+ finally {
478
+ refreshing = null;
479
+ }
480
+ })();
481
+ return refreshing;
482
+ };
483
+ return {
484
+ rotate,
485
+ async fresh() {
486
+ const tokens = await load();
487
+ return tokens.expiresAt - now() < REFRESH_EARLY_MS ? await rotate(tokens) : tokens;
488
+ },
489
+ };
490
+ }
491
+ // A form field may repeat when given as pairs.
492
+ async function tokenCall(args, body) {
493
+ const fields = Array.isArray(body) ? body : Object.entries(body);
494
+ const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/v1/link/token"), {
495
+ method: "POST",
496
+ headers: clientHeaders(args),
497
+ body: new URLSearchParams([["client_id", args.clientId], ...fields]),
498
+ });
499
+ return await json(response);
500
+ }
501
+ // A confidential client proves its secret with HTTP Basic.
502
+ function clientHeaders(args) {
503
+ return {
504
+ "content-type": "application/x-www-form-urlencoded",
505
+ ...(args.clientSecret
506
+ ? { authorization: `Basic ${btoa(`${encodeURIComponent(args.clientId)}:${encodeURIComponent(args.clientSecret)}`)}` }
507
+ : {}),
508
+ };
509
+ }
510
+ function tokenSet(payload) {
511
+ return {
512
+ accessToken: String(payload.access_token),
513
+ refreshToken: String(payload.refresh_token),
514
+ expiresAt: Date.now() + Number(payload.expires_in) * 1000,
515
+ grantId: typeof payload.grant_id === "string" ? payload.grant_id : null,
516
+ scope: typeof payload.scope === "string" ? payload.scope : "route",
517
+ budget: Array.isArray(payload.budget) ? payload.budget : [],
518
+ state: payload.state === "budget_limit" ? "budget_limit" : "ready",
519
+ availableAt: typeof payload.available_at === "string" ? payload.available_at : null,
520
+ plans: Array.isArray(payload.plans) ? payload.plans : [],
521
+ models: Array.isArray(payload.models) ? payload.models : [],
522
+ routes: payload.routes === true,
523
+ manageUrl: String(payload.manage_url),
524
+ };
525
+ }
526
+ // The JSON body of a successful response; otherwise a LinkError from either
527
+ // error shape (OAuth `error`, or the gateway's `error.code`).
528
+ async function json(response) {
529
+ const body = await response.json().catch(() => null);
530
+ const record = typeof body === "object" && body !== null ? body : {};
531
+ if (response.ok)
532
+ return record;
533
+ const error = record.error;
534
+ if (typeof error === "string") {
535
+ const { error: _error, error_description: description, error_code: specific, ...detail } = record;
536
+ throw new LinkError(typeof specific === "string" ? specific : error, String(description ?? error), response.status, detail);
537
+ }
538
+ if (typeof error === "object" && error !== null) {
539
+ const { code, message, ...detail } = error;
540
+ throw new LinkError(String(code ?? "error"), String(message ?? "Dari Link request failed."), response.status, detail);
541
+ }
542
+ throw new LinkError("error", `Dari Link request failed with status ${response.status}.`, response.status);
543
+ }
544
+ // The error code of a refused gateway response, or null.
545
+ async function errorCode(response) {
546
+ const body = await response.json().catch(() => null);
547
+ const error = typeof body === "object" && body !== null ? body.error : null;
548
+ const code = typeof error === "object" && error !== null ? error.code : null;
549
+ return typeof code === "string" ? code : null;
550
+ }
551
+ // A path on the gateway, or a full URL on its origin: the token is never sent anywhere else.
552
+ function endpoint(gatewayUrl, path) {
553
+ if (!/^https?:\/\//.test(path))
554
+ return `${gatewayUrl.replace(/\/+$/, "")}${path.startsWith("/") ? "" : "/"}${path}`;
555
+ if (new URL(path).origin !== new URL(gatewayUrl).origin) {
556
+ throw new LinkError("invalid_request", `Dari Link sends its token only to ${new URL(gatewayUrl).origin}.`, 0);
557
+ }
558
+ return path;
559
+ }
560
+ // A body that can be sent twice: a stream is spent by the first attempt.
561
+ function replayable(body) {
562
+ return body === undefined || body === null || typeof body === "string"
563
+ || body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body)
564
+ || (typeof Blob !== "undefined" && body instanceof Blob)
565
+ || (typeof FormData !== "undefined" && body instanceof FormData);
566
+ }
567
+ function randomToken(bytes) {
568
+ return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
569
+ }
570
+ async function pkceChallenge(verifier) {
571
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
572
+ }
573
+ function base64url(bytes) {
574
+ let binary = "";
575
+ for (const byte of bytes)
576
+ binary += String.fromCharCode(byte);
577
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
578
+ }
@@ -0,0 +1,23 @@
1
+ import type { GatewayPlatform } from "../platform/platform.js";
2
+ /** The `type` of the message a `web_message` approval posts to its opener. */
3
+ export declare const LINK_MESSAGE_TYPE = "dari-link";
4
+ export declare const LINK_EVENT_TYPE = "dari-link-event";
5
+ export declare const LINK_SCOPE = "route";
6
+ export declare const LINK_ROUTE_PREFIX = "/v1/link/";
7
+ export declare const LINK_METADATA_PATH = "/.well-known/oauth-authorization-server";
8
+ /** The PKCE S256 challenge for a code verifier. */
9
+ export declare function pkceChallenge(verifier: string): string;
10
+ export declare function handleLinkRequest(request: Request, platform: GatewayPlatform): Promise<Response>;
11
+ /**
12
+ * The `Cookie` header value that makes a request this user's on the approval
13
+ * page, for a platform's own tooling (the stub gateway approves with it).
14
+ */
15
+ export declare function linkUserCookie(secret: string, subject: string): string;
16
+ /**
17
+ * The step of approval the user reached, which a popup posts to the window
18
+ * that opened it (`{type: "dari-link-event", version: 1, event, state}`; the
19
+ * result alone is `type: "dari-link"`), so the app can tell where the user
20
+ * left: `connect_subscription` (connecting a plan) or `choose_plans`. A user
21
+ * who denies leaves at `denied`, which the `access_denied` result says.
22
+ */
23
+ export type LinkStep = "connect_subscription" | "choose_plans";