@mupt-ai/dari-gateway 1.0.313 → 1.0.315
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.
- package/README.md +17 -20
- package/dist/http/handler.js +1 -1
- package/dist/http/http2_server.js +5 -1
- package/dist/ingress/anthropic_messages.js +1 -1
- package/dist/ingress/models.js +1 -1
- package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
- package/dist/{link_client.js → link/client.js} +5 -6
- package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
- package/dist/{ingress/link.js → link/endpoints.js} +158 -62
- package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
- package/dist/link/grants.d.ts +151 -0
- package/dist/link/grants.js +275 -0
- package/dist/link/key_providers.d.ts +6 -0
- package/dist/link/key_providers.js +21 -0
- package/dist/link/self_hosted.d.ts +3 -0
- package/dist/link/self_hosted.js +166 -0
- package/dist/link/service.d.ts +85 -0
- package/dist/link/service.js +187 -0
- package/dist/link/sqlite_store.d.ts +74 -0
- package/dist/link/sqlite_store.js +381 -0
- package/dist/models/canonical_models.json +19 -0
- package/dist/platform/platform.d.ts +42 -47
- package/dist/runtime/explicit_model.js +1 -1
- package/dist/runtime/prepare_routed_completion.js +1 -1
- package/dist/self_host/main.js +2 -2
- package/dist/self_host/platform.js +4 -249
- package/dist/self_host/resolve.d.ts +2 -2
- package/dist/self_host/resolve.js +3 -19
- package/dist/self_host/stub_gateway.js +3 -3
- package/dist/self_host/subscriptions/http.js +2 -2
- package/dist/telemetry/report.js +1 -1
- package/package.json +2 -2
- package/src/http/handler.ts +1 -1
- package/src/http/http2_server.ts +4 -1
- package/src/ingress/anthropic_messages.ts +1 -1
- package/src/ingress/models.ts +1 -1
- package/src/{link_client.ts → link/client.ts} +11 -14
- package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
- package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
- package/src/link/grants.ts +436 -0
- package/src/link/key_providers.ts +25 -0
- package/src/link/self_hosted.ts +186 -0
- package/src/link/service.ts +281 -0
- package/src/link/sqlite_store.ts +512 -0
- package/src/models/canonical_models.json +19 -0
- package/src/platform/platform.ts +39 -45
- package/src/runtime/explicit_model.ts +1 -1
- package/src/runtime/prepare_routed_completion.ts +1 -1
- package/src/self_host/main.ts +2 -2
- package/src/self_host/platform.ts +5 -267
- package/src/self_host/resolve.ts +6 -21
- package/src/self_host/stub_gateway.ts +3 -3
- package/src/self_host/subscriptions/http.ts +2 -2
- package/src/telemetry/report.ts +1 -1
- package/dist/self_host/link_store.d.ts +0 -167
- package/dist/self_host/link_store.js +0 -564
- package/src/self_host/link_store.ts +0 -782
- /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
- /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
- /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
- /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
- /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
- /package/dist/{models/link_errors.js → link/errors.js} +0 -0
- /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
- /package/dist/{ingress/link_font.js → link/font.js} +0 -0
- /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
- /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
- /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
- /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
- /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
- /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
package/README.md
CHANGED
|
@@ -65,7 +65,7 @@ docker run -p 8080:8080 \
|
|
|
65
65
|
| `DARI_GATEWAY_CONFIG` | Router config file. Default `dari-gateway.yaml`. |
|
|
66
66
|
| `DARI_GATEWAY_DB` | SQLite database for subscriptions, Dari Link grants, model lists saved with `dari gateway models`, and conversation state. Default `dari-gateway.db`. Without `DARI_GATEWAY_ENCRYPTION_KEY` it stores subscription tokens in plaintext; protect it like a secret either way. |
|
|
67
67
|
| `DARI_GATEWAY_ENCRYPTION_KEY` | Encrypts the subscription tokens, pending sign-ins, and API keys in the database: a 32-byte key in base64 (`openssl rand -base64 32`). Each value is sealed with AES-256-GCM and bound to its own row, so a copied database, or a token moved into another row, is useless without the key. Keep the key outside the database's storage and backups (a secret manager, not the same disk). To rotate, list the new key first and the old one after a comma, start the gateway once (it re-encrypts everything under the first), then drop the old one. Required for Dari Link: without it the approval page takes nobody's subscriptions or keys. Losing the key loses the stored subscriptions; users connect again. |
|
|
68
|
-
| `DARI_LINK_SESSION_SECRET` | Signs the cookie that remembers
|
|
68
|
+
| `DARI_LINK_SESSION_SECRET` | Signs the cookie that remembers the user of Dari Link's approval and connections pages. Unset, each gateway process makes its own, so a restart forgets who connected which plans. Set it on any gateway that serves Dari Link. |
|
|
69
69
|
| `DARI_AUTO_ROUTING_API_KEY` | Optional. Select among a router's models with Dari Auto Routing. |
|
|
70
70
|
| `PORT` | Listen port. Default `8080`. |
|
|
71
71
|
| `DARI_GATEWAY_HOST` | Listen address. Default `127.0.0.1`, so only this machine can connect. The container image sets `0.0.0.0`; set it yourself to expose a process on your network. |
|
|
@@ -132,7 +132,7 @@ For a server app (a confidential client), the server makes the PKCE pair and sta
|
|
|
132
132
|
|
|
133
133
|
```ts
|
|
134
134
|
// On your server: start a connection and keep the verifier with the session.
|
|
135
|
-
import { createAuthorization } from "@mupt-ai/dari-gateway/
|
|
135
|
+
import { createAuthorization } from "@mupt-ai/dari-gateway/link/client";
|
|
136
136
|
|
|
137
137
|
app.post("/api/dari/start", async (req, res) => {
|
|
138
138
|
const { codeVerifier, codeChallenge, state } = await createAuthorization();
|
|
@@ -143,7 +143,7 @@ app.post("/api/dari/start", async (req, res) => {
|
|
|
143
143
|
|
|
144
144
|
```ts
|
|
145
145
|
// In your app's bundle. The client uses only fetch (and Web Crypto when it makes PKCE itself).
|
|
146
|
-
import { DariLink } from "@mupt-ai/dari-gateway/
|
|
146
|
+
import { DariLink } from "@mupt-ai/dari-gateway/link/client";
|
|
147
147
|
|
|
148
148
|
DariLink.renderButton(document.getElementById("connect-dari"), {
|
|
149
149
|
onClick: async () => {
|
|
@@ -167,7 +167,7 @@ DariLink.renderButton(document.getElementById("connect-dari"), {
|
|
|
167
167
|
Your server checks `state`, redeems the code with the verifier it kept, and keeps the tokens with the user:
|
|
168
168
|
|
|
169
169
|
```ts
|
|
170
|
-
import { exchange, linkFetch } from "@mupt-ai/dari-gateway/
|
|
170
|
+
import { exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
|
|
171
171
|
|
|
172
172
|
const client = { gatewayUrl: "https://routing.dari.dev", clientId, clientSecret };
|
|
173
173
|
const { codeVerifier, state: expected } = req.session.dariLink;
|
|
@@ -181,10 +181,10 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
181
181
|
- A browser-only app (a public client) leaves out `codeChallenge` and `state`: `DariLink.open` makes the PKCE pair in the page and resolves with `{ code, state, codeVerifier }` (`codeVerifier` is null when the server made it). That needs a secure page (https, or localhost); elsewhere it rejects with `insecure_context` before opening anything.
|
|
182
182
|
- Get `clientId` (and a server's `clientSecret`) by registering the app: on hosted Dari under **Settings → Dari Link Apps**, or with the API or CLI in step 1 below.
|
|
183
183
|
- Call `DariLink.open` from the click handler, so the browser allows the popup. It opens the popup before awaiting anything, so its options may be a function returning a promise (`DariLink.open(async () => ({ ...await fetchConfig() }))`), fetched after the popup is open; Safari blocks a popup opened after an `await`. It rejects with a `LinkError`: `access_denied` when the user denies, `popup_closed`, or `popup_blocked`.
|
|
184
|
-
- `onEvent(step)` hears each step the user reaches in the popup (`
|
|
184
|
+
- `onEvent(step)` hears each step the user reaches in the popup (`connect_subscription` when they have no plan to share yet, `choose_plans`), and `onExit({ error, step })` says where they left before it rejects (`step` is `denied` when they denied, null when they reached none), so you can tell "closed while connecting a plan" from "closed after seeing the plans". The popup posts each step as `{"type": "dari-link-event", "version": "1", "event": "<step>", "state"}` to your redirect URI's origin; only the result is `{"type": "dari-link", ...}`, with `code` or `error`. A client reading the messages itself should ignore any other type, and any `dari-link` message with neither `code` nor `error`.
|
|
185
185
|
- The popup posts its result to your window with `response_mode=web_message`, readable only by your redirect URI's origin; `DariLink.open` accepts it only from the popup, from the origin the gateway's metadata names (`web_message_origin`), and with the state it made.
|
|
186
|
-
- Put `DariLink.callback()` on your redirect URI's page. A popup that
|
|
187
|
-
- Users see
|
|
186
|
+
- Put `DariLink.callback()` on your redirect URI's page. A popup that sent the user to a provider's sign-in along the way can lose its link to your window; the approval then arrives on that page inside the popup, and `callback()` hands it to the window that opened it and closes the popup. A page whose CSP keeps it from bundling the client can load `<script src="<gateway>/v1/link/callback.js"></script>` (the metadata's `callback_script`) instead. The contract is stable: on the `BroadcastChannel` named `dari-link`, the page posts `{"type": "dari-link", "state", "code"}` or `{"type": "dari-link", "state", "error", "error_description"}`, then closes.
|
|
187
|
+
- Users see the apps they connected on the gateway's connections page, `/v1/link/connections`, in the browser they connected from: what each shares and used, its budget, and Disconnect, and the plans and keys they can remove. Link there with the grant's `manage_url` (that app's card) or the metadata's `connected_apps_uri`.
|
|
188
188
|
- **Update mode.** To let the user change which plans an app has, open the same flow with `grantId` (`grant_id=<lgr_…>` on the authorize request): the page is titled "Update Plans For <App>", starts with the grant's plans and budget, and saves to the same grant. Its id and every token it issued keep working; the new code redeems for more tokens of it, which you may keep or drop. A `grant_id` that is not this browser's user's grant for this app (another browser, cleared cookies) starts a new connection instead, and leaves that grant as it was.
|
|
189
189
|
- One grant may back several records in your app (one per plan, say) only with a confidential client: a public client's refresh token rotates on every use, so two records holding it race.
|
|
190
190
|
|
|
@@ -202,11 +202,9 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
202
202
|
- `response_mode=web_message`: for a page opened as a popup. The result is posted to the window that opened it (`{"type": "dari-link", "code" | "error", "state"}`, addressed to the redirect URI's origin) instead of sent on a redirect; a page with no opener left redirects to `redirect_uri` instead. `DariLink.open` does this for you.
|
|
203
203
|
- `grant_id`: update mode (above).
|
|
204
204
|
|
|
205
|
-
|
|
205
|
+
The gateway serves the page itself, hosted and self-hosted alike, and it needs no sign-in, like a bank link. A new user sees what connecting means, picks a subscription (Claude, ChatGPT, Meta Muse, OpenCode Go) or a provider to add an API key for, signs in to that provider (Claude shows a code to paste back; the others take a code the page shows and continue on their own), and allows the app with what they connected ticked. Their first plan or key makes them a user (on hosted Dari, a Dari account they never sign in to), and the gateway remembers them in a signed HttpOnly cookie, so the next app that asks finds their plans connected and takes one click. A self-hosted gateway takes their subscriptions and keys only when it encrypts what it stores (`DARI_GATEWAY_ENCRYPTION_KEY`). A plan a user connects this way is theirs alone: it serves only the grants they approve, never a gateway key, and the gateway owner's own plans are never offered on the page.
|
|
206
206
|
|
|
207
|
-
The
|
|
208
|
-
|
|
209
|
-
Either way the user approves; they can later cap the tokens the app may use per 5 hours and per week (see **Budgets**). The app gets `code` and `state`, or `error=access_denied`, on `redirect_uri` or as the popup's message.
|
|
207
|
+
The user approves; they can later cap the tokens the app may use per 5 hours and per week (see **Budgets**). The app gets `code` and `state`, or `error=access_denied`, on `redirect_uri` or as the popup's message.
|
|
210
208
|
3. `POST /v1/link/token` (form or JSON; CORS open) with `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `code_verifier` returns an access token (`dlk_at_…`, one hour) and a refresh token (`dlk_rt_…`), with the grant's fields below. `grant_type=refresh_token` with `refresh_token` returns a new access token:
|
|
211
209
|
- Every access token lives until its own expiry, so requests in flight on an older one complete.
|
|
212
210
|
- A public client's refresh token rotates on every use. Presenting the rotated one again within a minute is refused as `invalid_grant` with `"error_code": "refresh_race"` and nothing is revoked: use the tokens the winning request received. Presenting it later revokes the grant.
|
|
@@ -217,7 +215,7 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
217
215
|
- `opus`, `sonnet`, `haiku`, and the other Anthropic tier names route, as `dari/routing` does.
|
|
218
216
|
- `POST /v1/messages/count_tokens` is not served: it answers an Anthropic-shaped 404, on which Claude Code estimates locally.
|
|
219
217
|
- A non-streamed response carries `X-Dari-Usage: {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}` (input excludes cache reads and writes) beside `X-Dari-Selected-Model` and `X-Dari-Thinking-Level`, the same whatever protocol the app speaks. A stream reports usage in its protocol's own final event; `GET /v1/link/usage` has both.
|
|
220
|
-
5. The app ends its grant with `POST /v1/link/revoke` (RFC 7009: `client_id` and `token`, any of the grant's tokens; always 200). The user
|
|
218
|
+
5. The app ends its grant with `POST /v1/link/revoke` (RFC 7009: `client_id` and `token`, any of the grant's tokens; always 200). The user disconnects an app and changes its budget on the connections page. With a key, `GET` and `DELETE /v1/link/grants[/<id>]` and `PUT /v1/link/grants/<id>/budget` do the same: on hosted Dari a personal key manages its own user's grants, and on a self-hosted gateway a gateway key manages every grant. A revoked grant's tokens, access tokens included, stop working at once.
|
|
221
219
|
|
|
222
220
|
**The grant.** The token response and `GET /v1/link/grant` (bearer: the access token) describe the grant:
|
|
223
221
|
|
|
@@ -226,8 +224,7 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
226
224
|
"grant_id": "lgr_…", "client_id": "lnk_…", "app_name": "Notes", "created_at": "…", "scope": "route",
|
|
227
225
|
"budget": [{"window_minutes": 10080, "max_tokens": 5000000, "used_tokens": 312000, "resets_at": null}],
|
|
228
226
|
"state": "ready", "available_at": null,
|
|
229
|
-
"
|
|
230
|
-
"manage_url": "https://app.dari.dev/connected-apps&grant=lgr_…",
|
|
227
|
+
"manage_url": "https://routing.dari.dev/v1/link/connections#lgr_…",
|
|
231
228
|
"plans": [{
|
|
232
229
|
"id": "…", "kind": "openai_codex", "plan": "ChatGPT Plus/Pro", "label": "a@example.com", "account_email": "a@example.com",
|
|
233
230
|
"serves": "any_app", "state": "ready", "available_at": null, "unavailable_until": null,
|
|
@@ -239,11 +236,11 @@ await dari("/v1/chat/completions", { method: "POST", headers: { "content-type":
|
|
|
239
236
|
}
|
|
240
237
|
```
|
|
241
238
|
|
|
242
|
-
`serves` is `any_app`, `claude_code_only`, or `muse_code_only`. A plan's `state` is the one answer to "can this plan serve the app now": `ready`, or `plan_limit`, the plan is at its own usage limit; `available_at` is when it serves again (null when ready or unknown). The grant's own `state` is `budget_limit` while a window of its budget is at its cap, until `available_at` (see **Budgets**). `
|
|
239
|
+
`serves` is `any_app`, `claude_code_only`, or `muse_code_only`. A plan's `state` is the one answer to "can this plan serve the app now": `ready`, or `plan_limit`, the plan is at its own usage limit; `available_at` is when it serves again (null when ready or unknown). The grant's own `state` is `budget_limit` while a window of its budget is at its cap, until `available_at` (see **Budgets**). `label` is the user's name for the plan, else its account. `usage` lists the quota windows the plan last reported (five hours and a week for these plans), each with the share used from 0 to 1 and when it resets; it is empty until the plan has served a request through Dari (any request, not only this app's, including the user's own Claude Code or Codex through Dari), because plans report their windows only on responses. Dari does not read a fresh plan's windows when it connects: that takes a call to the provider with the user's credential that neither Claude nor ChatGPT documents for third parties, so a just-connected plan shows no usage until its first request. A plan's `models` are those it serves its clients now, each with the name a request uses (`id`) and the catalog's display name (`name`); the top-level `models` are what a plain API client can name now, and `routes` says whether `dari/routing` serves it. `GET /v1/models` with a link token lists the same models in the OpenAI list shape, empty when none can serve. `GET /v1/link/grant` makes no provider call, so it is the cheap check before a long run: a dead grant answers 401, and `unavailable_until` and `usage` say whether the plans have room.
|
|
243
240
|
|
|
244
|
-
**Budgets.** A user can cap the tokens an app may use per five hours and per week: on
|
|
241
|
+
**Budgets.** A user can cap the tokens an app may use per five hours and per week: on the connections page, or with `PUT /v1/link/grants/<id>/budget` and `{"budget": [{"window_minutes": 10080, "max_tokens": 5000000}]}` (the user's key; `window_minutes` is `300` or `10080`; `[]` removes it). The budget covers the whole grant: all its plans and API keys together.
|
|
245
242
|
|
|
246
|
-
Tokens are what Dari recorded for the grant's requests, child tokens' included: input + output + cache read + cache write, the same total `GET /v1/link/usage` and the
|
|
243
|
+
Tokens are what Dari recorded for the grant's requests, child tokens' included: input + output + cache read + cache write, the same total `GET /v1/link/usage` and the connections page show. Windows roll: a window's `used_tokens` are those of requests received in its last `window_minutes`. Before each request, a grant with any window at its cap is refused with 424 `grant_budget_exhausted`, with `resets_at` (and `Retry-After`) set to when enough of the window's oldest requests roll off to bring it under the cap; a budget window's `resets_at` is that same time, and null while under the cap. A request is counted once it finishes, so requests in flight may take a window past its cap.
|
|
247
244
|
|
|
248
245
|
**Usage.** Every request a grant's tokens make, child tokens' included, streamed or not, is recorded once it finishes (a moment after the response). `GET /v1/link/usage` (bearer: the access token; CORS open) reads it back:
|
|
249
246
|
|
|
@@ -298,7 +295,7 @@ A sandbox given a child token needs to reach only the gateway's host (for hosted
|
|
|
298
295
|
|
|
299
296
|
Error text replaces anything shaped like an `sk-` key with `sk-…`, and responses replace the serving plan's own credential wherever it appears.
|
|
300
297
|
|
|
301
|
-
**Client.** `@mupt-ai/dari-gateway/
|
|
298
|
+
**Client.** `@mupt-ai/dari-gateway/link/client` (fetch and Web Crypto only; browsers, Node, Bun, Deno; erasable TypeScript only, so `node` runs the `.ts` file as is) has `DariLink` (`open`, `callback`, `renderButton`), `createAuthorization` (a PKCE pair and state for your server), `registerClient`, `authorizeUrl` (makes the PKCE verifier and state; takes `clients`, `plans`, `purposes`, and `grantId`), `exchange`, `refresh`, `childToken`, `revoke`, and `linkFetch`. Every call takes `clientSecret` for a confidential client. `linkFetch` is a fetch that treats your storage as the source of truth: it reads the tokens with your `loadTokens` on every call, attaches the access token, refreshes it before it expires or once after a 401 for an expired token with one refresh at a time, and passes every new token set to your `saveTokens` before using it. `childToken` takes the same `loadTokens` and `saveTokens` instead of an `accessToken`, refreshing the grant's access token as needed. When the user is unlinked:
|
|
302
299
|
|
|
303
300
|
- `loadTokens` returning null makes both throw `LinkError` `not_linked`, with no call to the gateway;
|
|
304
301
|
- a `LinkError` with code `invalid_grant` from a refresh means the grant is gone;
|
|
@@ -309,7 +306,7 @@ Each means: show the user Reconnect. `usage({ fetcher: gatewayFetch, tags, since
|
|
|
309
306
|
A server-side integration, start to finish:
|
|
310
307
|
|
|
311
308
|
```ts
|
|
312
|
-
import { authorizeUrl, childToken, exchange, linkFetch, revoke } from "@mupt-ai/dari-gateway/
|
|
309
|
+
import { authorizeUrl, childToken, exchange, linkFetch, revoke } from "@mupt-ai/dari-gateway/link/client";
|
|
313
310
|
|
|
314
311
|
// Registered once, under Settings → Dari Link Apps or with POST /v1/link/register.
|
|
315
312
|
const client = { gatewayUrl, clientId, clientSecret: process.env.DARI_LINK_CLIENT_SECRET };
|
|
@@ -350,7 +347,7 @@ await revoke({ ...client, token: (await db.loadTokens(userId)).refreshToken });
|
|
|
350
347
|
- treat `invalid_grant`, `grant_revoked`, and `not_linked` as unlinked: stop the agent and show Reconnect.
|
|
351
348
|
|
|
352
349
|
```ts
|
|
353
|
-
import { LinkError, linkFetch } from "@mupt-ai/dari-gateway/
|
|
350
|
+
import { LinkError, linkFetch } from "@mupt-ai/dari-gateway/link/client";
|
|
354
351
|
|
|
355
352
|
const DROP = new Set(["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "te", "trailer", "authorization", "x-api-key"]);
|
|
356
353
|
|
package/dist/http/handler.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { handleResponses, handleResponsesWebSocketFallback, } from "../ingress/codex.js";
|
|
2
|
-
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../
|
|
2
|
+
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../link/endpoints.js";
|
|
3
3
|
import { handleModels } from "../ingress/models.js";
|
|
4
4
|
import { handleMuseCodeModels } from "../ingress/muse_models.js";
|
|
5
5
|
import { handleChatCompletions } from "../ingress/chat_completions.js";
|
|
@@ -55,10 +55,14 @@ async function handleRequest(incoming, outgoing, handler) {
|
|
|
55
55
|
const response = await handler(toRequest(incoming, abort.signal));
|
|
56
56
|
outgoing.statusCode = response.status;
|
|
57
57
|
for (const [name, value] of response.headers) {
|
|
58
|
-
if (!HTTP2_FORBIDDEN_RESPONSE_HEADERS.has(name
|
|
58
|
+
if (name !== "set-cookie" && !HTTP2_FORBIDDEN_RESPONSE_HEADERS.has(name)) {
|
|
59
59
|
outgoing.setHeader(name, value);
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
+
// Headers yields each cookie on its own, so setting them one by one keeps only the last.
|
|
63
|
+
const cookies = response.headers.getSetCookie();
|
|
64
|
+
if (cookies.length > 0)
|
|
65
|
+
outgoing.setHeader("set-cookie", cookies);
|
|
62
66
|
if (response.body === null || incoming.method === "HEAD") {
|
|
63
67
|
outgoing.end();
|
|
64
68
|
return;
|
|
@@ -3,7 +3,7 @@ import { anthropicMessagesResponse } from "../protocol/output/anthropic_messages
|
|
|
3
3
|
import { anthropicMessagesSseStream } from "../protocol/output/anthropic_messages_stream.js";
|
|
4
4
|
import { anthropicToken } from "../http/auth.js";
|
|
5
5
|
import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
|
|
6
|
-
import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../
|
|
6
|
+
import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../link/errors.js";
|
|
7
7
|
import { captureRequestError } from "../observability/errors.js";
|
|
8
8
|
import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
|
|
9
9
|
import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
|
package/dist/ingress/models.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
`provider=<id>[,<id>...]`. */
|
|
8
8
|
import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
9
9
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
10
|
-
import { LINK_GRANT_ERROR_CODES } from "../
|
|
10
|
+
import { LINK_GRANT_ERROR_CODES } from "../link/errors.js";
|
|
11
11
|
import { captureRequestError } from "../observability/errors.js";
|
|
12
12
|
import { anthropicErrorResponse } from "./anthropic_messages.js";
|
|
13
13
|
import { listModelCatalog } from "../models/catalog.js";
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* popup, the user signs in, picks plans, and approves, and the popup closes.
|
|
9
9
|
*
|
|
10
10
|
* ```ts
|
|
11
|
-
* import { DariLink } from "@mupt-ai/dari-gateway/
|
|
11
|
+
* import { DariLink } from "@mupt-ai/dari-gateway/link/client";
|
|
12
12
|
*
|
|
13
13
|
* button.onclick = async () => {
|
|
14
14
|
* const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* Without a popup, send the user to the approval URL yourself:
|
|
20
20
|
*
|
|
21
21
|
* ```ts
|
|
22
|
-
* import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/
|
|
22
|
+
* import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
|
|
23
23
|
*
|
|
24
24
|
* const { url, codeVerifier, state } = await authorizeUrl({ gatewayUrl, clientId, redirectUri });
|
|
25
25
|
* // Keep codeVerifier and state with the user's session, send them to `url`;
|
|
@@ -87,11 +87,7 @@ export type LinkTokenSet = {
|
|
|
87
87
|
availableAt: string | null;
|
|
88
88
|
plans: LinkPlan[];
|
|
89
89
|
models: LinkModel[];
|
|
90
|
-
|
|
91
|
-
email: string | null;
|
|
92
|
-
name: string | null;
|
|
93
|
-
} | null;
|
|
94
|
-
manageUrl: string | null;
|
|
90
|
+
manageUrl: string;
|
|
95
91
|
routes: boolean;
|
|
96
92
|
};
|
|
97
93
|
export type LinkChildToken = {
|
|
@@ -212,11 +208,11 @@ export type LinkBrowser = {
|
|
|
212
208
|
outerHeight?: number;
|
|
213
209
|
};
|
|
214
210
|
/**
|
|
215
|
-
* The approval step the user reached in the popup: `
|
|
216
|
-
*
|
|
217
|
-
*
|
|
211
|
+
* The approval step the user reached in the popup: `connect_subscription`
|
|
212
|
+
* (no plan to share yet) or `choose_plans`. A user who denies leaves at
|
|
213
|
+
* `denied`.
|
|
218
214
|
*/
|
|
219
|
-
export type LinkStep = "
|
|
215
|
+
export type LinkStep = "connect_subscription" | "choose_plans" | "denied";
|
|
220
216
|
/** Why the popup ended without a code, and the step the user left at (null before any). */
|
|
221
217
|
export type LinkExit = {
|
|
222
218
|
error: string;
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* popup, the user signs in, picks plans, and approves, and the popup closes.
|
|
9
9
|
*
|
|
10
10
|
* ```ts
|
|
11
|
-
* import { DariLink } from "@mupt-ai/dari-gateway/
|
|
11
|
+
* import { DariLink } from "@mupt-ai/dari-gateway/link/client";
|
|
12
12
|
*
|
|
13
13
|
* button.onclick = async () => {
|
|
14
14
|
* const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* Without a popup, send the user to the approval URL yourself:
|
|
20
20
|
*
|
|
21
21
|
* ```ts
|
|
22
|
-
* import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/
|
|
22
|
+
* import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
|
|
23
23
|
*
|
|
24
24
|
* const { url, codeVerifier, state } = await authorizeUrl({ gatewayUrl, clientId, redirectUri });
|
|
25
25
|
* // Keep codeVerifier and state with the user's session, send them to `url`;
|
|
@@ -138,7 +138,7 @@ const POPUP_POLL_MS = 400;
|
|
|
138
138
|
// A closed popup may have just handed its result to `completeLink`.
|
|
139
139
|
const POPUP_CLOSED_GRACE_MS = 300;
|
|
140
140
|
const LINK_CHANNEL = "dari-link";
|
|
141
|
-
const STEPS = ["
|
|
141
|
+
const STEPS = ["connect_subscription", "choose_plans"];
|
|
142
142
|
/**
|
|
143
143
|
* Open Dari's approval page in a popup and resolve with the code once the
|
|
144
144
|
* user approves. Call it from a click handler, so the browser allows the
|
|
@@ -316,7 +316,7 @@ export function renderButton(container, options) {
|
|
|
316
316
|
*/
|
|
317
317
|
export const DariLink = { open: openLink, callback: completeLink, renderButton };
|
|
318
318
|
// The origin the approval page posts its result from, as the gateway's
|
|
319
|
-
// metadata names it: the gateway
|
|
319
|
+
// metadata names it: the gateway's public origin.
|
|
320
320
|
async function approvalOrigin(args) {
|
|
321
321
|
const response = await (args.fetch ?? fetch)(endpoint(args.gatewayUrl, "/.well-known/oauth-authorization-server"));
|
|
322
322
|
const origin = (await json(response)).web_message_origin;
|
|
@@ -520,8 +520,7 @@ function tokenSet(payload) {
|
|
|
520
520
|
plans: Array.isArray(payload.plans) ? payload.plans : [],
|
|
521
521
|
models: Array.isArray(payload.models) ? payload.models : [],
|
|
522
522
|
routes: payload.routes === true,
|
|
523
|
-
|
|
524
|
-
manageUrl: typeof payload.manage_url === "string" ? payload.manage_url : null,
|
|
523
|
+
manageUrl: String(payload.manage_url),
|
|
525
524
|
};
|
|
526
525
|
}
|
|
527
526
|
// The JSON body of a successful response; otherwise a LinkError from either
|
|
@@ -17,8 +17,7 @@ export declare function linkUserCookie(secret: string, subject: string): string;
|
|
|
17
17
|
* The step of approval the user reached, which a popup posts to the window
|
|
18
18
|
* that opened it (`{type: "dari-link-event", version: 1, event, state}`; the
|
|
19
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
|
|
21
|
-
*
|
|
22
|
-
* denies leaves at `denied`, which the `access_denied` result says.
|
|
20
|
+
* left: `connect_subscription` (connecting a plan) or `choose_plans`. A user
|
|
21
|
+
* who denies leaves at `denied`, which the `access_denied` result says.
|
|
23
22
|
*/
|
|
24
|
-
export type LinkStep = "
|
|
23
|
+
export type LinkStep = "connect_subscription" | "choose_plans";
|