@mupt-ai/dari-gateway 1.0.312 → 1.0.314
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +276 -2
- package/dist/context/routing_context.js +4 -1
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +12 -2
- package/dist/ingress/anthropic_messages.js +15 -3
- package/dist/ingress/chat_completions.js +6 -1
- package/dist/ingress/codex.js +2 -2
- package/dist/ingress/models.js +46 -2
- package/dist/interaction/types.d.ts +1 -0
- package/dist/link/assets.d.ts +14 -0
- package/dist/link/assets.js +49 -0
- package/dist/link/budget.d.ts +27 -0
- package/dist/link/budget.js +62 -0
- package/dist/link/client.d.ts +382 -0
- package/dist/link/client.js +578 -0
- package/dist/link/endpoints.d.ts +23 -0
- package/dist/link/endpoints.js +1615 -0
- package/dist/link/errors.d.ts +30 -0
- package/dist/link/errors.js +120 -0
- package/dist/link/font.d.ts +1 -0
- package/dist/link/font.js +6 -0
- package/dist/link/grant_access.d.ts +7 -0
- package/dist/link/grant_access.js +99 -0
- package/dist/link/grants.d.ts +151 -0
- package/dist/link/grants.js +275 -0
- package/dist/link/in_flight.d.ts +4 -0
- package/dist/link/in_flight.js +43 -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/models/gateways.d.ts +2 -0
- package/dist/models/gateways.js +2 -0
- package/dist/models/subscriptions.d.ts +8 -1
- package/dist/models/subscriptions.js +13 -2
- package/dist/platform/platform.d.ts +298 -1
- package/dist/protocol/input/router_model.d.ts +4 -0
- package/dist/protocol/input/router_model.js +31 -1
- package/dist/providers/execution.js +24 -2
- package/dist/providers/pi_options.js +57 -1
- package/dist/providers/provider_call.d.ts +4 -0
- package/dist/providers/provider_call.js +4 -1
- package/dist/providers/stream_finalization.d.ts +1 -0
- package/dist/runtime/explicit_model.js +16 -4
- package/dist/runtime/harness_identity/extract.js +20 -36
- package/dist/runtime/prepare_routed_completion.js +5 -1
- package/dist/runtime/routed_runtime.js +8 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/config.d.ts +9 -0
- package/dist/self_host/config.js +11 -1
- package/dist/self_host/main.d.ts +10 -3
- package/dist/self_host/main.js +19 -4
- package/dist/self_host/platform.d.ts +2 -2
- package/dist/self_host/platform.js +36 -7
- package/dist/self_host/resolve.d.ts +8 -0
- package/dist/self_host/resolve.js +130 -15
- package/dist/self_host/secret_box.d.ts +23 -0
- package/dist/self_host/secret_box.js +105 -0
- package/dist/self_host/stub_gateway.d.ts +60 -0
- package/dist/self_host/stub_gateway.js +397 -0
- package/dist/self_host/stub_main.d.ts +2 -0
- package/dist/self_host/stub_main.js +69 -0
- package/dist/self_host/subscription_test_gateway.d.ts +12 -9
- package/dist/self_host/subscription_test_gateway.js +25 -91
- package/dist/self_host/subscriptions/http.js +3 -2
- package/dist/self_host/subscriptions/index.d.ts +2 -2
- package/dist/self_host/subscriptions/index.js +2 -2
- package/dist/self_host/subscriptions/store.d.ts +41 -16
- package/dist/self_host/subscriptions/store.js +136 -32
- package/dist/telemetry/report.js +18 -0
- package/dist/types.d.ts +18 -0
- package/package.json +4 -3
- package/src/context/routing_context.ts +3 -1
- package/src/http/handler.ts +14 -2
- package/src/ingress/anthropic_messages.ts +19 -4
- package/src/ingress/chat_completions.ts +6 -1
- package/src/ingress/codex.ts +2 -2
- package/src/ingress/models.ts +48 -2
- package/src/interaction/types.ts +4 -0
- package/src/link/assets.ts +56 -0
- package/src/link/budget.ts +75 -0
- package/src/link/client.ts +793 -0
- package/src/link/endpoints.ts +1834 -0
- package/src/link/errors.ts +157 -0
- package/src/link/font.ts +9 -0
- package/src/link/grant_access.ts +116 -0
- package/src/link/grants.ts +436 -0
- package/src/link/in_flight.ts +46 -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/models/gateways.ts +3 -0
- package/src/models/subscriptions.ts +15 -1
- package/src/platform/platform.ts +324 -1
- package/src/protocol/input/router_model.ts +36 -1
- package/src/providers/execution.ts +24 -2
- package/src/providers/pi_options.ts +57 -1
- package/src/providers/provider_call.ts +15 -1
- package/src/providers/stream_finalization.ts +1 -0
- package/src/runtime/explicit_model.ts +21 -8
- package/src/runtime/harness_identity/extract.ts +21 -60
- package/src/runtime/prepare_routed_completion.ts +6 -1
- package/src/runtime/routed_runtime.ts +8 -0
- package/src/runtime/runtime_reporter.ts +3 -0
- package/src/self_host/config.ts +24 -1
- package/src/self_host/main.ts +21 -4
- package/src/self_host/platform.ts +40 -8
- package/src/self_host/resolve.ts +157 -15
- package/src/self_host/secret_box.ts +112 -0
- package/src/self_host/stub_gateway.ts +497 -0
- package/src/self_host/stub_main.ts +72 -0
- package/src/self_host/subscription_test_gateway.ts +26 -95
- package/src/self_host/subscriptions/http.ts +3 -2
- package/src/self_host/subscriptions/index.ts +3 -0
- package/src/self_host/subscriptions/store.ts +167 -36
- package/src/telemetry/report.ts +17 -1
- package/src/types.ts +26 -0
- package/dist/self_host/subscriptions/test_support.d.ts +0 -15
- package/dist/self_host/subscriptions/test_support.js +0 -34
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkPlanAdded, LinkPlatform, LinkSubscription } from "../platform/platform.js";
|
|
2
|
+
import type { SubscriptionKind } from "../types.js";
|
|
3
|
+
import { type BudgetUse } from "./budget.js";
|
|
4
|
+
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo } from "./grants.js";
|
|
5
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
6
|
+
/** A live grant as stored. */
|
|
7
|
+
export type LinkGrantRecord = {
|
|
8
|
+
id: string;
|
|
9
|
+
clientId: string;
|
|
10
|
+
appName: string;
|
|
11
|
+
subject: string | null;
|
|
12
|
+
credentialIds: string[];
|
|
13
|
+
createdAt: string;
|
|
14
|
+
budget: LinkBudget[];
|
|
15
|
+
};
|
|
16
|
+
/** Storage for Dari Link: the token protocol's steps, and grants. */
|
|
17
|
+
export type LinkStore = LinkRepo & {
|
|
18
|
+
/** Live grants of one user, or of everyone (null), oldest first. */
|
|
19
|
+
grants(subject: string | null): MaybePromise<LinkGrantRecord[]>;
|
|
20
|
+
/** A live grant; null when none is live by that id. */
|
|
21
|
+
grant(grantId: string): MaybePromise<LinkGrantRecord | null>;
|
|
22
|
+
/**
|
|
23
|
+
* Store a grant awaiting its code exchange, and return its id. With
|
|
24
|
+
* `grantId`, give that live grant of this user and app new plans, budget,
|
|
25
|
+
* and code instead; null when there is none.
|
|
26
|
+
*/
|
|
27
|
+
saveGrant(request: {
|
|
28
|
+
grantId?: string;
|
|
29
|
+
subject: string;
|
|
30
|
+
clientId: string;
|
|
31
|
+
redirectUri: string;
|
|
32
|
+
codeHash: string;
|
|
33
|
+
codeChallenge: string;
|
|
34
|
+
codeExpiresAt: number;
|
|
35
|
+
credentialIds: string[];
|
|
36
|
+
budget: LinkBudget[];
|
|
37
|
+
now: number;
|
|
38
|
+
}): MaybePromise<string | null>;
|
|
39
|
+
/** Change a live grant's plans or budget; false when none is live by that id. */
|
|
40
|
+
updateGrant(grantId: string, change: {
|
|
41
|
+
credentialIds?: string[];
|
|
42
|
+
budget?: LinkBudget[];
|
|
43
|
+
}): MaybePromise<boolean>;
|
|
44
|
+
/** The tokens each of a grant's requests received after `since` used. */
|
|
45
|
+
budgetUses(grantId: string, since: number): MaybePromise<BudgetUse[]>;
|
|
46
|
+
};
|
|
47
|
+
/** A platform's users: who a key is, and where their plans and keys live. */
|
|
48
|
+
export type LinkUsers = {
|
|
49
|
+
/** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
|
|
50
|
+
sessionSecret(): string;
|
|
51
|
+
connectable: readonly SubscriptionKind[];
|
|
52
|
+
keyProviders: readonly LinkKeyProvider[];
|
|
53
|
+
/** See `LinkPlatform.httpRedirectHosts`. */
|
|
54
|
+
httpRedirectHosts?: readonly string[];
|
|
55
|
+
/**
|
|
56
|
+
* Store a registered app; with `apiKey`, owned by whoever that key is.
|
|
57
|
+
* Throws HttpError(401 or 403) for a key that may not register apps.
|
|
58
|
+
*/
|
|
59
|
+
registerApp(app: LinkAppRecord, apiKey: string | undefined): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Whose grants a management key manages: one user, or everyone (null).
|
|
62
|
+
* Throws HttpError(401 or 403) for a key that manages none.
|
|
63
|
+
*/
|
|
64
|
+
manager(apiKey: string): Promise<string | null>;
|
|
65
|
+
/** When a grant's usage is complete through; null when the platform cannot tell. */
|
|
66
|
+
completeThrough(grantId: string): string | null;
|
|
67
|
+
/** A user's plans and API keys, oldest first. */
|
|
68
|
+
plans(subject: string): Promise<LinkSubscription[]>;
|
|
69
|
+
/** The plans and API keys with these ids, whoever added them. */
|
|
70
|
+
plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
|
|
71
|
+
/** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
|
|
72
|
+
addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
|
|
73
|
+
startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
|
|
74
|
+
completeConnect(subject: string | null, session: string, authorizationResponse: string): Promise<LinkPlanAdded | null>;
|
|
75
|
+
/** Delete one of the user's plans or keys; false when they have none by that id. */
|
|
76
|
+
removePlan(subject: string, credentialId: string): Promise<boolean>;
|
|
77
|
+
};
|
|
78
|
+
export declare function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform;
|
|
79
|
+
/**
|
|
80
|
+
* The grant a link token serves a request for: null when the key is no link
|
|
81
|
+
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|
|
82
|
+
* gets until its window rolls on.
|
|
83
|
+
*/
|
|
84
|
+
export declare function linkTokenGrant(store: LinkStore, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/* Dari Link's rules, once, for every platform. A platform supplies its
|
|
2
|
+
storage (`LinkStore`: the self-hosted gateway's SQLite database, hosted
|
|
3
|
+
Dari's control plane) and its users (`LinkUsers`: who a key or a page
|
|
4
|
+
visitor is, and where their plans and API keys live); `linkPlatform` makes
|
|
5
|
+
the rest: approving grants, managing them, budgets, and the token protocol
|
|
6
|
+
(grants.ts). */
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { HttpError } from "../http/errors.js";
|
|
9
|
+
import { budgetLookbackMs, budgetStandings, overBudgetUntil } from "./budget.js";
|
|
10
|
+
import { budgetExhausted, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
11
|
+
import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, } from "./grants.js";
|
|
12
|
+
export function linkPlatform(store, users) {
|
|
13
|
+
const protocol = linkGrants(store);
|
|
14
|
+
const standings = async (grant, now = new Date()) => (await linkBudgetStandings(store, grant, now)).map((standing) => ({
|
|
15
|
+
...standing,
|
|
16
|
+
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
17
|
+
}));
|
|
18
|
+
// A live grant of this user's; null for anyone else's.
|
|
19
|
+
const ownGrant = async (subject, grantId) => {
|
|
20
|
+
const grant = await store.grant(grantId);
|
|
21
|
+
return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
|
|
22
|
+
};
|
|
23
|
+
const revoke = (grantId) => store.revokeGrant(grantId, "user", Date.now());
|
|
24
|
+
return {
|
|
25
|
+
httpRedirectHosts: users.httpRedirectHosts ?? [],
|
|
26
|
+
approval: {
|
|
27
|
+
sessionSecret: () => users.sessionSecret(),
|
|
28
|
+
connectable: users.connectable,
|
|
29
|
+
keyProviders: users.keyProviders,
|
|
30
|
+
subscriptions: (subject) => users.plans(subject),
|
|
31
|
+
async addKey(subject, provider, apiKey) {
|
|
32
|
+
if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
|
|
33
|
+
throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
|
|
34
|
+
}
|
|
35
|
+
return await users.addKey(subject, provider, apiKey);
|
|
36
|
+
},
|
|
37
|
+
startConnect: (kind) => users.startConnect(kind),
|
|
38
|
+
completeConnect: (subject, session, response) => users.completeConnect(subject, session, response),
|
|
39
|
+
async remove(subject, credentialId) {
|
|
40
|
+
if (!(await users.plans(subject)).some((plan) => plan.id === credentialId))
|
|
41
|
+
return false;
|
|
42
|
+
// Every app loses it first, and a grant left with nothing ends, so a
|
|
43
|
+
// failure part way never leaves a grant on a deleted plan.
|
|
44
|
+
for (const grant of await store.grants(subject)) {
|
|
45
|
+
if (!grant.credentialIds.includes(credentialId))
|
|
46
|
+
continue;
|
|
47
|
+
const left = grant.credentialIds.filter((id) => id !== credentialId);
|
|
48
|
+
if (left.length === 0)
|
|
49
|
+
await revoke(grant.id);
|
|
50
|
+
else
|
|
51
|
+
await store.updateGrant(grant.id, { credentialIds: left });
|
|
52
|
+
}
|
|
53
|
+
return await users.removePlan(subject, credentialId);
|
|
54
|
+
},
|
|
55
|
+
async grant(subject, grantId, clientId) {
|
|
56
|
+
const grant = await ownGrant(subject, grantId);
|
|
57
|
+
return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget };
|
|
58
|
+
},
|
|
59
|
+
async approve(request) {
|
|
60
|
+
const owned = new Set((await users.plans(request.subject)).map((plan) => plan.id));
|
|
61
|
+
if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => owned.has(id))) {
|
|
62
|
+
throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
|
|
63
|
+
}
|
|
64
|
+
const app = await store.appRecord(request.clientId);
|
|
65
|
+
if (app === null || !app.redirectUris.includes(request.redirectUri)) {
|
|
66
|
+
throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
|
|
67
|
+
}
|
|
68
|
+
const code = linkSecret(LINK_CODE_PREFIX);
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const grantId = await store.saveGrant({
|
|
71
|
+
...(request.grantId === undefined ? {} : { grantId: request.grantId }),
|
|
72
|
+
subject: request.subject,
|
|
73
|
+
clientId: request.clientId,
|
|
74
|
+
redirectUri: request.redirectUri,
|
|
75
|
+
codeHash: linkHash(code),
|
|
76
|
+
codeChallenge: request.codeChallenge,
|
|
77
|
+
codeExpiresAt: now + LINK_CODE_TTL_MS,
|
|
78
|
+
credentialIds: [...new Set(request.credentialIds)].sort(),
|
|
79
|
+
budget: request.budget,
|
|
80
|
+
now,
|
|
81
|
+
});
|
|
82
|
+
if (grantId === null)
|
|
83
|
+
throw new HttpError(400, "That connection no longer exists.", "invalid_request");
|
|
84
|
+
return { code };
|
|
85
|
+
},
|
|
86
|
+
async connections(subject) {
|
|
87
|
+
return await Promise.all((await store.grants(subject)).map(async (grant) => {
|
|
88
|
+
const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
|
|
89
|
+
return {
|
|
90
|
+
id: grant.id,
|
|
91
|
+
clientId: grant.clientId,
|
|
92
|
+
appName: grant.appName,
|
|
93
|
+
createdAt: grant.createdAt,
|
|
94
|
+
budget: await standings(grant),
|
|
95
|
+
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
96
|
+
usage,
|
|
97
|
+
};
|
|
98
|
+
}));
|
|
99
|
+
},
|
|
100
|
+
async disconnect(subject, grantId) {
|
|
101
|
+
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
102
|
+
},
|
|
103
|
+
async setBudget(subject, grantId, budget) {
|
|
104
|
+
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
async registerApp({ apiKey, name, redirectUris, confidential }) {
|
|
108
|
+
const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
|
|
109
|
+
const app = {
|
|
110
|
+
clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
|
|
111
|
+
name,
|
|
112
|
+
redirectUris,
|
|
113
|
+
confidential: clientSecret !== undefined,
|
|
114
|
+
};
|
|
115
|
+
await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
|
|
116
|
+
return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
|
|
117
|
+
},
|
|
118
|
+
async app(clientId) {
|
|
119
|
+
const record = await store.appRecord(clientId);
|
|
120
|
+
if (record === null)
|
|
121
|
+
return null;
|
|
122
|
+
const { clientSecretHash: _, ...app } = record;
|
|
123
|
+
return app;
|
|
124
|
+
},
|
|
125
|
+
exchangeCode: (request) => protocol.exchangeCode(request),
|
|
126
|
+
refresh: (request) => protocol.refresh(request),
|
|
127
|
+
exchangeToken: (request) => protocol.exchangeToken(request),
|
|
128
|
+
revokeToken: (request) => protocol.revokeToken(request),
|
|
129
|
+
async grant(accessToken) {
|
|
130
|
+
const { id } = await protocol.parentGrant(accessToken);
|
|
131
|
+
const grant = await store.grant(id);
|
|
132
|
+
// Revoked since the token was read.
|
|
133
|
+
if (grant === null)
|
|
134
|
+
throw linkGrantRevoked(null, null);
|
|
135
|
+
return {
|
|
136
|
+
id: grant.id,
|
|
137
|
+
clientId: grant.clientId,
|
|
138
|
+
appName: grant.appName,
|
|
139
|
+
createdAt: grant.createdAt,
|
|
140
|
+
budget: await standings(grant),
|
|
141
|
+
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
async usage({ accessToken, ...query }) {
|
|
145
|
+
const { id } = await protocol.parentGrant(accessToken);
|
|
146
|
+
// Read before the rows, so a request recorded in between is counted.
|
|
147
|
+
const completeThrough = users.completeThrough(id);
|
|
148
|
+
return { ...(await protocol.usage(id, query)), completeThrough };
|
|
149
|
+
},
|
|
150
|
+
async grants(apiKey) {
|
|
151
|
+
const subject = await users.manager(apiKey);
|
|
152
|
+
return (await store.grants(subject)).map(({ subject: _, ...grant }) => grant);
|
|
153
|
+
},
|
|
154
|
+
async setBudget({ apiKey, grantId, budget }) {
|
|
155
|
+
const subject = await users.manager(apiKey);
|
|
156
|
+
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
157
|
+
},
|
|
158
|
+
async revokeGrant({ apiKey, grantId }) {
|
|
159
|
+
const subject = await users.manager(apiKey);
|
|
160
|
+
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The grant a link token serves a request for: null when the key is no link
|
|
166
|
+
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|
|
167
|
+
* gets until its window rolls on.
|
|
168
|
+
*/
|
|
169
|
+
export async function linkTokenGrant(store, token, now = new Date()) {
|
|
170
|
+
const auth = await linkGrants(store).authenticate(token, now);
|
|
171
|
+
if (auth === null)
|
|
172
|
+
return null;
|
|
173
|
+
if (auth.status === "expired")
|
|
174
|
+
throw linkTokenExpired();
|
|
175
|
+
if (auth.status === "revoked")
|
|
176
|
+
throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
|
|
177
|
+
const back = overBudgetUntil(await linkBudgetStandings(store, auth.grant, now));
|
|
178
|
+
if (back !== undefined)
|
|
179
|
+
throw linkUnavailableError(budgetExhausted(back));
|
|
180
|
+
return auth.grant;
|
|
181
|
+
}
|
|
182
|
+
async function linkBudgetStandings(store, grant, now) {
|
|
183
|
+
if (grant.budget.length === 0)
|
|
184
|
+
return [];
|
|
185
|
+
const uses = await store.budgetUses(grant.id, now.getTime() - budgetLookbackMs(grant.budget));
|
|
186
|
+
return budgetStandings(grant.budget, uses, now);
|
|
187
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The self-hosted gateway's Dari Link storage, in SQLite: registered apps, the
|
|
3
|
+
* grants users approve for them, each grant's tokens and usage, and the API
|
|
4
|
+
* keys users add. A grant names the subscriptions it may use. The rules over
|
|
5
|
+
* these tables are link/service.ts and link/grants.ts.
|
|
6
|
+
*/
|
|
7
|
+
import type { Database } from "bun:sqlite";
|
|
8
|
+
import { type SecretBox } from "../self_host/secret_box.js";
|
|
9
|
+
import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
|
|
10
|
+
import type { BudgetUse } from "./budget.js";
|
|
11
|
+
import { type LinkAppRecord, type LinkRevoker, type LinkTokenIssue, type LinkTokenRecord, type LinkUsageRecord } from "./grants.js";
|
|
12
|
+
import type { LinkGrantRecord, LinkStore } from "./service.js";
|
|
13
|
+
/** An API key a user added on the approval page, for one model provider or gateway. */
|
|
14
|
+
export type LinkApiKey = {
|
|
15
|
+
id: string;
|
|
16
|
+
subject: string;
|
|
17
|
+
provider: string;
|
|
18
|
+
apiKey: string;
|
|
19
|
+
};
|
|
20
|
+
export declare class SqliteLinkStore implements LinkStore {
|
|
21
|
+
private readonly db;
|
|
22
|
+
private readonly box;
|
|
23
|
+
constructor(db: Database, box?: SecretBox | null);
|
|
24
|
+
private encryptStored;
|
|
25
|
+
private seal;
|
|
26
|
+
private key;
|
|
27
|
+
/** Store a user's API key for a provider, replacing their earlier one for it. */
|
|
28
|
+
addKey(subject: string, provider: string, apiKey: string, now?: Date): LinkApiKey;
|
|
29
|
+
/** Delete a user's API key; false when they have none by that id. */
|
|
30
|
+
removeKey(subject: string, id: string): boolean;
|
|
31
|
+
/** The API keys a user added, oldest first. */
|
|
32
|
+
keys(subject: string): LinkApiKey[];
|
|
33
|
+
/** The API keys with these ids, whoever added them. */
|
|
34
|
+
keysWithIds(ids: ReadonlySet<string>): LinkApiKey[];
|
|
35
|
+
budgetUses(grantId: string, since: number): BudgetUse[];
|
|
36
|
+
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
37
|
+
recordUsage(entry: LinkUsageEntry): void;
|
|
38
|
+
usageRecords(grantId: string, query: Pick<LinkUsageQuery, "since" | "until" | "requestId">): LinkUsageRecord[];
|
|
39
|
+
addApp(app: LinkAppRecord, now?: Date): void;
|
|
40
|
+
appRecord(clientId: string): LinkAppRecord | null;
|
|
41
|
+
saveGrant(request: Parameters<LinkStore["saveGrant"]>[0]): string | null;
|
|
42
|
+
updateGrant(grantId: string, change: {
|
|
43
|
+
credentialIds?: string[];
|
|
44
|
+
budget?: LinkBudget[];
|
|
45
|
+
}): boolean;
|
|
46
|
+
grants(subject: string | null): LinkGrantRecord[];
|
|
47
|
+
grant(grantId: string): LinkGrantRecord | null;
|
|
48
|
+
redeemCode(request: Parameters<LinkStore["redeemCode"]>[0]): string | null;
|
|
49
|
+
tokenRecord(tokenHash: string): LinkTokenRecord | null;
|
|
50
|
+
issueTokens(request: {
|
|
51
|
+
grantId: string;
|
|
52
|
+
tokens: LinkTokenIssue[];
|
|
53
|
+
rotate?: string;
|
|
54
|
+
now: number;
|
|
55
|
+
}): "ok" | "race" | "revoked";
|
|
56
|
+
private insertTokens;
|
|
57
|
+
deleteToken(tokenHash: string): void;
|
|
58
|
+
/** The subscriptions a grant may use; empty once it is revoked. */
|
|
59
|
+
credentialIds(grantId: string): ReadonlySet<string>;
|
|
60
|
+
revokeGrant(grantId: string, by: LinkRevoker, now?: number): boolean;
|
|
61
|
+
}
|
|
62
|
+
export type LinkUsageEntry = {
|
|
63
|
+
requestId: string;
|
|
64
|
+
grantId: string;
|
|
65
|
+
receivedAt: Date;
|
|
66
|
+
model: string | null;
|
|
67
|
+
thinking: string | null;
|
|
68
|
+
tags: Record<string, string>;
|
|
69
|
+
inputTokens: number;
|
|
70
|
+
outputTokens: number;
|
|
71
|
+
cacheReadTokens: number;
|
|
72
|
+
cacheWriteTokens: number;
|
|
73
|
+
status: string;
|
|
74
|
+
};
|