@mupt-ai/dari-gateway 1.0.327 → 1.0.328

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.
@@ -4,47 +4,51 @@
4
4
  * themselves. It uses only `fetch` and Web Crypto, so it runs in browsers,
5
5
  * Node, Bun, and Deno.
6
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.
7
+ * An app with a server is three calls. In the browser, one button does the
8
+ * approval: `DariLink.open` opens Dari in a popup, the user signs in, picks
9
+ * plans, and approves, and the popup closes.
9
10
  *
10
11
  * ```ts
11
12
  * import { DariLink } from "@mupt-ai/dari-gateway/link/client";
12
13
  *
13
14
  * button.onclick = async () => {
14
15
  * const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
15
- * await fetch("/api/dari/exchange", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
+ * await fetch("/api/dari/connect", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
17
  * };
17
18
  * ```
18
19
  *
19
- * Without a popup, send the user to the approval URL yourself:
20
+ * The server, registered as a confidential client (`registerClient({
21
+ * confidential: true })`, or Settings → Dari Link Apps on hosted Dari),
22
+ * redeems the code and stores one string per user: the refresh token. It
23
+ * never changes, and it is useless without the client secret. Every later
24
+ * call takes it, and makes its own access tokens:
20
25
  *
21
26
  * ```ts
22
- * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
27
+ * import { exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
23
28
  *
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", {
29
+ * const client = { gatewayUrl, clientId, clientSecret };
30
+ * const { refreshToken } = await exchange({ ...client, redirectUri, code, codeVerifier });
31
+ * await db.save(user, refreshToken);
32
+ *
33
+ * const dari = linkFetch({ ...client, refreshToken });
34
+ * await dari("/v1/chat/completions", {
35
35
  * method: "POST",
36
36
  * headers: { "content-type": "application/json" },
37
37
  * body: JSON.stringify({ model: "dari/routing", messages }),
38
38
  * });
39
39
  * ```
40
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.
41
+ * `grant`, `usage`, and `childToken` take the same `refreshToken`, and
42
+ * `revoke` ends the grant. Dari refuses a model the grant cannot serve, a
43
+ * plan at its limit, and a revoked grant itself, so an app checks none of
44
+ * that before calling: it shows the error, and Reconnect when
45
+ * `LinkError.unlinked` is true.
46
+ *
47
+ * An app with no server (a public client) has no secret, and its refresh
48
+ * token rotates on every use: it passes its storage (`loadTokens` and
49
+ * `saveTokens`) instead of `refreshToken`, and processes that share that
50
+ * storage share the rotation. Without a popup, `authorizeUrl` gives the
51
+ * approval URL to send the user to.
48
52
  */
49
53
 
