@mupt-ai/dari-gateway 1.0.312 → 1.0.313

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +279 -2
  2. package/dist/context/routing_context.js +4 -1
  3. package/dist/http/handler.d.ts +2 -1
  4. package/dist/http/handler.js +12 -2
  5. package/dist/ingress/anthropic_messages.js +15 -3
  6. package/dist/ingress/chat_completions.js +6 -1
  7. package/dist/ingress/codex.js +2 -2
  8. package/dist/ingress/link.d.ts +24 -0
  9. package/dist/ingress/link.js +1519 -0
  10. package/dist/ingress/link_assets.d.ts +14 -0
  11. package/dist/ingress/link_assets.js +49 -0
  12. package/dist/ingress/link_font.d.ts +1 -0
  13. package/dist/ingress/link_font.js +6 -0
  14. package/dist/ingress/models.js +46 -2
  15. package/dist/interaction/types.d.ts +1 -0
  16. package/dist/link_client.d.ts +386 -0
  17. package/dist/link_client.js +579 -0
  18. package/dist/models/gateways.d.ts +2 -0
  19. package/dist/models/gateways.js +2 -0
  20. package/dist/models/link_errors.d.ts +30 -0
  21. package/dist/models/link_errors.js +120 -0
  22. package/dist/models/subscriptions.d.ts +8 -1
  23. package/dist/models/subscriptions.js +13 -2
  24. package/dist/platform/platform.d.ts +303 -1
  25. package/dist/protocol/input/router_model.d.ts +4 -0
  26. package/dist/protocol/input/router_model.js +31 -1
  27. package/dist/providers/execution.js +24 -2
  28. package/dist/providers/pi_options.js +57 -1
  29. package/dist/providers/provider_call.d.ts +4 -0
  30. package/dist/providers/provider_call.js +4 -1
  31. package/dist/providers/stream_finalization.d.ts +1 -0
  32. package/dist/runtime/explicit_model.js +16 -4
  33. package/dist/runtime/harness_identity/extract.js +20 -36
  34. package/dist/runtime/link_budget.d.ts +27 -0
  35. package/dist/runtime/link_budget.js +62 -0
  36. package/dist/runtime/link_grant_access.d.ts +7 -0
  37. package/dist/runtime/link_grant_access.js +99 -0
  38. package/dist/runtime/link_in_flight.d.ts +4 -0
  39. package/dist/runtime/link_in_flight.js +43 -0
  40. package/dist/runtime/prepare_routed_completion.js +5 -1
  41. package/dist/runtime/routed_runtime.js +8 -0
  42. package/dist/runtime/runtime_reporter.d.ts +1 -0
  43. package/dist/runtime/runtime_reporter.js +1 -0
  44. package/dist/self_host/config.d.ts +9 -0
  45. package/dist/self_host/config.js +11 -1
  46. package/dist/self_host/link_store.d.ts +167 -0
  47. package/dist/self_host/link_store.js +564 -0
  48. package/dist/self_host/main.d.ts +10 -3
  49. package/dist/self_host/main.js +19 -4
  50. package/dist/self_host/platform.d.ts +2 -2
  51. package/dist/self_host/platform.js +284 -10
  52. package/dist/self_host/resolve.d.ts +8 -0
  53. package/dist/self_host/resolve.js +146 -15
  54. package/dist/self_host/secret_box.d.ts +23 -0
  55. package/dist/self_host/secret_box.js +105 -0
  56. package/dist/self_host/stub_gateway.d.ts +60 -0
  57. package/dist/self_host/stub_gateway.js +397 -0
  58. package/dist/self_host/stub_main.d.ts +2 -0
  59. package/dist/self_host/stub_main.js +69 -0
  60. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  61. package/dist/self_host/subscription_test_gateway.js +25 -91
  62. package/dist/self_host/subscriptions/http.js +1 -0
  63. package/dist/self_host/subscriptions/index.d.ts +2 -2
  64. package/dist/self_host/subscriptions/index.js +2 -2
  65. package/dist/self_host/subscriptions/store.d.ts +41 -16
  66. package/dist/self_host/subscriptions/store.js +136 -32
  67. package/dist/telemetry/report.js +18 -0
  68. package/dist/types.d.ts +18 -0
  69. package/package.json +4 -3
  70. package/src/context/routing_context.ts +3 -1
  71. package/src/http/handler.ts +14 -2
  72. package/src/ingress/anthropic_messages.ts +19 -4
  73. package/src/ingress/chat_completions.ts +6 -1
  74. package/src/ingress/codex.ts +2 -2
  75. package/src/ingress/link.ts +1731 -0
  76. package/src/ingress/link_assets.ts +56 -0
  77. package/src/ingress/link_font.ts +9 -0
  78. package/src/ingress/models.ts +48 -2
  79. package/src/interaction/types.ts +4 -0
  80. package/src/link_client.ts +796 -0
  81. package/src/models/gateways.ts +3 -0
  82. package/src/models/link_errors.ts +157 -0
  83. package/src/models/subscriptions.ts +15 -1
  84. package/src/platform/platform.ts +330 -1
  85. package/src/protocol/input/router_model.ts +36 -1
  86. package/src/providers/execution.ts +24 -2
  87. package/src/providers/pi_options.ts +57 -1
  88. package/src/providers/provider_call.ts +15 -1
  89. package/src/providers/stream_finalization.ts +1 -0
  90. package/src/runtime/explicit_model.ts +21 -8
  91. package/src/runtime/harness_identity/extract.ts +21 -60
  92. package/src/runtime/link_budget.ts +75 -0
  93. package/src/runtime/link_grant_access.ts +116 -0
  94. package/src/runtime/link_in_flight.ts +46 -0
  95. package/src/runtime/prepare_routed_completion.ts +6 -1
  96. package/src/runtime/routed_runtime.ts +8 -0
  97. package/src/runtime/runtime_reporter.ts +3 -0
  98. package/src/self_host/config.ts +24 -1
  99. package/src/self_host/link_store.ts +782 -0
  100. package/src/self_host/main.ts +21 -4
  101. package/src/self_host/platform.ts +305 -11
  102. package/src/self_host/resolve.ts +172 -15
  103. package/src/self_host/secret_box.ts +112 -0
  104. package/src/self_host/stub_gateway.ts +497 -0
  105. package/src/self_host/stub_main.ts +72 -0
  106. package/src/self_host/subscription_test_gateway.ts +26 -95
  107. package/src/self_host/subscriptions/http.ts +1 -0
  108. package/src/self_host/subscriptions/index.ts +3 -0
  109. package/src/self_host/subscriptions/store.ts +167 -36
  110. package/src/telemetry/report.ts +17 -1
  111. package/src/types.ts +26 -0
  112. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  113. package/dist/self_host/subscriptions/test_support.js +0 -34
