@mupt-ai/dari-gateway 1.0.321 → 1.0.322
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 +1 -1
- package/dist/link/budget.d.ts +6 -3
- package/dist/link/budget.js +6 -2
- package/dist/link/endpoints.d.ts +14 -1
- package/dist/link/endpoints.js +120 -36
- package/dist/link/errors.d.ts +20 -1
- package/dist/link/errors.js +35 -0
- package/dist/link/grants.d.ts +3 -1
- package/dist/link/grants.js +3 -0
- package/dist/link/key_providers.d.ts +2 -0
- package/dist/link/key_providers.js +4 -0
- package/dist/link/self_hosted.js +2 -2
- package/dist/link/service.d.ts +21 -1
- package/dist/link/service.js +25 -8
- package/dist/link/sqlite_store.d.ts +1 -0
- package/dist/link/sqlite_store.js +12 -11
- package/dist/platform/platform.d.ts +25 -4
- package/dist/self_host/resolve.js +6 -32
- package/package.json +2 -2
- package/src/link/budget.ts +12 -4
- package/src/link/endpoints.ts +130 -39
- package/src/link/errors.ts +53 -1
- package/src/link/grants.ts +6 -1
- package/src/link/key_providers.ts +5 -0
- package/src/link/self_hosted.ts +2 -2
- package/src/link/service.ts +33 -9
- package/src/link/sqlite_store.ts +27 -19
- package/src/platform/platform.ts +22 -4
- package/src/self_host/resolve.ts +10 -47
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { openWithoutKey } from "../self_host/secret_box.js";
|
|
3
|
-
import { LINK_TOKEN_RETENTION_MS, } from "./grants.js";
|
|
4
3
|
// Where a stored API key belongs, which its encryption is bound to.
|
|
5
4
|
function keyPlace(id) {
|
|
6
5
|
return `link_api_keys:${id}:api_key`;
|
|
@@ -149,10 +148,10 @@ export class SqliteLinkStore {
|
|
|
149
148
|
}
|
|
150
149
|
budgetUses(grantId, since) {
|
|
151
150
|
return this.db
|
|
152
|
-
.query(`SELECT received_at, input_tokens
|
|
151
|
+
.query(`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
|
|
153
152
|
FROM link_usage WHERE grant_id = ? AND received_at > ?`)
|
|
154
153
|
.all(grantId, since)
|
|
155
|
-
.map((row) => ({ at: new Date(row.received_at),
|
|
154
|
+
.map((row) => ({ at: new Date(row.received_at), ...tokenCounts(row) }));
|
|
156
155
|
}
|
|
157
156
|
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
158
157
|
recordUsage(entry) {
|
|
@@ -185,10 +184,7 @@ export class SqliteLinkStore {
|
|
|
185
184
|
model: row.model,
|
|
186
185
|
thinking: row.thinking,
|
|
187
186
|
tags: JSON.parse(row.tags),
|
|
188
|
-
|
|
189
|
-
outputTokens: row.output_tokens,
|
|
190
|
-
cacheReadTokens: row.cache_read_tokens,
|
|
191
|
-
cacheWriteTokens: row.cache_write_tokens,
|
|
187
|
+
...tokenCounts(row),
|
|
192
188
|
}));
|
|
193
189
|
}
|
|
194
190
|
addApp(app, now = new Date()) {
|
|
@@ -311,10 +307,7 @@ export class SqliteLinkStore {
|
|
|
311
307
|
if (rotated === 0)
|
|
312
308
|
return "race";
|
|
313
309
|
}
|
|
314
|
-
|
|
315
|
-
// Rotated refresh tokens stay while the grant lives (revoking it deletes
|
|
316
|
-
// them): presenting one again is how a stolen refresh token is caught.
|
|
317
|
-
this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
|
|
310
|
+
this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND (expires_at < ? OR (rotated_at < ? AND kind != 'refresh'))", [request.grantId, request.forgetBefore, request.forgetBefore]);
|
|
318
311
|
this.insertTokens(request.grantId, request.tokens, request.now);
|
|
319
312
|
return "ok";
|
|
320
313
|
})();
|
|
@@ -351,6 +344,14 @@ export class SqliteLinkStore {
|
|
|
351
344
|
return true;
|
|
352
345
|
}
|
|
353
346
|
}
|
|
347
|
+
function tokenCounts(row) {
|
|
348
|
+
return {
|
|
349
|
+
inputTokens: row.input_tokens,
|
|
350
|
+
outputTokens: row.output_tokens,
|
|
351
|
+
cacheReadTokens: row.cache_read_tokens,
|
|
352
|
+
cacheWriteTokens: row.cache_write_tokens,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
354
355
|
// A child token's models. One minted before `pins` existed kept its one model
|
|
355
356
|
// in `model` and `thinking`.
|
|
356
357
|
function childPins(row) {
|
|
@@ -174,10 +174,11 @@ export type LinkPlatform = {
|
|
|
174
174
|
}): Promise<boolean>;
|
|
175
175
|
};
|
|
176
176
|
/**
|
|
177
|
-
* What the gateway's approval and connections pages need. The
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
177
|
+
* What the gateway's approval and connections pages need. The gateway
|
|
178
|
+
* remembers the user in a signed cookie as a subject, so their plans are there
|
|
179
|
+
* the next time an app asks and they manage their connections there. With
|
|
180
|
+
* `signIn` the subject is the account they signed in with; without it the
|
|
181
|
+
* pages need no account, and a user's first plan makes their subject.
|
|
181
182
|
*/
|
|
182
183
|
export type LinkApprovalPage = {
|
|
183
184
|
/**
|
|
@@ -185,6 +186,11 @@ export type LinkApprovalPage = {
|
|
|
185
186
|
* `link_not_configured`) when the platform has none.
|
|
186
187
|
*/
|
|
187
188
|
sessionSecret(): string;
|
|
189
|
+
/**
|
|
190
|
+
* Set on a platform whose users have accounts: the page then acts only for
|
|
191
|
+
* a user who signed in with one, so their plans follow them to any browser.
|
|
192
|
+
*/
|
|
193
|
+
signIn?: LinkSignIn;
|
|
188
194
|
/** The kinds of plan a user can connect on the page, in the order offered. */
|
|
189
195
|
connectable: readonly SubscriptionKind[];
|
|
190
196
|
/** The providers and gateways a user can add an API key for, in the order offered. */
|
|
@@ -229,6 +235,21 @@ export type LinkApprovalPage = {
|
|
|
229
235
|
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
230
236
|
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
231
237
|
};
|
|
238
|
+
/**
|
|
239
|
+
* The platform's own sign-in. The page sends the user to `url()` with `state`
|
|
240
|
+
* and `next`; the platform signs them in and returns them to
|
|
241
|
+
* `/v1/link/session` with the same `next` and a ticket for that state.
|
|
242
|
+
*/
|
|
243
|
+
export type LinkSignIn = {
|
|
244
|
+
/** Throws HttpError(503, `link_not_configured`) when the platform has none. */
|
|
245
|
+
url(): string;
|
|
246
|
+
/** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
|
|
247
|
+
redeem(ticket: string): Promise<{
|
|
248
|
+
subject: string;
|
|
249
|
+
state: string;
|
|
250
|
+
issuedAt: number;
|
|
251
|
+
} | null>;
|
|
252
|
+
};
|
|
232
253
|
/** A plan or API key the user added, and who they are now. */
|
|
233
254
|
export type LinkPlanAdded = {
|
|
234
255
|
subject: string;
|
|
@@ -2,10 +2,10 @@ import { timingSafeEqual } from "node:crypto";
|
|
|
2
2
|
import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
|
|
3
3
|
import { HttpError } from "../http/errors.js";
|
|
4
4
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
5
|
-
import { codexModelConfig,
|
|
5
|
+
import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
6
6
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
7
7
|
import { gatewayFor } from "../models/gateways.js";
|
|
8
|
-
import {
|
|
8
|
+
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
9
9
|
import { registeredModelPrice } from "../providers/pi.js";
|
|
10
10
|
import { allRouterModels, routerModelsFor, } from "./config.js";
|
|
11
11
|
import { linkTokenGrant } from "../link/service.js";
|
|
@@ -87,9 +87,10 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
87
87
|
// A model-specific hold tries the pool's other plans before removing the
|
|
88
88
|
// model. Its provider's active plan and conversation pin stay unchanged.
|
|
89
89
|
const modelCredentials = {};
|
|
90
|
+
// A provider the request wanted that no granted plan served.
|
|
90
91
|
const linkUnavailable = grant === null
|
|
91
92
|
? {}
|
|
92
|
-
:
|
|
93
|
+
: providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider), request.clientHarness, now);
|
|
93
94
|
const models = [];
|
|
94
95
|
for (const model of listed) {
|
|
95
96
|
const credential = credentials.get(providerForModel(model.id));
|
|
@@ -120,11 +121,8 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
120
121
|
// A grant with a gateway key serves the gateway's models by name, listed or not.
|
|
121
122
|
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
122
123
|
if (models.length === 0 && !gatewayKeyed) {
|
|
123
|
-
if (grant !== null)
|
|
124
|
-
throw grant.pins
|
|
125
|
-
? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0].model)
|
|
126
|
-
: linkGrantUnavailableError(linkUnavailable);
|
|
127
|
-
}
|
|
124
|
+
if (grant !== null)
|
|
125
|
+
throw linkNothingServed(linkUnavailable, grant.pins);
|
|
128
126
|
const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
|
|
129
127
|
throw unavailableRouterError(request.routerId, exhausted, missing);
|
|
130
128
|
}
|
|
@@ -241,30 +239,6 @@ function grantModels(grant, routed, granted, grantedKeys) {
|
|
|
241
239
|
const pinned = new Set(grant.pins.map((pin) => pin.model));
|
|
242
240
|
return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
|
|
243
241
|
}
|
|
244
|
-
/**
|
|
245
|
-
* Why each provider with a granted plan serves nothing now: its plans serve
|
|
246
|
-
* only another client, or are all at their usage limits.
|
|
247
|
-
*/
|
|
248
|
-
function grantUnavailable(granted, credentials, clientHarness, now) {
|
|
249
|
-
const unavailable = {};
|
|
250
|
-
for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
|
|
251
|
-
// Only a provider the request wanted and no plan served.
|
|
252
|
-
if (credentials.get(provider) !== null)
|
|
253
|
-
continue;
|
|
254
|
-
const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
|
|
255
|
-
const usable = plans.filter((credential) => {
|
|
256
|
-
const client = subscriptionClient(credential.provider);
|
|
257
|
-
return client === undefined || client === clientHarness;
|
|
258
|
-
});
|
|
259
|
-
if (usable.length === 0) {
|
|
260
|
-
unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
|
|
261
|
-
continue;
|
|
262
|
-
}
|
|
263
|
-
const held = usable.flatMap((credential) => credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []);
|
|
264
|
-
unavailable[provider] = plansExhausted(usable.map((credential) => credential.provider), held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null);
|
|
265
|
-
}
|
|
266
|
-
return unavailable;
|
|
267
|
-
}
|
|
268
242
|
// Configured endpoints read their own key variable, or send a placeholder
|
|
269
243
|
// when they take none; known providers use their standard variable.
|
|
270
244
|
export async function configuredProviderApiKey(deps, provider) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.322",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.322",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
package/src/link/budget.ts
CHANGED
|
@@ -10,13 +10,21 @@
|
|
|
10
10
|
A window at its cap is back once enough of its oldest requests roll off to
|
|
11
11
|
bring it under the cap again: `resetsAt` is when that happens. */
|
|
12
12
|
|
|
13
|
-
import type { LinkBudget } from "../platform/platform.js";
|
|
13
|
+
import type { LinkBudget, LinkUsageTotals } from "../platform/platform.js";
|
|
14
14
|
|
|
15
15
|
/** The windows a budget can cap: five hours and one week. */
|
|
16
16
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080] as const;
|
|
17
17
|
|
|
18
|
+
/** The tokens a request used, as each kind is recorded. */
|
|
19
|
+
export type LinkTokenCounts = Pick<LinkUsageTotals, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens">;
|
|
20
|
+
|
|
21
|
+
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
22
|
+
export function linkTokens(counts: LinkTokenCounts): number {
|
|
23
|
+
return counts.inputTokens + counts.outputTokens + counts.cacheReadTokens + counts.cacheWriteTokens;
|
|
24
|
+
}
|
|
25
|
+
|
|
18
26
|
/** Tokens one of a grant's requests used, and when it was received. */
|
|
19
|
-
export type BudgetUse = { at: Date
|
|
27
|
+
export type BudgetUse = LinkTokenCounts & { at: Date };
|
|
20
28
|
|
|
21
29
|
/** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
|
|
22
30
|
export type BudgetStanding = { windowMinutes: number; maxTokens: number; usedTokens: number; resetsAt: Date | null };
|
|
@@ -28,12 +36,12 @@ export function budgetStandings(budget: readonly LinkBudget[], uses: readonly Bu
|
|
|
28
36
|
const live = uses
|
|
29
37
|
.filter((use) => use.at.getTime() > now.getTime() - windowMs)
|
|
30
38
|
.sort((a, b) => a.at.getTime() - b.at.getTime());
|
|
31
|
-
const usedTokens = live.reduce((sum, use) => sum + use
|
|
39
|
+
const usedTokens = live.reduce((sum, use) => sum + linkTokens(use), 0);
|
|
32
40
|
let resetsAt: Date | null = null;
|
|
33
41
|
let remaining = usedTokens;
|
|
34
42
|
for (const use of live) {
|
|
35
43
|
if (remaining < entry.maxTokens) break;
|
|
36
|
-
remaining -= use
|
|
44
|
+
remaining -= linkTokens(use);
|
|
37
45
|
resetsAt = new Date(use.at.getTime() + windowMs);
|
|
38
46
|
}
|
|
39
47
|
return { windowMinutes: entry.windowMinutes, maxTokens: entry.maxTokens, usedTokens, resetsAt };
|
package/src/link/endpoints.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
- PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
|
|
25
25
|
budget: the most tokens the app may use per
|
|
26
26
|
five hours and per week
|
|
27
|
+
- GET /v1/link/session where a platform's sign-in returns the user
|
|
27
28
|
- GET /v1/link/connections the page where the approval page's user sees
|
|
28
29
|
the apps they connected, sets each one's
|
|
29
30
|
budget, disconnects it, and removes plans
|
|
@@ -33,15 +34,16 @@
|
|
|
33
34
|
with HTTP Basic (`client_id:client_secret`); a public one sends `client_id`
|
|
34
35
|
in the body.
|
|
35
36
|
|
|
36
|
-
The
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
it, so another site cannot
|
|
37
|
+
The user picks a plan, signs in to its provider, and allows the app. The
|
|
38
|
+
gateway keeps who they are in a signed, HttpOnly, SameSite=Lax cookie
|
|
39
|
+
scoped to /v1/link/, so the next app that asks finds their plans connected
|
|
40
|
+
and the connections page knows them. On a platform with accounts (hosted:
|
|
41
|
+
Dari's own sign-in) they sign in first and are that account, with the plans
|
|
42
|
+
it already has; elsewhere their first plan makes them a user. Every change
|
|
43
|
+
needs that cookie and a form token derived from it, so another site cannot
|
|
44
|
+
make one. */
|
|
43
45
|
|
|
44
|
-
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
46
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
45
47
|
|
|
46
48
|
import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
47
49
|
|
|
@@ -61,6 +63,7 @@ import type {
|
|
|
61
63
|
LinkKeyProvider,
|
|
62
64
|
LinkUsageTotals,
|
|
63
65
|
LinkPlatform,
|
|
66
|
+
LinkSignIn,
|
|
64
67
|
LinkBudget,
|
|
65
68
|
LinkBudgetStanding,
|
|
66
69
|
LinkSubscription,
|
|
@@ -70,7 +73,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
70
73
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
71
74
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
72
75
|
import { gatewayFor } from "../models/gateways.js";
|
|
73
|
-
import { budgetBody, validBudget } from "./budget.js";
|
|
76
|
+
import { budgetBody, linkTokens, validBudget } from "./budget.js";
|
|
74
77
|
import { catalogModelFor } from "./grant_access.js";
|
|
75
78
|
import { requestTags } from "../runtime/request_tags.js";
|
|
76
79
|
import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
@@ -90,12 +93,21 @@ const MAX_REGISTRATIONS_PER_MINUTE = 20;
|
|
|
90
93
|
const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
|
|
91
94
|
const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
|
|
92
95
|
const MAX_TAG_KEY_CHARS = 64;
|
|
93
|
-
// Who the approval page's user is
|
|
96
|
+
// Who the approval page's user is. Without accounts the cookie is who they
|
|
97
|
+
// are, so it lasts a year from their last plan; with accounts, a month from
|
|
98
|
+
// their sign-in, which is a click away again.
|
|
94
99
|
const USER_COOKIE = "dari_link_user";
|
|
95
100
|
const USER_SECONDS = 365 * 24 * 60 * 60;
|
|
101
|
+
const ACCOUNT_SECONDS = 30 * 24 * 60 * 60;
|
|
96
102
|
// A provider sign-in under way, for as long as providers keep one open.
|
|
97
103
|
const CONNECT_COOKIE = "dari_link_connect";
|
|
98
104
|
const CONNECT_SECONDS = 15 * 60;
|
|
105
|
+
// A sign-in at the platform under way: the state its ticket must carry.
|
|
106
|
+
const SIGN_IN_COOKIE = "dari_link_sign_in";
|
|
107
|
+
const SIGN_IN_SECONDS = 15 * 60;
|
|
108
|
+
// How long after the platform signed the user in its ticket is good.
|
|
109
|
+
const TICKET_MS = 2 * 60 * 1000;
|
|
110
|
+
const SESSION_PATH = "/v1/link/session";
|
|
99
111
|
// How often the page asks a provider whether the user approved its code.
|
|
100
112
|
const DEVICE_POLL_SECONDS = 5;
|
|
101
113
|
const AUTHORIZE_PATH = "/v1/link/authorize";
|
|
@@ -169,6 +181,9 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
|
|
|
169
181
|
if (pathname === AUTHORIZE_PATH && request.method === "POST") {
|
|
170
182
|
return await authorizeSubmit(link, request, new URLSearchParams(await request.text()));
|
|
171
183
|
}
|
|
184
|
+
if (pathname === SESSION_PATH && request.method === "GET") {
|
|
185
|
+
return await signedIn(link.approval, request, url.searchParams);
|
|
186
|
+
}
|
|
172
187
|
if (pathname === CONNECTIONS_PATH && request.method === "GET") {
|
|
173
188
|
return await connectionsPage(link.approval, request);
|
|
174
189
|
}
|
|
@@ -315,14 +330,7 @@ function isHttps(request: Request): boolean {
|
|
|
315
330
|
|
|
316
331
|
async function registerApp(link: LinkPlatform, request: Request): Promise<Response> {
|
|
317
332
|
const apiKey = bearerToken(request.headers);
|
|
318
|
-
const
|
|
319
|
-
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
320
|
-
throw new HttpError(400, message, "invalid_request_error", param);
|
|
321
|
-
});
|
|
322
|
-
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
323
|
-
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
324
|
-
}
|
|
325
|
-
const app = await link.registerApp({ apiKey, name, redirectUris, confidential: body.confidential === true });
|
|
333
|
+
const app = await link.registerApp({ apiKey, ...linkAppMetadata(link, await parseJsonRequest(request)) });
|
|
326
334
|
return Response.json(
|
|
327
335
|
// The secret is shown this once; only its hash is stored.
|
|
328
336
|
{ ...appBody(app), ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret }) },
|
|
@@ -416,8 +424,25 @@ function registrationError(error: string, description: string): Response {
|
|
|
416
424
|
return Response.json({ error, error_description: description }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
|
417
425
|
}
|
|
418
426
|
|
|
427
|
+
/**
|
|
428
|
+
* An app's name, redirect URIs, and whether it is confidential, as every
|
|
429
|
+
* registration takes them; HttpError(400) for anything else.
|
|
430
|
+
*/
|
|
431
|
+
export function linkAppMetadata(
|
|
432
|
+
link: Pick<LinkPlatform, "httpRedirectHosts">,
|
|
433
|
+
body: { name?: unknown; redirect_uris?: unknown; confidential?: unknown },
|
|
434
|
+
): { name: string; redirectUris: string[]; confidential: boolean } {
|
|
435
|
+
const { name, redirectUris } = validClient(link, body.name, body.redirect_uris, (message, param) => {
|
|
436
|
+
throw new HttpError(400, message, "invalid_request_error", param);
|
|
437
|
+
});
|
|
438
|
+
if (body.confidential !== undefined && typeof body.confidential !== "boolean") {
|
|
439
|
+
throw new HttpError(400, "confidential must be a boolean.", "invalid_request_error", "confidential");
|
|
440
|
+
}
|
|
441
|
+
return { name, redirectUris, confidential: body.confidential === true };
|
|
442
|
+
}
|
|
443
|
+
|
|
419
444
|
function validClient(
|
|
420
|
-
link: LinkPlatform,
|
|
445
|
+
link: Pick<LinkPlatform, "httpRedirectHosts">,
|
|
421
446
|
rawName: unknown,
|
|
422
447
|
rawRedirectUris: unknown,
|
|
423
448
|
refuse: (message: string, param: string) => never,
|
|
@@ -1008,8 +1033,9 @@ async function authorizePage(link: LinkPlatform, request: Request, params: URLSe
|
|
|
1008
1033
|
if (authorize instanceof Response) return authorize;
|
|
1009
1034
|
const approval = link.approval;
|
|
1010
1035
|
const secret = approval.sessionSecret();
|
|
1011
|
-
const session = sessionFrom(request,
|
|
1012
|
-
|
|
1036
|
+
const session = sessionFrom(request, approval);
|
|
1037
|
+
// On a platform with accounts, only a signed-in user has a provider sign-in under way.
|
|
1038
|
+
const connect = session === null && approval.signIn !== undefined ? null : connectFrom(request, secret);
|
|
1013
1039
|
if (connect !== null) {
|
|
1014
1040
|
// A provider that gave the user a code to enter is asked whether they approved.
|
|
1015
1041
|
return connect.userCode === null
|
|
@@ -1058,7 +1084,10 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1058
1084
|
if (authorize instanceof Response) return authorize;
|
|
1059
1085
|
const back = { redirectUri: authorize.redirectUri, state: authorize.state, webMessage: authorize.webMessage };
|
|
1060
1086
|
const secret = approval.sessionSecret();
|
|
1061
|
-
const session = sessionFrom(request,
|
|
1087
|
+
const session = sessionFrom(request, approval);
|
|
1088
|
+
if (session === null && approval.signIn !== undefined && !["deny", "sign_out"].includes(form.get("decision") ?? "")) {
|
|
1089
|
+
return signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
|
|
1090
|
+
}
|
|
1062
1091
|
const endConnect = clearCookie(request, CONNECT_COOKIE);
|
|
1063
1092
|
// A plan's or a key provider's row on the select page is its own submit button.
|
|
1064
1093
|
const kind = form.get("connect");
|
|
@@ -1070,6 +1099,7 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1070
1099
|
}
|
|
1071
1100
|
const decision = kind !== null ? "connect" : form.get("decision");
|
|
1072
1101
|
if (decision === "deny") return redirect(back, { error: "access_denied" }, [endConnect]);
|
|
1102
|
+
if (decision === "sign_out") return seeAuthorize(authorize, signOutCookies(request));
|
|
1073
1103
|
if (decision === "select") return selectPage(approval, authorize, undefined, [endConnect]);
|
|
1074
1104
|
if (decision === "connect") {
|
|
1075
1105
|
if (!connectKinds(approval, authorize).includes(kind as SubscriptionKind)) {
|
|
@@ -1106,7 +1136,7 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1106
1136
|
if (!(error instanceof HttpError) || (error.status !== 400 && error.code !== "link_not_configured")) throw error;
|
|
1107
1137
|
return keyPage(authorize, keyProvider, error.message);
|
|
1108
1138
|
}
|
|
1109
|
-
return seeAuthorize(authorize, [userCookie(request,
|
|
1139
|
+
return seeAuthorize(authorize, [userCookie(request, approval, added.subject), endConnect]);
|
|
1110
1140
|
}
|
|
1111
1141
|
const connect = connectFrom(request, secret);
|
|
1112
1142
|
if (decision === "complete" && connect !== null) {
|
|
@@ -1178,7 +1208,7 @@ async function finishConnect(
|
|
|
1178
1208
|
}
|
|
1179
1209
|
return connected === null
|
|
1180
1210
|
? providerPage(authorize, connect)
|
|
1181
|
-
: seeAuthorize(authorize, [userCookie(request, approval
|
|
1211
|
+
: seeAuthorize(authorize, [userCookie(request, approval, connected.subject), endConnect]);
|
|
1182
1212
|
}
|
|
1183
1213
|
|
|
1184
1214
|
/**
|
|
@@ -1187,10 +1217,13 @@ async function finishConnect(
|
|
|
1187
1217
|
* and keys, each of which they can remove.
|
|
1188
1218
|
*/
|
|
1189
1219
|
async function connectionsPage(approval: LinkApprovalPage, request: Request, error?: string): Promise<Response> {
|
|
1190
|
-
const session = sessionFrom(request, approval
|
|
1220
|
+
const session = sessionFrom(request, approval);
|
|
1191
1221
|
const title = "Connected Apps";
|
|
1192
1222
|
if (session === null) {
|
|
1193
|
-
return
|
|
1223
|
+
return approval.signIn === undefined
|
|
1224
|
+
? page(title, `<div class="body"><h1>${title}</h1><p>No apps are connected in this browser. Apps that use Dari Link connect from their own Connect button.</p></div>`)
|
|
1225
|
+
: page(title, `<form method="post" action="${CONNECTIONS_PATH}"><div class="body"><h1>${title}</h1><p>Sign in to see the apps you connected.</p></div>
|
|
1226
|
+
<div class="foot"><button class="btn primary" type="submit" name="decision" value="sign_in">Sign In</button></div></form>`);
|
|
1194
1227
|
}
|
|
1195
1228
|
const [connections, plans] = await Promise.all([
|
|
1196
1229
|
approval.connections(session.subject),
|
|
@@ -1207,13 +1240,13 @@ async function connectionsPage(approval: LinkApprovalPage, request: Request, err
|
|
|
1207
1240
|
${error === undefined ? "" : `<p role="alert">${escapeHtml(error)}</p>`}
|
|
1208
1241
|
${cards.length === 0 ? "<p>No apps are connected.</p>" : cards.join("\n")}
|
|
1209
1242
|
${planRows.length === 0 ? "" : `<p class="label">Your Plans And Keys</p>\n${planRows.join("\n")}`}
|
|
1243
|
+
${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${SIGN_OUT}</form>` : ""}
|
|
1210
1244
|
</div>`,
|
|
1211
1245
|
);
|
|
1212
1246
|
}
|
|
1213
1247
|
|
|
1214
1248
|
function connectionCard(connection: LinkConnection, csrf: string): string {
|
|
1215
|
-
const tokens = connection.usage
|
|
1216
|
-
+ connection.usage.cacheReadTokens + connection.usage.cacheWriteTokens;
|
|
1249
|
+
const tokens = linkTokens(connection.usage);
|
|
1217
1250
|
const limit = (minutes: number, label: string) => {
|
|
1218
1251
|
const standing = connection.budget.find((window) => window.windowMinutes === minutes);
|
|
1219
1252
|
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
@@ -1235,10 +1268,19 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
|
|
|
1235
1268
|
if (crossSite(request)) {
|
|
1236
1269
|
return page("Request Refused", `<div class="body"><h1>Request Refused</h1><p>Open the connections page again.</p></div>`, { status: 403 });
|
|
1237
1270
|
}
|
|
1238
|
-
const
|
|
1271
|
+
const secret = approval.sessionSecret();
|
|
1272
|
+
const session = sessionFrom(request, approval);
|
|
1273
|
+
if (session === null && approval.signIn !== undefined && form.get("decision") === "sign_in") {
|
|
1274
|
+
return signIn(request, approval.signIn, secret, CONNECTIONS_PATH);
|
|
1275
|
+
}
|
|
1239
1276
|
const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
|
|
1240
1277
|
if (session === null || !sameText(form.get("csrf") ?? "", session.csrf)) return back;
|
|
1241
1278
|
const decision = form.get("decision");
|
|
1279
|
+
if (decision === "sign_out") {
|
|
1280
|
+
const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
|
|
1281
|
+
for (const cookie of signOutCookies(request)) headers.append("Set-Cookie", cookie);
|
|
1282
|
+
return new Response(null, { status: 303, headers });
|
|
1283
|
+
}
|
|
1242
1284
|
const grantId = form.get("grant_id") ?? "";
|
|
1243
1285
|
if (decision === "disconnect") {
|
|
1244
1286
|
await approval.disconnect(session.subject, grantId);
|
|
@@ -1321,12 +1363,18 @@ function shareable(authorize: AuthorizeRequest, subscriptions: LinkSubscription[
|
|
|
1321
1363
|
}
|
|
1322
1364
|
|
|
1323
1365
|
// The user the cookie remembers, and the form token that ties an approval to
|
|
1324
|
-
// them; another site has neither.
|
|
1325
|
-
|
|
1366
|
+
// them; another site has neither. `account`: they signed in to the platform's
|
|
1367
|
+
// account, so they can sign out (as on a shared computer).
|
|
1368
|
+
type Session = { subject: string; csrf: string; account: boolean };
|
|
1326
1369
|
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1370
|
+
const SIGN_OUT = `<button class="btn ghost" type="submit" name="decision" value="sign_out" formnovalidate>Sign Out</button>`;
|
|
1371
|
+
|
|
1372
|
+
function sessionFrom(request: Request, approval: LinkApprovalPage): Session | null {
|
|
1373
|
+
const secret = approval.sessionSecret();
|
|
1374
|
+
const user = readSigned(request, secret, USER_COOKIE);
|
|
1375
|
+
// A platform with accounts knows only users its sign-in made.
|
|
1376
|
+
if (typeof user?.sub !== "string" || (approval.signIn !== undefined && user.account !== true)) return null;
|
|
1377
|
+
return { subject: user.sub, csrf: sign(secret, `csrf\0${user.sub}`), account: approval.signIn !== undefined };
|
|
1330
1378
|
}
|
|
1331
1379
|
|
|
1332
1380
|
// A provider sign-in under way.
|
|
@@ -1348,6 +1396,39 @@ function connectFrom(request: Request, secret: string): Connect | null {
|
|
|
1348
1396
|
};
|
|
1349
1397
|
}
|
|
1350
1398
|
|
|
1399
|
+
// Send the user to the platform's sign-in, which returns them to `next` (a
|
|
1400
|
+
// page of this gateway's) by way of /v1/link/session. The state, kept in a
|
|
1401
|
+
// cookie here, binds the ticket that comes back to this browser, so no one
|
|
1402
|
+
// can sign a user in as someone else.
|
|
1403
|
+
function signIn(request: Request, platform: LinkSignIn, secret: string, next: string): Response {
|
|
1404
|
+
const state = randomBytes(24).toString("base64url");
|
|
1405
|
+
const url = new URL(platform.url());
|
|
1406
|
+
url.searchParams.set("state", state);
|
|
1407
|
+
url.searchParams.set("next", next);
|
|
1408
|
+
const headers = new Headers({ Location: url.toString(), "Cache-Control": "no-store" });
|
|
1409
|
+
headers.append("Set-Cookie", signedCookie(request, secret, SIGN_IN_COOKIE, { state }, SIGN_IN_SECONDS));
|
|
1410
|
+
return new Response(null, { status: 303, headers });
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
// The platform's sign-in returns here: a fresh ticket for this browser's state
|
|
1414
|
+
// makes the browser that user's, and the user goes on to `next`.
|
|
1415
|
+
async function signedIn(approval: LinkApprovalPage, request: Request, params: URLSearchParams): Promise<Response> {
|
|
1416
|
+
const secret = approval.sessionSecret();
|
|
1417
|
+
const state = readSigned(request, secret, SIGN_IN_COOKIE)?.state;
|
|
1418
|
+
const next = params.get("next") ?? "";
|
|
1419
|
+
const ticket = params.get("ticket") ?? "";
|
|
1420
|
+
const signed = approval.signIn === undefined || typeof state !== "string" || !ticket || !next.startsWith(LINK_ROUTE_PREFIX)
|
|
1421
|
+
? null
|
|
1422
|
+
: await approval.signIn.redeem(ticket);
|
|
1423
|
+
if (signed === null || signed.state !== state || Date.now() - signed.issuedAt > TICKET_MS) {
|
|
1424
|
+
return page("Sign-In Expired", `<div class="body"><h1>Sign-In Expired</h1><p>Open Dari Link from the app again.</p></div>`, { status: 400 });
|
|
1425
|
+
}
|
|
1426
|
+
const headers = new Headers({ Location: next, "Cache-Control": "no-store" });
|
|
1427
|
+
headers.append("Set-Cookie", userCookie(request, approval, signed.subject));
|
|
1428
|
+
headers.append("Set-Cookie", clearCookie(request, SIGN_IN_COOKIE));
|
|
1429
|
+
return new Response(null, { status: 303, headers });
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1351
1432
|
// A signed cookie's payload: `<payload>.<HMAC-SHA256>`, where the payload
|
|
1352
1433
|
// holds the value and when it ends.
|
|
1353
1434
|
function readSigned(request: Request, secret: string, cookie: string): Record<string, unknown> | null {
|
|
@@ -1377,9 +1458,16 @@ function signedCookie(request: Request, secret: string, cookie: string, value: R
|
|
|
1377
1458
|
return `${cookie}=${signedValue(secret, cookie, value, seconds)}; Path=${COOKIE_PATH}; Max-Age=${seconds}; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
|
|
1378
1459
|
}
|
|
1379
1460
|
|
|
1380
|
-
// Who the user is,
|
|
1381
|
-
function userCookie(request: Request,
|
|
1382
|
-
return
|
|
1461
|
+
// Who the user is, from when the page last said so (see USER_COOKIE).
|
|
1462
|
+
function userCookie(request: Request, approval: LinkApprovalPage, subject: string): string {
|
|
1463
|
+
return approval.signIn === undefined
|
|
1464
|
+
? signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject }, USER_SECONDS)
|
|
1465
|
+
: signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
|
|
1469
|
+
function signOutCookies(request: Request): string[] {
|
|
1470
|
+
return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
|
|
1383
1471
|
}
|
|
1384
1472
|
|
|
1385
1473
|
function clearCookie(request: Request, cookie: string): string {
|
|
@@ -1583,7 +1671,8 @@ function choosePage(
|
|
|
1583
1671
|
body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
|
|
1584
1672
|
<input type="hidden" name="csrf" value="${session.csrf}">
|
|
1585
1673
|
${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
|
|
1586
|
-
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button
|
|
1674
|
+
<button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
|
|
1675
|
+
${session.account ? SIGN_OUT : ""}`,
|
|
1587
1676
|
footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
|
|
1588
1677
|
<p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
|
|
1589
1678
|
});
|
|
@@ -1722,7 +1811,9 @@ ${body}
|
|
|
1722
1811
|
"Cache-Control": "no-store",
|
|
1723
1812
|
"Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
|
|
1724
1813
|
"X-Frame-Options": "DENY",
|
|
1725
|
-
|
|
1814
|
+
// No other site sees these pages' URLs. Not no-referrer: under it a form
|
|
1815
|
+
// posts Origin: null, which an http gateway (sent no Sec-Fetch-Site) refuses.
|
|
1816
|
+
"Referrer-Policy": "same-origin",
|
|
1726
1817
|
});
|
|
1727
1818
|
for (const cookie of options.cookies ?? []) headers.append("Set-Cookie", cookie);
|
|
1728
1819
|
return new Response(html, { status: options.status ?? 200, headers });
|
package/src/link/errors.ts
CHANGED
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
25
25
|
|
|
26
26
|
import { HttpError } from "../http/errors.js";
|
|
27
|
-
import
|
|
27
|
+
import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
28
|
+
import type { ClientHarness, LinkUnavailable, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
28
29
|
|
|
29
30
|
export const LINK_GRANT_ERROR_CODES = [
|
|
30
31
|
"subscription_exhausted",
|
|
@@ -100,6 +101,57 @@ export function plansForAnotherClient(plans: readonly SubscriptionKind[]): LinkU
|
|
|
100
101
|
};
|
|
101
102
|
}
|
|
102
103
|
|
|
104
|
+
/** A granted subscription, as a platform's resolve found it. */
|
|
105
|
+
export type LinkGrantedPlan = { kind: SubscriptionKind; unavailableUntil: Date | null };
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Why a grant serves nothing for each provider in `unserved` (the request
|
|
109
|
+
* wanted it, the grant holds a plan for it, and no plan served): its plans
|
|
110
|
+
* serve only another client, or are all at their usage limits. Every
|
|
111
|
+
* platform's resolve says it this way.
|
|
112
|
+
*/
|
|
113
|
+
export function providersUnavailable(
|
|
114
|
+
granted: readonly LinkGrantedPlan[],
|
|
115
|
+
unserved: Iterable<string>,
|
|
116
|
+
clientHarness: ClientHarness | undefined,
|
|
117
|
+
now: Date,
|
|
118
|
+
): Record<string, LinkUnavailable> {
|
|
119
|
+
const unavailable: Record<string, LinkUnavailable> = {};
|
|
120
|
+
for (const provider of unserved) {
|
|
121
|
+
const plans = granted.filter((plan) => subscriptionModelProvider(plan.kind) === provider);
|
|
122
|
+
if (plans.length === 0) continue;
|
|
123
|
+
const usable = plans.filter((plan) => {
|
|
124
|
+
const client = subscriptionClient(plan.kind);
|
|
125
|
+
return client === undefined || client === clientHarness;
|
|
126
|
+
});
|
|
127
|
+
if (usable.length === 0) {
|
|
128
|
+
unavailable[provider] = plansForAnotherClient(plans.map((plan) => plan.kind));
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const held = usable.flatMap((plan) =>
|
|
132
|
+
plan.unavailableUntil !== null && plan.unavailableUntil > now ? [plan.unavailableUntil] : []
|
|
133
|
+
);
|
|
134
|
+
unavailable[provider] = plansExhausted(
|
|
135
|
+
usable.map((plan) => plan.kind),
|
|
136
|
+
held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return unavailable;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The error a grant that serves the request nothing gets: why its one pinned
|
|
144
|
+
* model is not served, or why none is.
|
|
145
|
+
*/
|
|
146
|
+
export function linkNothingServed(
|
|
147
|
+
unavailable: Record<string, LinkUnavailable>,
|
|
148
|
+
pins: readonly { model: string }[] | null | undefined,
|
|
149
|
+
): HttpError {
|
|
150
|
+
return pins?.length === 1
|
|
151
|
+
? modelNotServed({ link_unavailable: unavailable }, pins[0]!.model)
|
|
152
|
+
: linkGrantUnavailableError(unavailable);
|
|
153
|
+
}
|
|
154
|
+
|
|
103
155
|
/**
|
|
104
156
|
* Why a grant serves nothing at all: its plans are at their limits, serve
|
|
105
157
|
* only another client, or serve no model.
|