50
54
  export type LinkPlan = {
@@ -78,12 +82,9 @@ export type LinkModel = { id: string; name: string };
78
82
 
79
83
  export type LinkBudgetWindow = { window_minutes: number; max_tokens: number; used_tokens: number; resets_at: string | null };
80
84
 
81
- export type LinkTokenSet = {
82
- accessToken: string;
83
- refreshToken: string;
84
- // Milliseconds since the epoch.
85
- expiresAt: number;
86
- grantId: string | null;
85
+ /** What a grant holds now: what `grant` reads, and what comes with every token set. */
86
+ export type LinkGrant = {
87
+ grantId: string;
87
88
  scope: string;
88
89
  // The most tokens this app may use per window (300: five hours, 10080: a
89
90
  // week), across all its plans and API keys, and what it used in each
@@ -101,6 +102,14 @@ export type LinkTokenSet = {
101
102
  routes: boolean;
102
103
  };
103
104
 
105
+ export type LinkTokenSet = LinkGrant & {
106
+ accessToken: string;
107
+ // A server with a client secret stores only this: it never changes.
108
+ refreshToken: string;
109
+ // When the access token expires, in milliseconds since the epoch.
110
+ expiresAt: number;
111
+ };
112
+
104
113
  export type LinkChildToken = {
105
114
  accessToken: string;
106
115
  // Milliseconds since the epoch.
@@ -129,6 +138,11 @@ export class LinkError extends Error {
129
138
  this.status = status;
130
139
  this.detail = detail;
131
140
  }
141
+
142
+ /** Whether the user's grant is gone, so the app should offer Reconnect. */
143
+ get unlinked(): boolean {
144
+ return this.code === "invalid_grant" || this.code === "grant_revoked" || this.code === "not_linked";
145
+ }
132
146
  }
133
147
 
134
148
  type Fetch = typeof fetch;
@@ -504,12 +518,13 @@ export async function refresh(args: Client & { refreshToken: string }): Promise<
504
518
  }
505
519
 
506
520
  /**
507
- * Mint a child token for a sandbox or worker, from the grant's access token
508
- * or from your token storage (refreshed as `linkFetch` does): it serves only
509
- * its models (each at one thinking level when pinned) for up to twelve
510
- * hours, cannot refresh, mint, or read the grant, and dies with the grant.
521
+ * Mint a child token for a sandbox or worker, from the grant's refresh token
522
+ * or token storage (as `linkFetch` takes them), or from an access token: it
523
+ * serves only its models (each at one thinking level when pinned) for up to
524
+ * twelve hours, cannot refresh, mint, or read the grant, and dies with the
525
+ * grant.
511
526
  */
512
- export async function childToken(args: Client & ({ accessToken: string } | TokenStorage) & {
527
+ export async function childToken(args: Client & ({ accessToken: string } | LinkTokens) & {
513
528
  // Such as `[{ model: "dari/model/openai/gpt-5.5", thinking: "high" }]`.
514
529
  models: Array<{ model: string; thinking?: string }>;
515
530
  // Seconds, 60 to 43200; an hour when omitted.
@@ -535,7 +550,7 @@ export async function childToken(args: Client & ({ accessToken: string } | Token
535
550
  if ("accessToken" in args) {
536
551
  payload = await mint(args.accessToken);
537
552
  } else {
538
- // From storage, refreshing the grant's access token as linkFetch does.
553
+ // Refreshing the grant's access token as linkFetch does.
539
554
  const source = tokenSource(args);
540
555
  const tokens = await source.fresh();
541
556
  try {
@@ -564,22 +579,23 @@ export async function revoke(args: Client & { token: string }): Promise<void> {
564
579
 
565
580
  /**
566
581
  * A fetch for the gateway on one grant: paths resolve against `gatewayUrl`
567
- * and the access token is attached. Your storage is the source of truth: the
568
- * tokens are read with `loadTokens` on every call, refreshed shortly before
569
- * they expire and once after a 401 for an expired token, and every new token
570
- * set reaches `saveTokens` before use. Concurrent calls in a process share
571
- * one refresh. A grant that is gone throws LinkError with code
582
+ * and the access token is attached, refreshed shortly before it expires and
583
+ * once after a 401 for an expired token. A server passes the grant's
584
+ * `refreshToken`; a public client passes its storage, which is then the
585
+ * source of truth: the tokens are read with `loadTokens` on every call, and
586
+ * every new token set reaches `saveTokens` before use. Concurrent calls in a
587
+ * process share one refresh. A grant that is gone throws LinkError with code
572
588
  * `invalid_grant` from the refresh, and a revoked access token's 401
573
589
  * (`grant_revoked`) is returned as it is: either way the user is unlinked and
574
590
  * must link again. With no tokens stored it throws `not_linked`.
575
591
  */
576
- export function linkFetch(args: Client & TokenStorage & {
592
+ export function linkFetch(args: Client & LinkTokens & {
577
593
  now?: () => number;
578
594
  }): (input: string, init?: RequestInit) => Promise<Response> {
579
595
  const fetchImpl = args.fetch ?? fetch;
580
596
  const source = tokenSource(args);
581
597
 
582
- const call = (tokens: LinkTokenSet, input: string, init: RequestInit | undefined) => {
598
+ const call = (tokens: HeldTokens, input: string, init: RequestInit | undefined) => {
583
599
  const headers = new Headers(init?.headers);
584
600
  headers.set("authorization", `Bearer ${tokens.accessToken}`);
585
601
  return fetchImpl(endpoint(args.gatewayUrl, input), { ...init, headers });
@@ -616,17 +632,30 @@ export type LinkUsage = LinkUsageTotals & {
616
632
  by_tag?: Array<LinkUsageTotals & { value: string | null }>;
617
633
  };
618
634
 
635
+ // A `linkFetch` the app already made, or what makes one.
636
+ type GrantCall =
637
+ | { fetcher: (input: string, init?: RequestInit) => Promise<Response> }
638
+ | (Client & LinkTokens & { now?: () => number });
639
+
640
+ /**
641
+ * What the grant holds now: its plans and API keys, whether each can serve,
642
+ * the models they serve, and the user's budget. It makes no provider call,
643
+ * so it is the cheap check before a long run, and what a connections list
644
+ * shows. A grant that is gone throws a LinkError whose `unlinked` is true.
645
+ */
646
+ export async function grant(args: GrantCall): Promise<LinkGrant> {
647
+ const fetcher = "fetcher" in args ? args.fetcher : linkFetch(args);
648
+ return grantOf(await json(await fetcher("/v1/link/grant")));
649
+ }
650
+
619
651
  /**
620
652
  * What the grant's requests used, child tokens' included: only requests
621
653
  * carrying every given tag (X-Dari-Tags or a child token's tags), received
622
654
  * in [since, until), and with `groupByTag` also totalled per value of that
623
- * tag. Pass the `linkFetch` your app already uses as `fetcher` so this shares
624
- * its refresh; otherwise pass the client and token storage.
655
+ * tag. Takes the grant's `refreshToken` or token storage as `linkFetch`
656
+ * does, or the `linkFetch` your app already made as `fetcher`.
625
657
  */
626
- export async function usage(args: (
627
- | { fetcher: (input: string, init?: RequestInit) => Promise<Response> }
628
- | (Client & TokenStorage & { now?: () => number })
629
- ) & {
658
+ export async function usage(args: GrantCall & {
630
659
  tags?: Record<string, string>;
631
660
  since?: Date;
632
661
  until?: Date;
@@ -644,34 +673,69 @@ export async function usage(args: (
644
673
  }
645
674
 
646
675
  /**
647
- * Where an app keeps one grant's tokens. `loadTokens` returns null when the
648
- * user has not linked (or unlinked): calls then throw LinkError `not_linked`
649
- * without reaching the gateway.
676
+ * Where a public client keeps one grant's tokens. `loadTokens` returns null
677
+ * when the user has not linked (or unlinked): calls then throw LinkError
678
+ * `not_linked` without reaching the gateway.
650
679
  */
651
680
  export type TokenStorage = {
652
681
  loadTokens: () => LinkTokenSet | null | Promise<LinkTokenSet | null>;
653
682
  saveTokens: (tokens: LinkTokenSet) => void | Promise<void>;
654
683
  };
655
684
 
656
- // One grant's tokens from storage: fresh ones, refreshed shortly before they
657
- // expire, and a rotation that concurrent callers share.
658
- function tokenSource(args: Client & TokenStorage & { now?: () => number }) {
685
+ /**
686
+ * One grant's tokens. A server with a client secret passes `refreshToken`,
687
+ * the one string it stores for the grant: it never changes, and the access
688
+ * tokens made from it are kept in this process. A public client's refresh
689
+ * token rotates on every use, so it passes its storage.
690
+ */
691
+ export type LinkTokens = { refreshToken: string } | TokenStorage;
692
+
693
+ // What a grant's tokens are read for.
694
+ type HeldTokens = Pick<LinkTokenSet, "accessToken" | "refreshToken" | "expiresAt">;
695
+
696
+ // The access tokens this process made from refresh tokens, by gateway,
697
+ // client, and refresh token, and each one's refresh in flight.
698
+ const held = new Map<string, HeldTokens>();
699
+ const refreshes = new Map<string, Promise<HeldTokens>>();
700
+
701
+ // One grant's tokens: fresh ones, refreshed shortly before they expire, and
702
+ // a rotation that concurrent callers share.
703
+ function tokenSource(args: Client & LinkTokens & { now?: () => number }) {
659
704
  const now = args.now ?? Date.now;
660
- const load = async (): Promise<LinkTokenSet> => {
705
+ // A refresh token that never rotates names its grant for the whole process.
706
+ const key = "refreshToken" in args ? `${args.gatewayUrl}\n${args.clientId}\n${args.refreshToken}` : null;
707
+ if (key !== null && !args.clientSecret) {
708
+ throw new LinkError(
709
+ "invalid_request",
710
+ "Only a client with a clientSecret keeps one refresh token; a public client's rotates, so pass loadTokens and saveTokens.",
711
+ 0,
712
+ );
713
+ }
714
+ const load = async (): Promise<HeldTokens> => {
715
+ // No access token made yet: the first call refreshes.
716
+ if ("refreshToken" in args) return held.get(key!) ?? { accessToken: "", refreshToken: args.refreshToken, expiresAt: 0 };
661
717
  const stored = await args.loadTokens();
662
718
  if (stored === null) throw new LinkError("not_linked", "This user has not linked a Dari Link grant.", 0);
663
719
  return stored;
664
720
  };
665
- let refreshing: Promise<LinkTokenSet> | null = null;
666
- const rotate = (stale: LinkTokenSet): Promise<LinkTokenSet> => {
667
- refreshing ??= (async () => {
721
+ const save = async (next: LinkTokenSet): Promise<void> => {
722
+ if (!("refreshToken" in args)) return await args.saveTokens(next);
723
+ for (const [other, tokens] of held) if (tokens.expiresAt <= now()) held.delete(other);
724
+ held.set(key!, { accessToken: next.accessToken, refreshToken: next.refreshToken, expiresAt: next.expiresAt });
725
+ };
726
+ // One refresh at a time: per call site with storage, per process with a refresh token.
727
+ let refreshing: Promise<HeldTokens> | null = null;
728
+ const rotate = (stale: HeldTokens): Promise<HeldTokens> => {
729
+ const running = key === null ? refreshing : refreshes.get(key) ?? null;
730
+ if (running !== null) return running;
731
+ const started = (async () => {
668
732
  try {
669
733
  // Another call or process may have refreshed since `stale` was read.
670
734
  const stored = await load();
671
735
  if (stored.accessToken !== stale.accessToken) return stored;
672
736
  try {
673
737
  const next = await refresh({ ...args, refreshToken: stored.refreshToken });
674
- await args.saveTokens(next);
738
+ await save(next);
675
739
  return next;
676
740
  } catch (error) {
677
741
  // Another process rotated this refresh token a moment ago and is
@@ -680,14 +744,17 @@ function tokenSource(args: Client & TokenStorage & { now?: () => number }) {
680
744
  throw error;
681
745
  }
682
746
  } finally {
683
- refreshing = null;
747
+ if (key === null) refreshing = null;
748
+ else refreshes.delete(key);
684
749
  }
685
750
  })();
686
- return refreshing;
751
+ if (key === null) refreshing = started;
752
+ else refreshes.set(key, started);
753
+ return started;
687
754
  };
688
755
  return {
689
756
  rotate,
690
- async fresh(): Promise<LinkTokenSet> {
757
+ async fresh(): Promise<HeldTokens> {
691
758
  const tokens = await load();
692
759
  return tokens.expiresAt - now() < REFRESH_EARLY_MS ? await rotate(tokens) : tokens;
693
760
  },
@@ -720,10 +787,16 @@ function clientHeaders(args: Client): Record<string, string> {
720
787
 
721
788
  function tokenSet(payload: Record<string, unknown>): LinkTokenSet {
722
789
  return {
790
+ ...grantOf(payload),
723
791
  accessToken: String(payload.access_token),
724
792
  refreshToken: String(payload.refresh_token),
725
793
  expiresAt: Date.now() + Number(payload.expires_in) * 1000,
726
- grantId: typeof payload.grant_id === "string" ? payload.grant_id : null,
794
+ };
795
+ }
796
+
797
+ function grantOf(payload: Record<string, unknown>): LinkGrant {
798
+ return {
799
+ grantId: String(payload.grant_id),
727
800
  scope: typeof payload.scope === "string" ? payload.scope : "route",
728
801
  budget: Array.isArray(payload.budget) ? payload.budget as LinkBudgetWindow[] : [],
729
802
  state: payload.state === "budget_limit" ? "budget_limit" : "ready",
@@ -37,7 +37,7 @@ export function anthropicMessagesToInteraction(
37
37
  }
38
38
 
39
39
  const tools = anthropicTools(payload.tools);
40
- toolsByWireName(tools);
40
+ const declaredTools = toolsByWireName(tools);
41
41
  const toolChoice = anthropicToolChoice(payload.tool_choice);
42
42
  const maxOutputTokens = requiredPositiveInteger(payload.max_tokens, "max_tokens");
43
43
  const stream = optionalBoolean(payload.stream, "stream") ?? false;
@@ -47,7 +47,7 @@ export function anthropicMessagesToInteraction(
47
47
  sourceProtocol: "anthropic_messages",
48
48
  model,
49
49
  instructions: anthropicSystem(payload.system),
50
- items: anthropicItems(payload.messages),
50
+ items: anthropicItems(payload.messages, declaredTools),
51
51
  tools,
52
52
  toolChoice,
53
53
  parallelToolCalls: parallelToolCalls(payload.tool_choice),
@@ -66,7 +66,9 @@ export function anthropicMessagesToInteraction(
66
66
  };
67
67
  }
68
68
 
69
- function anthropicItems(value: unknown): InteractionItem[] {
69
+ // `declaredTools` resolves `tool_addition` references by name: the request's
70
+ // tools, then each tool an earlier `tool_addition` defined.
71
+ function anthropicItems(value: unknown, declaredTools: Map<string, InteractionTool>): InteractionItem[] {
70
72
  if (!Array.isArray(value) || value.length === 0) {
71
73
  throw invalidRequest("messages must be a non-empty array.", "messages");
72
74
  }
@@ -80,7 +82,7 @@ function anthropicItems(value: unknown): InteractionItem[] {
80
82
  if (role !== "system" && role !== "user" && role !== "assistant") {
81
83
  throw invalidRequest(`Unsupported Anthropic message role '${role}'.`, `messages.${messageIndex}.role`);
82
84
  }
83
- appendAnthropicMessage(items, role, rawMessage.content, messageIndex);
85
+ appendAnthropicMessage(items, role, rawMessage.content, messageIndex, declaredTools);
84
86
  }
85
87
  return items;
86
88
  }
@@ -89,7 +91,8 @@ function appendAnthropicMessage(
89
91
  items: InteractionItem[],
90
92
  role: "system" | "user" | "assistant",
91
93
  value: unknown,
92
- messageIndex: number
94
+ messageIndex: number,
95
+ declaredTools: Map<string, InteractionTool>
93
96
  ): void {
94
97
  if (typeof value === "string") {
95
98
  items.push({
@@ -264,11 +267,7 @@ function appendAnthropicMessage(
264
267
  }
265
268
  if (type === "tool_addition") {
266
269
  if (role !== "system") throw invalidRequest("tool_addition blocks require the system role.", param);
267
- const tool = isRecord(rawBlock.tool) ? rawBlock.tool : undefined;
268
- if (tool?.type !== "tool_definition") {
269
- throw invalidRequest(`${param}.tool must be a tool_definition.`, `${param}.tool`);
270
- }
271
- toolsAdded.push(anthropicTool(tool.definition, `${param}.tool.definition`));
270
+ toolsAdded.push(anthropicToolAddition(rawBlock.tool, `${param}.tool`, declaredTools));
272
271
  continue;
273
272
  }
274
273
  throw new HttpError(400, `Anthropic content block type '${type}' is not supported.`, "unsupported_content_block", param);
@@ -276,6 +275,27 @@ function appendAnthropicMessage(
276
275
  flushMessage();
277
276
  }
278
277
 
278
+ /* A `tool_addition` carries the tool by value (`tool_definition`) or names a
279
+ tool already declared (`tool_reference`), which Claude Code sends for a
280
+ deferred tool it loads mid-session. A referenced tool is added by value,
281
+ no longer deferred, so every provider path sees its full definition. */
282
+ function anthropicToolAddition(value: unknown, param: string, declaredTools: Map<string, InteractionTool>): InteractionTool {
283
+ if (!isRecord(value)) throw invalidRequest(`${param} must be an object.`, param);
284
+ const type = requiredString(value.type, `${param}.type`);
285
+ if (type === "tool_definition") {
286
+ const tool = anthropicTool(value.definition, `${param}.definition`);
287
+ if (tool.kind !== "hosted" && tool.kind !== "server_tool") declaredTools.set(tool.name, tool);
288
+ return tool;
289
+ }
290
+ if (type === "tool_reference") {
291
+ const name = requiredString(value.name, `${param}.name`);
292
+ const tool = declaredTools.get(name);
293
+ if (tool === undefined) throw invalidRequest(`${param} references undeclared tool '${name}'.`, `${param}.name`);
294
+ return tool.kind === "function" ? { ...tool, deferLoading: undefined } : tool;
295
+ }
296
+ throw new HttpError(400, `Anthropic tool_addition tool type '${type}' is not supported.`, "unsupported_content_block", `${param}.type`);
297
+ }
298
+
279
299
  /* PDFs stay native documents; they route only to models that read PDFs.
280
300
  Text and content documents become ordinary parts so every model can read
281
301
  them. Title and context travel as a leading text part. Citations are not
@@ -7,18 +7,28 @@
7
7
  * ```ts
8
8
  * import { startStubGateway } from "@mupt-ai/dari-gateway/self_host/stub_gateway";
9
9
  * const gateway = await startStubGateway({ plans: ["openai_codex"] });
10
- * // gateway.baseUrl, gateway.gatewayKey, gateway.planIds, gateway.calls; await gateway.stop();
10
+ * // Your app's Dari Link settings in the test: gateway.app.
11
+ * // The user clicks Connect with Dari and approves:
12
+ * const { code, codeVerifier } = await gateway.connect();
13
+ * // Send them to your server as your page does; then gateway.calls; await gateway.stop();
11
14
  * ```
12
15
  *
13
16
  * From any other test runner, as a process (`dari-gateway-stub`, see
14
17
  * stub_main.ts): it prints one JSON line with the same fields and serves the
15
18
  * recorded calls at `GET <controlUrl>/served`.
16
19
  *
17
- * Approval without a browser: `gateway.approve(authorizeUrl)` (or `POST
18
- * <controlUrl>/approve` with `{"url"}`) opens the approval page as the user
19
- * who connected the stand-in plans, ticks every plan the app can use (or
20
- * `credentialIds`), approves (or denies with `deny`), and returns what the
21
- * page hands the app:
20
+ * `gateway.app` is a server app registered on the gateway (a confidential
21
+ * client: `gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
22
+ * `gateway.connect()` (or `POST <controlUrl>/connect`) is its user approving
23
+ * it: it resolves with what `DariLink.open` hands your page, `{code,
24
+ * codeVerifier, state}`, or rejects with the `LinkError` it would (`deny`).
25
+ * `clients`, `plans`, `keyProviders`, and `grantId` are `DariLink.open`'s.
26
+ *
27
+ * To drive an approval for an app you registered yourself:
28
+ * `gateway.approve(authorizeUrl)` (or `POST <controlUrl>/approve` with
29
+ * `{"url"}`) opens the approval page as the user who connected the stand-in
30
+ * plans, ticks every plan the app can use (or `credentialIds`), approves (or
31
+ * denies with `deny`), and returns what the page hands the app:
22
32
  * `{message, targetOrigin}`, the `web_message` post or the redirect's query.
23
33
  * Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
24
34
  *
@@ -51,6 +61,7 @@ import { join } from "node:path";
51
61
  import { fileURLToPath } from "node:url";
52
62
  import { zstdDecompressSync } from "node:zlib";
53
63
 
64
+ import { authorizeUrl, LinkError } from "../link/client.js";
54
65
  import { linkUserCookie } from "../link/endpoints.js";
55
66
  import type { SubscriptionKind } from "../types.js";
56
67
  import { SqliteLinkStore } from "../link/sqlite_store.js";
@@ -99,6 +110,22 @@ export type StubGatewayOptions = {
99
110
  port?: number;
100
111
  // Hosts the gateway allows http redirect URIs on (`link.allowHttpRedirectHosts`).
101
112
  allowHttpRedirectHosts?: string[];
113
+ // The redirect URI `app` is registered with. Default: `https://app.test/dari/callback`.
114
+ redirectUri?: string;
115
+ };
116
+
117
+ /** A server app on the stub gateway: the settings an app's Dari Link calls take. */
118
+ export type StubLinkApp = { gatewayUrl: string; clientId: string; clientSecret: string; redirectUri: string };
119
+
120
+ export type StubConnectOptions = {
121
+ // The plans and keys the user shares. Default: every one the app can use.
122
+ credentialIds?: string[];
123
+ deny?: boolean;
124
+ // As `DariLink.open` takes them.
125
+ clients?: string[];
126
+ plans?: string[];
127
+ keyProviders?: string[];
128
+ grantId?: string;
102
129
  };
103
130
 
104
131
  /** What the approval page handed the app: a `web_message` post, or a redirect's query. */
@@ -133,6 +160,10 @@ export type StubGateway = {
133
160
  // What each `approve` handed the app, in order.
134
161
  messages: StubLinkMessage[];
135
162
  approve(authorizeUrl: string, options?: { credentialIds?: string[]; deny?: boolean }): Promise<StubLinkMessage>;
163
+ // A server app registered on the gateway, and its user approving it: what
164
+ // `DariLink.open` resolves with.
165
+ app: StubLinkApp;
166
+ connect(options?: StubConnectOptions): Promise<{ code: string; codeVerifier: string; state: string }>;
136
167
  setState(state: StubState): void;
137
168
  stop(): Promise<void>;
138
169
  };
@@ -152,6 +183,9 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
152
183
  let approve: StubGateway["approve"] = async () => {
153
184
  throw new Error("The gateway is not up yet.");
154
185
  };
186
+ let connect: StubGateway["connect"] = async () => {
187
+ throw new Error("The gateway is not up yet.");
188
+ };
155
189
  const provider = Bun.serve({
156
190
  port: 0,
157
191
  hostname: "127.0.0.1",
@@ -163,6 +197,30 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
163
197
  state = (await request.json()) as StubState;
164
198
  return Response.json({ state });
165
199
  }
200
+ if (pathname === "/connect" && request.method === "POST") {
201
+ // No body is the user sharing everything the app can use.
202
+ const body = ((await request.json().catch(() => null)) ?? {}) as {
203
+ credential_ids?: string[];
204
+ deny?: boolean;
205
+ clients?: string[];
206
+ plans?: string[];
207
+ key_providers?: string[];
208
+ grant_id?: string;
209
+ };
210
+ try {
211
+ const result = await connect({
212
+ ...(body.credential_ids ? { credentialIds: body.credential_ids } : {}),
213
+ ...(body.deny ? { deny: true } : {}),
214
+ ...(body.clients ? { clients: body.clients } : {}),
215
+ ...(body.plans ? { plans: body.plans } : {}),
216
+ ...(body.key_providers ? { keyProviders: body.key_providers } : {}),
217
+ ...(body.grant_id ? { grantId: body.grant_id } : {}),
218
+ });
219
+ return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
220
+ } catch (error) {
221
+ return Response.json({ error: error instanceof LinkError ? error.code : String(error) }, { status: 400 });
222
+ }
223
+ }
166
224
  if (pathname === "/approve" && request.method === "POST") {
167
225
  const body = (await request.json()) as { url: string; credential_ids?: string[]; deny?: boolean };
168
226
  try {
@@ -289,6 +347,31 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
289
347
  messages.push(result);
290
348
  return result;
291
349
  };
350
+ const registered = await fetch(`${baseUrl}/v1/link/apps`, {
351
+ method: "POST",
352
+ headers: { authorization: `Bearer ${gatewayKey}`, "content-type": "application/json" },
353
+ body: JSON.stringify({
354
+ name: "Stub App",
355
+ redirect_uris: [options.redirectUri ?? "https://app.test/dari/callback"],
356
+ confidential: true,
357
+ }),
358
+ });
359
+ if (!registered.ok) throw new Error(`The stub app was not registered:\n${await registered.text()}`);
360
+ const { client_id: clientId, client_secret: clientSecret } = (await registered.json()) as { client_id: string; client_secret: string };
361
+ const app: StubLinkApp = {
362
+ gatewayUrl: baseUrl,
363
+ clientId,
364
+ clientSecret,
365
+ redirectUri: options.redirectUri ?? "https://app.test/dari/callback",
366
+ };
367
+ connect = async ({ credentialIds, deny, ...request } = {}) => {
368
+ const { url, codeVerifier, state } = await authorizeUrl({ ...app, ...request, responseMode: "web_message" });
369
+ const { message } = await approve(url, { ...(credentialIds ? { credentialIds } : {}), ...(deny ? { deny } : {}) });
370
+ if (message.code === undefined) {
371
+ throw new LinkError(message.error ?? "invalid_request", message.error_description ?? "Dari Link was not approved.", 0);
372
+ }
373
+ return { code: message.code, codeVerifier, state };
374
+ };
292
375
  return {
293
376
  baseUrl,
294
377
  gatewayKey,
@@ -302,6 +385,8 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
302
385
  dbPath,
303
386
  messages,
304
387
  approve: (url, approveOptions) => approve(url, approveOptions),
388
+ app,
389
+ connect: (connectOptions) => connect(connectOptions),
305
390
  setState: (next) => {
306
391
  state = next;
307
392
  },
@@ -7,10 +7,14 @@
7
7
  * ```
8
8
  *
9
9
  * It prints one JSON line, `{"baseUrl", "gatewayKey", "planIds", "keyIds",
10
- * "userCookie", "controlUrl"}`, then serves until it is killed. The plans are the approval
11
- * page's user's: `userCookie` is the `Cookie` header that opens the page as them. `GET <controlUrl>/served`
10
+ * "userCookie", "controlUrl", "app"}`, then serves until it is killed. The plans are the approval
11
+ * page's user's: `userCookie` is the `Cookie` header that opens the page as them. `app` is a server
12
+ * app registered on the gateway (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
13
+ * `POST <controlUrl>/connect` (with `{"credential_ids"?, "deny"?, "clients"?, "plans"?,
14
+ * "key_providers"?, "grant_id"?}`, all optional) is its user approving it: it answers
15
+ * `{"code", "code_verifier", "state"}`, what Connect with Dari hands your page. `GET <controlUrl>/served`
12
16
  * answers `{"calls": [...]}`: every provider call so far, with its path,
13
- * model, thinking, and client headers. `POST <controlUrl>/approve` with
17
+ * model, thinking, and client headers. For an app you registered yourself, `POST <controlUrl>/approve` with
14
18
  * `{"url": <authorize URL>, "credential_ids"?, "deny"?}` goes through the
15
19
  * approval page and answers `{"message", "target_origin"}`, which `GET
16
20
  * <controlUrl>/messages` lists; `POST <controlUrl>/state` with `{"limited"?,
@@ -19,6 +23,7 @@
19
23
  * `openai_codex` and `anthropic_claude_code`), `--keys` (comma-separated
20
24
  * `anthropic`, `openai`, and `openrouter`: an API key of the plans' user for each), `--models` (the default
21
25
  * router's models), `--key` (the gateway key), `--port` (the gateway's port),
26
+ * `--redirect-uri` (the redirect URI `app` is registered with),
22
27
  * and `--allow-http-redirect-host` (repeatable: a host apps may register http
23
28
  * redirect URIs on, such as `*.example.ts.net`).
24
29
  */
@@ -48,6 +53,7 @@ if (port !== undefined && !/^\d+$/.test(port)) {
48
53
  console.error("--port takes a port number.");
49
54
  process.exit(2);
50
55
  }
56
+ const redirectUri = option("redirect-uri");
51
57
  const httpHosts = process.argv.flatMap((arg, index) => arg === "--allow-http-redirect-host" ? [process.argv[index + 1] ?? ""] : []);
52
58
  const gateway = await startStubGateway({
53
59
  ...(plans ? { plans: plans as NonNullable<StubGatewayOptions["plans"]> } : {}),
@@ -55,6 +61,7 @@ const gateway = await startStubGateway({
55
61
  ...(models ? { models } : {}),
56
62
  ...(gatewayKey ? { gatewayKey } : {}),
57
63
  ...(port ? { port: Number(port) } : {}),
64
+ ...(redirectUri ? { redirectUri } : {}),
58
65
  ...(httpHosts.length > 0 ? { allowHttpRedirectHosts: httpHosts } : {}),
59
66
  });
60
67
  console.log(JSON.stringify({
@@ -64,6 +71,7 @@ console.log(JSON.stringify({
64
71
  keyIds: gateway.keyIds,
65
72
  userCookie: gateway.userCookie,
66
73
  controlUrl: gateway.controlUrl,
74
+ app: gateway.app,
67
75
  }));
68
76
  for (const signal of ["SIGINT", "SIGTERM"] as const) {
69
77
  process.on(signal, () => {