@@ -1,6 +1,7 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
 
3
3
  import {
4
+ isReasoningEffort,
4
5
  nativeModelId,
5
6
  providerForModel,
6
7
  type ReasoningEffort,
@@ -8,9 +9,22 @@ import {
8
9
  } from "@mupt-ai/dari-router/policy-engine";
9
10
  import { HttpError } from "../http/errors.js";
10
11
  import type { ResolveRouterRequest } from "../platform/platform.js";
11
- import { codexModelConfig } from "../models/subscriptions.js";
12
+ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
13
+ import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
14
+ import { CANONICAL_MODELS } from "../models/canonical.js";
15
+ import { gatewayFor } from "../models/gateways.js";
16
+ import {
17
+ budgetExhausted,
18
+ linkGrantRevoked,
19
+ linkGrantUnavailableError,
20
+ linkTokenExpired,
21
+ linkUnavailableError,
22
+ modelNotServed,
23
+ plansExhausted,
24
+ plansForAnotherClient,
25
+ } from "../models/link_errors.js";
12
26
  import { registeredModelPrice } from "../providers/pi.js";
13
- import type { ProviderKeySource, ResolvedRouter } from "../types.js";
27
+ import type { LinkUnavailable, ProviderKeySource, ResolvedRouter } from "../types.js";
14
28
  import {
15
29
  allRouterModels,
16
30
  routerModelsFor,
@@ -18,6 +32,8 @@ import {
18
32
  type RouterConfig,
19
33
  type RouterModelConfig,
20
34
  } from "./config.js";
35
+ import type { ActiveLinkGrant, LinkStore } from "./link_store.js";
36
+ import { overBudgetUntil } from "../runtime/link_budget.js";
21
37
  import type { RouterModelStore } from "./router_models.js";
22
38
  import {
23
39
  activeModelHolds,
@@ -39,6 +55,7 @@ export type SelfHostedResolverDeps = {
39
55
  routerModels: RouterModelStore;
40
56
  gatewayKeys: readonly string[];
41
57
  subscriptions: SubscriptionStore;
58
+ links: LinkStore;
42
59
  prefixHits: (args: {
43
60
  routerId: string;
44
61
  prefixHashes: readonly string[];
@@ -65,32 +82,57 @@ type ProviderCredential = {
65
82
  * available, otherwise by the provider's API key; models whose provider has
66
83
  * neither are left out. A coding agent with its own model list on the router
67
84
  * is served that list.
85
+ *
86
+ * A Dari Link token resolves only the default router, served on its grant's
87
+ * subscriptions alone and never an API key. Its `enabled_models` are the
88
+ * router's models a granted plan serves, and `link_models` adds every other
89
+ * catalog model of those plans' providers, which a request may name
90
+ * explicitly. A child token serves only its one model.
68
91
  */
69
92
  export async function resolveSelfHostedRouter(
70
93
  deps: SelfHostedResolverDeps,
71
94
  request: ResolveRouterRequest,
72
95
  ): Promise<ResolvedRouter> {
73
96
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
74
- if (keyIndex === null) {
97
+ const grant = keyIndex === null ? activeLinkGrant(deps.links, request.apiKey) : null;
98
+ if (keyIndex === null && grant === null) {
75
99
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
76
100
  }
101
+ if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
102
+ throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
103
+ }
104
+ if (grant !== null) {
105
+ // A grant at its token budget serves nothing until its window rolls on.
106
+ const back = overBudgetUntil(deps.links.budgetStandings(grant.id));
107
+ if (back !== undefined) throw linkUnavailableError(budgetExhausted(back));
108
+ }
77
109
  const configured = deps.config.routers[request.routerId];
78
110
  if (configured === undefined) {
79
111
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
80
112
  }
81
113
  const router = deps.routerModels.served(request.routerId, configured);
82
114
 
83
- const listed = routerModelsFor(router, request.clientHarness);
115
+ const routed = routerModelsFor(router, request.clientHarness);
116
+ const granted = grant === null
117
+ ? []
118
+ : deps.subscriptions.withIds(grant.credentialIds);
119
+ // A grant's API keys, by the provider or gateway each is a key for.
120
+ const grantedKeys = new Map(
121
+ (grant === null ? [] : deps.links.keysWithIds(grant.credentialIds)).map((key) => [key.provider, key.apiKey]),
122
+ );
123
+ const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
84
124
  const now = new Date();
125
+ const servable = grant === null ? undefined : new Set(grant.credentialIds);
85
126
  const credentials = new Map<string, ProviderCredential | null>();
86
127
  const exhausted = new Set<SubscriptionProvider>();
87
128
  for (const provider of new Set(listed.map((model) => providerForModel(model.id)))) {
88
- const subscription = router.subscriptions
129
+ // A grant uses the subscriptions its user chose, whatever the router allows.
130
+ const subscription = router.subscriptions || grant !== null
89
131
  ? subscriptionProviderFor(provider, request.clientHarness)
90
132
  : null;
91
133
  const active = subscription === null
92
134
  ? null
93
- : deps.subscriptions.selectCredential(subscription, request.conversationId, now);
135
+ : deps.subscriptions.selectCredential(subscription, request.conversationId, now, servable);
94
136
  if (active !== null) {
95
137
  credentials.set(provider, {
96
138
  // A provisional resolve's credentials never serve, so it neither marks
@@ -103,37 +145,74 @@ export async function resolveSelfHostedRouter(
103
145
  });
104
146
  continue;
105
147
  }
106
- if (subscription !== null && deps.subscriptions.list(subscription).length > 0) {
107
- exhausted.add(subscription);
148
+ if (grant !== null) {
149
+ // A plan first; else the key the user added for the provider.
150
+ const key = grantedKeys.get(provider);
151
+ credentials.set(provider, key === undefined ? null : { key, source: "user" });
152
+ continue;
108
153
  }
154
+ if (subscription !== null && deps.subscriptions.list(subscription).length > 0) exhausted.add(subscription);
109
155
  const apiKey = await configuredProviderApiKey(deps, provider);
110
156
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
111
157
  }
112
158
 
113
159
  // A model at its own limit on the serving plan leaves routing until it resets.
160
+ const linkUnavailable = grant === null
161
+ ? {}
162
+ : grantUnavailable(granted, credentials, request.clientHarness, now);
114
163
  const models = listed.filter((model) => {
115
164
  const credential = credentials.get(providerForModel(model.id));
116
165
  if (credential == null) return false;
117
166
  const plan = credential.subscription;
118
- if (plan === undefined || !activeModelHolds(plan, now).some((hold) => hold.model === model.id)) return true;
167
+ const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
168
+ if (plan === undefined || hold === undefined) return true;
119
169
  exhausted.add(plan.provider);
170
+ linkUnavailable[model.id] = plansExhausted([plan.provider], hold.until);
120
171
  return false;
121
172
  });
122
- if (models.length === 0) {
173
+ // A grant with a gateway key serves the gateway's models by name, listed or not.
174
+ const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
175
+ if (models.length === 0 && !gatewayKeyed) {
176
+ if (grant !== null) {
177
+ throw grant.pins?.length === 1
178
+ ? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0]!.model)
179
+ : linkGrantUnavailableError(linkUnavailable);
180
+ }
123
181
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
124
182
  throw unavailableRouterError(request.routerId, exhausted, missing);
125
183
  }
184
+ // `dari/routing` chooses among the router's own models; a grant may also
185
+ // name any other catalog model its plans serve.
186
+ const routedIds = new Set(routed.map((model) => model.id));
187
+ const enabled = grant === null || grant.pins !== undefined ? models : models.filter((model) => routedIds.has(model.id));
126
188
 
127
189
  const resolved: ResolvedRouter = {
128
190
  router_id: request.routerId,
129
191
  organization_id: SELF_HOSTED_ORGANIZATION_ID,
130
- api_key_id: `gateway_key_${keyIndex + 1}`,
192
+ api_key_id: grant === null ? `gateway_key_${keyIndex! + 1}` : grant.id,
131
193
  attributed_user_id: SELF_HOSTED_USER_ID,
132
- enabled_models: models.map((model) => model.id),
194
+ enabled_models: enabled.map((model) => model.id),
133
195
  routing_listed: deps.autoRouting,
134
196
  provider_keys: {},
135
197
  provider_key_sources: {},
136
198
  subscription_credential_ids: {},
199
+ link_grant_id: grant?.id ?? null,
200
+ ...(grant === null
201
+ ? {}
202
+ : {
203
+ link_models: models.map((model) => model.id),
204
+ link_key_gateways: Object.fromEntries(
205
+ [...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
206
+ const endpoint = deps.config.providers[gateway];
207
+ return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
208
+ }),
209
+ ),
210
+ link_unavailable: linkUnavailable,
211
+ link_pins: grant.pins === undefined
212
+ ? null
213
+ : grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
214
+ link_tags: grant.tags ?? null,
215
+ }),
137
216
  zdr: router.zdr,
138
217
  speculative_routing: false,
139
218
  session_pinning: router.sessionPinning,
@@ -141,8 +220,8 @@ export async function resolveSelfHostedRouter(
141
220
  primary_retries: router.retries,
142
221
  routing_strategy: "dari",
143
222
  custom_config: null,
144
- role_models: router.roleModels,
145
- role_prompts: router.rolePrompts,
223
+ // A grant's request is served the model it named, never a role's.
224
+ ...(grant === null ? { role_models: router.roleModels, role_prompts: router.rolePrompts } : {}),
146
225
  evals: [],
147
226
  model_thinking_levels: thinkingLevels(listed),
148
227
  model_prices: {},
@@ -163,13 +242,19 @@ export async function resolveSelfHostedRouter(
163
242
  }
164
243
  }
165
244
  }
245
+ // A gateway key serves any model of its gateway a request names, listed or not.
246
+ for (const [provider, key] of grantedKeys) {
247
+ if (resolved.provider_keys[provider] !== undefined) continue;
248
+ resolved.provider_keys[provider] = key;
249
+ resolved.provider_key_sources![provider] = "user";
250
+ }
166
251
  for (const model of models) {
167
252
  const price = registeredModelPrice(model.id);
168
253
  if (price !== null) resolved.model_prices![model.id] = price;
169
254
  const provider = providerForModel(model.id);
170
255
  const endpoint = deps.config.providers[provider];
171
256
  if (credentials.get(provider)?.subscription?.provider === "openai_codex") {
172
- resolved.model_configs![model.id] = codexModelConfig(model.id, price);
257
+ resolved.model_configs![model.id] = codexModelConfig(model.id, price, deps.config.providers["openai-codex"]?.baseUrl);
173
258
  } else if (endpoint !== undefined) {
174
259
  resolved.model_configs![model.id] = {
175
260
  provider,
@@ -183,6 +268,78 @@ export async function resolveSelfHostedRouter(
183
268
  return resolved;
184
269
  }
185
270
 
271
+ // The grant a live link token belongs to, or null for a token that is not
272
+ // one. A dead token is refused with the reason.
273
+ function activeLinkGrant(links: LinkStore, token: string): ActiveLinkGrant | null {
274
+ const auth = links.authenticate(token);
275
+ if (auth === null) return null;
276
+ if (auth.status === "expired") throw linkTokenExpired();
277
+ if (auth.status === "revoked") throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
278
+ return auth.grant;
279
+ }
280
+
281
+ /**
282
+ * The models a grant's request may be served: a child token's one model, or
283
+ * the router's own models followed by every other catalog model of the
284
+ * providers its plans and API keys serve.
285
+ */
286
+ function grantModels(
287
+ grant: ActiveLinkGrant,
288
+ routed: readonly RouterModelConfig[],
289
+ granted: readonly SubscriptionCredential[],
290
+ grantedKeys: ReadonlyMap<string, string>,
291
+ ): RouterModelConfig[] {
292
+ const providers = new Set([
293
+ ...granted.map((credential) => subscriptionModelProvider(credential.provider)),
294
+ ...grantedKeys.keys(),
295
+ ]);
296
+ const routedIds = new Set(routed.map((model) => model.id));
297
+ const models = [
298
+ ...routed,
299
+ ...CANONICAL_MODELS
300
+ .filter((model) => !routedIds.has(model.id) && providers.has(providerForModel(model.id)) && registeredModelPrice(model.id) !== null)
301
+ .map((model): RouterModelConfig => ({ id: model.id })),
302
+ ];
303
+ if (grant.pins === undefined) return models;
304
+ // A pinned level replaces the router's own choice of levels for the model.
305
+ const pinned = new Set(grant.pins.map((pin) => pin.model));
306
+ return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
307
+ }
308
+
309
+ /**
310
+ * Why each provider with a granted plan serves nothing now: its plans serve
311
+ * only another client, or are all at their usage limits.
312
+ */
313
+ function grantUnavailable(
314
+ granted: readonly SubscriptionCredential[],
315
+ credentials: ReadonlyMap<string, ProviderCredential | null>,
316
+ clientHarness: ResolveRouterRequest["clientHarness"],
317
+ now: Date,
318
+ ): Record<string, LinkUnavailable> {
319
+ const unavailable: Record<string, LinkUnavailable> = {};
320
+ for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
321
+ // Only a provider the request wanted and no plan served.
322
+ if (credentials.get(provider) !== null) continue;
323
+ const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
324
+ const usable = plans.filter((credential) => {
325
+ const client = subscriptionClient(credential.provider);
326
+ return client === undefined || client === clientHarness;
327
+ });
328
+ if (usable.length === 0) {
329
+ unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
330
+ continue;
331
+ }
332
+ const held = usable.flatMap((credential) =>
333
+ credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []
334
+ );
335
+ unavailable[provider] = plansExhausted(
336
+ usable.map((credential) => credential.provider),
337
+ held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null,
338
+ );
339
+ }
340
+ return unavailable;
341
+ }
342
+
186
343
  // Configured endpoints read their own key variable, or send a placeholder
187
344
  // when they take none; known providers use their standard variable.
188
345
  export async function configuredProviderApiKey(
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Encryption at rest for the secrets the gateway's database holds:
3
+ * subscription tokens, pending sign-ins, and the API keys Dari Link users add.
4
+ *
5
+ * `DARI_GATEWAY_ENCRYPTION_KEY` holds one or more 32-byte keys, base64 or
6
+ * base64url, comma-separated. The first encrypts; any of them decrypts, so a
7
+ * key is rotated by putting the new one first and keeping the old one until
8
+ * the gateway has started once (startup re-encrypts every stored secret under
9
+ * the first key).
10
+ *
11
+ * Each value is sealed with AES-256-GCM under a fresh nonce and bound to the
12
+ * row and column it belongs to, so a ciphertext copied into another row, or
13
+ * another column, does not open. A sealed value reads
14
+ * `enc:v1:<key id>:<base64url(nonce | ciphertext | tag)>`; the key id is the
15
+ * first 8 hex characters of the key's SHA-256.
16
+ *
17
+ * Without a key the database holds secrets as they are, protected only by its
18
+ * file permissions, and the gateway refuses to take other people's
19
+ * subscriptions and keys on the Dari Link approval page.
20
+ */
21
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
22
+
23
+ const PREFIX = "enc:v1:";
24
+ const NONCE_BYTES = 12;
25
+ const TAG_BYTES = 16;
26
+
27
+ export class SecretBox {
28
+ private readonly keys: Map<string, Buffer>;
29
+ private readonly currentId: string;
30
+
31
+ constructor(keys: readonly Buffer[]) {
32
+ if (keys.length === 0 || keys.some((key) => key.length !== 32)) {
33
+ throw new Error("Each encryption key must be 32 bytes.");
34
+ }
35
+ this.keys = new Map(keys.map((key) => [keyId(key), key]));
36
+ this.currentId = keyId(keys[0]!);
37
+ }
38
+
39
+ /** Encrypt a value for one place: `where` names its table, row, and column. */
40
+ seal(plaintext: string, where: string): string {
41
+ const nonce = randomBytes(NONCE_BYTES);
42
+ const cipher = createCipheriv("aes-256-gcm", this.keys.get(this.currentId)!, nonce);
43
+ cipher.setAAD(Buffer.from(where));
44
+ const sealed = Buffer.concat([nonce, cipher.update(plaintext, "utf8"), cipher.final(), cipher.getAuthTag()]);
45
+ return `${PREFIX}${this.currentId}:${sealed.toString("base64url")}`;
46
+ }
47
+
48
+ /**
49
+ * The value stored at `where`. Throws when it is not sealed (a value written
50
+ * into the database around the gateway), was sealed for another place, was
51
+ * altered, or needs a key this box does not hold.
52
+ */
53
+ open(stored: string, where: string): string {
54
+ if (!isSealed(stored)) throw new Error(`A stored secret (${where}) is not encrypted.`);
55
+ const [id, body] = stored.slice(PREFIX.length).split(":");
56
+ const key = this.keys.get(id ?? "");
57
+ if (key === undefined || body === undefined) {
58
+ throw new Error(`A stored secret needs an encryption key (${id}) that DARI_GATEWAY_ENCRYPTION_KEY does not list.`);
59
+ }
60
+ const sealed = Buffer.from(body, "base64url");
61
+ if (sealed.length < NONCE_BYTES + TAG_BYTES) throw new Error(`A stored secret (${where}) does not open: it was altered or moved.`);
62
+ const decipher = createDecipheriv("aes-256-gcm", key, sealed.subarray(0, NONCE_BYTES), { authTagLength: TAG_BYTES });
63
+ decipher.setAAD(Buffer.from(where));
64
+ decipher.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES));
65
+ try {
66
+ return Buffer.concat([decipher.update(sealed.subarray(NONCE_BYTES, sealed.length - TAG_BYTES)), decipher.final()])
67
+ .toString("utf8");
68
+ } catch {
69
+ throw new Error(`A stored secret (${where}) does not open: it was altered or moved.`);
70
+ }
71
+ }
72
+
73
+ /** A stored value for re-sealing at startup: one stored before encryption was turned on is taken as it is. */
74
+ adopt(stored: string, where: string): string {
75
+ return isSealed(stored) ? this.open(stored, where) : stored;
76
+ }
77
+
78
+ /** Whether a stored value is sealed under the key that encrypts now. */
79
+ current(stored: string): boolean {
80
+ return stored.startsWith(`${PREFIX}${this.currentId}:`);
81
+ }
82
+ }
83
+
84
+ /** Whether a stored value is encrypted. */
85
+ export function isSealed(stored: string): boolean {
86
+ return stored.startsWith(PREFIX);
87
+ }
88
+
89
+ /** A value read without a box: itself, unless it is encrypted and so needs the key. */
90
+ export function openWithoutKey(stored: string): string {
91
+ if (isSealed(stored)) {
92
+ throw new Error("This gateway database is encrypted. Set DARI_GATEWAY_ENCRYPTION_KEY to the key it was encrypted with.");
93
+ }
94
+ return stored;
95
+ }
96
+
97
+ /** The box for `DARI_GATEWAY_ENCRYPTION_KEY`, or null when it is unset. */
98
+ export function secretBoxFromEnv(value: string | undefined): SecretBox | null {
99
+ const keys = (value ?? "").split(",").map((key) => key.trim()).filter(Boolean);
100
+ if (keys.length === 0) return null;
101
+ return new SecretBox(keys.map((key) => {
102
+ const bytes = Buffer.from(key, key.includes("-") || key.includes("_") ? "base64url" : "base64");
103
+ if (bytes.length !== 32) {
104
+ throw new Error("DARI_GATEWAY_ENCRYPTION_KEY must be 32-byte keys in base64, such as `openssl rand -base64 32` prints.");
105
+ }
106
+ return bytes;
107
+ }));
108
+ }
109
+
110
+ function keyId(key: Buffer): string {
111
+ return createHash("sha256").update(key).digest("hex").slice(0, 8);
112
+ }