@goodandready/dsh-key-rotation 0.7.38 → 0.7.40

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/lib/index.js CHANGED
@@ -1,44 +1,18 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // dsh-key-rotation — per-provider API key rotation for DeepSeek Harness.
1
+ // dsh-key-rotation — per-provider API key rotation for DeepSeek Harness.
3
2
  //
4
- // Transparent key rotation, Hermes-style: every configured provider has a KEY
5
- // POOL (env refs). The plugin patches `ctx.credentials.resolve` so a pool ref
6
- // resolves to the next available key (round-robin, skipping keys in cooldown),
7
- // and intercepts `llm/stream` to retry a request on the next key when the
8
- // current one fails with a switchable error (QUOTA, RATE_LIMIT, ...) before
9
- // any content chunk.
10
- //
11
- // The PROVIDER IDENTITY NEVER CHANGES: requests always go out with the
12
- // provider the user selected, only the resolved API key differs. This keeps
13
- // pi-ai's replay state consistent across multi-call turns and multi-turn
14
- // sessions (the earlier clone-provider approach broke it with
15
- // INVALID_REPLAY_STATE).
16
- //
17
- // Config is a KEY POOL PER PROVIDER: you list a real provider id and the env
18
- // names of its API keys (e.g. <PROVIDER>_API_KEY, <PROVIDER>_API_KEY_2, ...).
19
- // When a key's limit is exhausted, the request retries on the next key in the
20
- // list; exhausted keys stay in cooldown for cooldownMs. Clone provider routes
21
- // (named `<base>-2`, `<base>-3`, ...) are no longer used for rotation but
22
- // remain registered, so selecting them also rotates (their apiKeyEnv ref
23
- // belongs to the same pool).
24
- //
25
- // The Settings section ("Key Rotation") edits the provider key pools as a
26
- // simple list: pick a provider from the dropdown of every provider registered
27
- // with ctx.llm (clone routes are hidden from the dropdown), then add/remove key
28
- // env names. Plus cooldown and switch codes.
29
- //
30
- // Config (all optional, sane defaults):
31
- // switchCodes: string[] failure codes eligible to switch
32
- // cooldownMs: number key cooldown after a switchable failure
33
- // providers: array [{ provider, keys: [envName, ...] }]
34
- // ─────────────────────────────────────────────────────────────────────────────
3
+ // Transparent key pool rotation: credentials.resolve patch + llm/stream
4
+ // interceptor. Provider identity never changes (keeps pi-ai replay state).
5
+ // See README.md and docs/design/DESIGN.md for the full contract.
6
+ // Config (all optional): switchCodes, cooldownMs, providers[{provider,keys}],
7
+ // verboseLogging (default false) gates per-request rotation logs.
8
+
35
9
  import { AsyncLocalStorage } from 'node:async_hooks';
36
10
  import Schema from '@deepseek-ai/schemastery';
37
11
  import { keyTail, isLoopbackAddress, isTrustedBridgeRequest, SWITCHABLE_MESSAGE_PATTERN, DEFAULT_SWITCH_CODES, isValidRef, pickNext, applyCooldown, recordFailure, recordSuccess, computeBackoff, envValue, sweepExpired, parseRetryAfter, computeHealthScore, extractRateLimit, isRateLimited, selectPool, isSwitchableError, formatExhaustionMessage, expiringSoon, shouldNotifyDaily, costForDay, costForWeek, budgetVerdict } from './pool.js';
38
12
 
39
13
  export const name = 'dsh-key-rotation';
40
14
  export const inject = ['llm', 'webServer', 'settings', 'credentials'];
41
- export { keyTail, isLoopbackAddress, isTrustedBridgeRequest, DEFAULT_SWITCH_CODES, isSwitchableError, formatExhaustionMessage };
15
+ export { keyTail, isLoopbackAddress, isTrustedBridgeRequest, DEFAULT_SWITCH_CODES, isSwitchableError, formatExhaustionMessage, getRuntime };
42
16
 
43
17
  /** Settings namespace owning the GUI-editable section (settingsNamespace-valid). */
44
18
  const NS = 'dsh-key-rotation';
@@ -66,6 +40,9 @@ import { usageRows, usageCsv, compactUsage } from './usage-report.js';
66
40
 
67
41
  const dispatchStorage = new AsyncLocalStorage();
68
42
  import { findSecrets, looksLikeApiSecret } from './keycheck.js';
43
+ import { json, readJson, descriptorOf, viewOf, writeSection, providerCatalog, handleConfigBridge, NS as BRIDGE_NS } from './http-bridge.js';
44
+ import { createRotate } from './rotate.js';
45
+ import { registerOpsRoutes } from './routes-ops.js';
69
46
 
70
47
  /** The llm-pi-ai namespace whose provider profiles map providers to pools. */
71
48
  const PIAI_NS = 'llm-pi-ai';
@@ -204,6 +181,7 @@ export const Config = Schema.object({
204
181
  webhookActionToken: Schema.string().role('secret').default(''),
205
182
  expiryWarnDays: Schema.number().default(7),
206
183
  switchNotify: Schema.boolean().default(false),
184
+ verboseLogging: Schema.boolean().default(false),
207
185
  switchNotifyThrottleMs: Schema.number().default(60000),
208
186
  warnBelowHealthy: Schema.number().default(0),
209
187
  latencySloMs: Schema.number().default(0),
@@ -228,163 +206,6 @@ export const Config = Schema.object({
228
206
  // ── config bridge (GET/PUT/DELETE on CONFIG_PATH), mirroring llm-fallback ──
229
207
 
230
208
 
231
- function json(res, status, obj) {
232
- res.writeHead(status, { 'content-type': 'application/json' });
233
- res.end(JSON.stringify(obj));
234
- }
235
-
236
- function readJson(request) {
237
- return new Promise((resolve, reject) => {
238
- let raw = '';
239
- request.on('data', (c) => { raw += c; });
240
- request.on('end', () => {
241
- try {
242
- resolve(JSON.parse(raw || '{}'));
243
- } catch (e) {
244
- reject(e);
245
- }
246
- });
247
- request.on('error', reject);
248
- });
249
- }
250
-
251
- function descriptorOf(ctx, ns) {
252
- const settings = ctx.get('settings');
253
- if (settings === void 0) return void 0;
254
- return settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === ns);
255
- }
256
-
257
- function viewOf(descriptor, settings) {
258
- return {
259
- available: true,
260
- writable: settings.writable,
261
- hasDocument: settings.hasDocument,
262
- value: descriptor.value,
263
- ...descriptor.base === void 0 ? {} : { base: descriptor.base },
264
- ...descriptor.user === void 0 || Object.keys(descriptor.user).length === 0 ? {} : { user: descriptor.user },
265
- revision: descriptor.revision,
266
- };
267
- }
268
-
269
- async function writeSection(ctx, ns, section, expectedRevision, res) {
270
- const settings = ctx.get('settings');
271
- if (settings === void 0) {
272
- json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider is mounted' } });
273
- return;
274
- }
275
- try {
276
- await settings.replace(ns, section, expectedRevision);
277
- } catch (error) {
278
- if (error?.code === 'SETTINGS_CONFLICT') {
279
- json(res, 409, { error: { code: 'settings-conflict', message: `dsh-key-rotation: changed elsewhere (expected revision ${String(error.expected)}, current ${String(error.actual)}); reload and retry` } });
280
- return;
281
- }
282
- json(res, 400, { error: { code: 'settings-rejected', message: error instanceof Error ? error.message : String(error) } });
283
- return;
284
- }
285
- const descriptor = descriptorOf(ctx, ns);
286
- if (descriptor === void 0) {
287
- json(res, 500, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: namespace vanished after write' } });
288
- return;
289
- }
290
- json(res, 200, viewOf(descriptor, { writable: settings.writable, hasDocument: settings.documentPath !== void 0 }));
291
- }
292
-
293
- /** Provider catalog for the GUI dropdown, minus clone routes of configured chains. */
294
- function providerCatalog(ctx, cloneIds) {
295
- const seen = new Set();
296
- const out = [];
297
- for (const info of ctx.llm.listProviders()) {
298
- if (seen.has(info.id) || cloneIds.has(info.id)) continue;
299
- seen.add(info.id);
300
- out.push({ id: info.id, name: info.name ?? info.id });
301
- }
302
- return out;
303
- }
304
-
305
- async function handleConfigBridge(ctx, request, res, getCloneIds) {
306
- if (!isTrustedBridgeRequest(request)) {
307
- res.writeHead(403);
308
- res.end();
309
- return;
310
- }
311
- const method = request.method ?? 'GET';
312
- if (method === 'GET') {
313
- const settings = ctx.get('settings');
314
- const descriptor = descriptorOf(ctx, NS);
315
- const body = {
316
- providers: providerCatalog(ctx, getCloneIds()),
317
- };
318
- if (descriptor === void 0) {
319
- json(res, 200, {
320
- ...body,
321
- available: false,
322
- writable: settings?.writable ?? false,
323
- hasDocument: settings?.documentPath !== void 0,
324
- value: void 0,
325
- revision: 0,
326
- });
327
- return;
328
- }
329
- json(res, 200, {
330
- ...body,
331
- ...viewOf(descriptor, {
332
- writable: settings?.writable ?? false,
333
- hasDocument: settings?.documentPath !== void 0,
334
- }),
335
- });
336
- return;
337
- }
338
- if (method === 'PUT' || method === 'DELETE') {
339
- let section;
340
- let expectedRevision;
341
- if (method === 'PUT') {
342
- let body;
343
- try {
344
- body = await readJson(request);
345
- } catch (error) {
346
- json(res, 400, { error: { code: 'settings-rejected', message: `dsh-key-rotation: invalid request body: ${error instanceof Error ? error.message : String(error)}` } });
347
- return;
348
- }
349
- if (typeof body !== 'object' || body === null || typeof body.section !== 'object' || body.section === null || Array.isArray(body.section)) {
350
- json(res, 400, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: PUT requires {"section": {...}}' } });
351
- return;
352
- }
353
- section = body.section;
354
- expectedRevision = typeof body.expectedRevision === 'number' ? body.expectedRevision : void 0;
355
- // #200 leak detector: a live secret pasted into the config section is
356
- // almost always a mistake (real key values belong in PUT /key). The two
357
- // fields that legitimately hold tokens are masked before scanning.
358
- try {
359
- const masked = structuredClone(section);
360
- if (masked.webhookActionToken) masked.webhookActionToken = '***';
361
- // notifyWebhook legitimately carries bot tokens inside URLs
362
- // (api.telegram.org/bot<token>/...) - scan it for nothing.
363
- if (masked.notifyWebhook) masked.notifyWebhook = '***';
364
- const findings = findSecrets(JSON.stringify(masked));
365
- if (findings.length > 0) {
366
- json(res, 400, {
367
- error: {
368
- code: 'secret-in-config',
369
- message: `dsh-key-rotation: value looks like a live credential (${findings[0].type}); store key values via the key field, not the config section`,
370
- findings,
371
- },
372
- });
373
- return;
374
- }
375
- } catch {
376
- /* scanning must never block a valid save */
377
- }
378
- } else {
379
- section = {};
380
- }
381
- await writeSection(ctx, NS, section, expectedRevision, res);
382
- return;
383
- }
384
- res.writeHead(405);
385
- res.end();
386
- }
387
-
388
209
  function registerConfigBridge(ctx, getCloneIds) {
389
210
  return ctx.webServer.register({
390
211
  kind: 'exact',
@@ -452,13 +273,13 @@ export function apply(ctx, config = {}) {
452
273
  }
453
274
  const n = sweepExpired(poolState, now);
454
275
  if (n > 0) console.warn(`[dsh-key-rotation] sweep: cleared ${n} expired cooldown(s)`);
455
- for (const pool of buildRuntime().poolByRef.values()) {
276
+ const runtime = buildRuntime();
277
+ for (const pool of runtime.poolByRef.values()) {
456
278
  compactUsage(pool, 30, now);
457
279
  }
458
280
  // #207 expiry pre-warning + #208 cost budget - piggybacked on this timer,
459
281
  // deduped to one notification per key/window per day (shouldNotifyDaily).
460
282
  try {
461
- const runtime = buildRuntime();
462
283
  const seen = new Set();
463
284
  for (const pool of runtime.poolByRef.values()) {
464
285
  if (seen.has(pool.base)) continue;
@@ -563,6 +384,7 @@ export function apply(ctx, config = {}) {
563
384
  }
564
385
  } catch (_) { /* maintenance must never crash the sweep */ }
565
386
  }, 30000);
387
+ if (typeof id.unref === 'function') id.unref();
566
388
  return () => clearInterval(id);
567
389
  }, 'dsh-key-rotation: sweep expired cooldowns');
568
390
 
@@ -715,7 +537,7 @@ export function apply(ctx, config = {}) {
715
537
  const weekly = typeof p.costBudgetWeekly === 'number' ? p.costBudgetWeekly : 0;
716
538
  if (daily > 0 || weekly > 0) providerBudgets.set(p.provider, { costBudgetDaily: daily, costBudgetWeekly: weekly, pauseOnBudget: p.pauseOnBudget ?? false });
717
539
  }
718
- cachedRuntime = { switchCodes, cooldownMs, maxCooldownMs, notifyWebhook, notifyThreshold, concurrencyLimit, cascade, quotaResetWindow, rateLimitThreshold, rpmLimit, webhookActionToken, expiryWarnDays: cfg.expiryWarnDays ?? 7, switchNotify: cfg.switchNotify ?? false, switchNotifyThrottleMs: cfg.switchNotifyThrottleMs ?? 60000, warnBelowHealthy: cfg.warnBelowHealthy ?? 0, latencySloMs: cfg.latencySloMs ?? 0, providerTags, providerBudgets, poolByRef, providerToPool, modelPoolByProvider, cloneIds };
540
+ cachedRuntime = { switchCodes, cooldownMs, maxCooldownMs, notifyWebhook, notifyThreshold, concurrencyLimit, cascade, quotaResetWindow, rateLimitThreshold, rpmLimit, webhookActionToken, expiryWarnDays: cfg.expiryWarnDays ?? 7, switchNotify: cfg.switchNotify ?? false, verboseLogging: cfg.verboseLogging ?? false, switchNotifyThrottleMs: cfg.switchNotifyThrottleMs ?? 60000, warnBelowHealthy: cfg.warnBelowHealthy ?? 0, latencySloMs: cfg.latencySloMs ?? 0, providerTags, providerBudgets, poolByRef, providerToPool, modelPoolByProvider, cloneIds };
719
541
  lastConfigRef = rawConfig;
720
542
  lastProfilesRef = currentProfiles;
721
543
  return cachedRuntime;
@@ -771,6 +593,8 @@ export function apply(ctx, config = {}) {
771
593
  let hit = await original(candidate);
772
594
  if (hit && typeof hit.value === 'string' && hit.value.length > 0) {
773
595
  pool.state.lastUsed = candidate;
596
+ if (!pool.state.lastUsedAt) pool.state.lastUsedAt = new Map();
597
+ pool.state.lastUsedAt.set(candidate, now);
774
598
  const store = dispatchStorage.getStore();
775
599
  if (store && store.pool === pool) store.pickedRef = candidate;
776
600
  if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
@@ -792,6 +616,8 @@ export function apply(ctx, config = {}) {
792
616
  const envVal = envValue(candidate);
793
617
  if (envVal !== undefined) {
794
618
  pool.state.lastUsed = candidate;
619
+ if (!pool.state.lastUsedAt) pool.state.lastUsedAt = new Map();
620
+ pool.state.lastUsedAt.set(candidate, now);
795
621
  const store = dispatchStorage.getStore();
796
622
  if (store && store.pool === pool) store.pickedRef = candidate;
797
623
  if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
@@ -844,757 +670,34 @@ export function apply(ctx, config = {}) {
844
670
  } catch (_) { /* ponytail: never crash */ }
845
671
  }
846
672
 
673
+ // rotate() factory (#253): dependencies injected for testability
674
+ const rotate = createRotate({
675
+ ctx,
676
+ dispatchStorage,
677
+ buildRuntime,
678
+ pushEvent,
679
+ notifySwitch,
680
+ notifyExhaustion,
681
+ recordLatency,
682
+ concurrencyTracker,
683
+ MARKER,
684
+ finishError,
685
+ setRotateStartMs: (v) => { _rotateStartMs = v; },
686
+ });
687
+
847
688
  // Retry one request on the next pool key when the current key fails with a
848
689
  // switchable error before any content chunk. The provider never changes —
849
690
  // the resolve patch hands out the next key on each dispatch.
850
- function rotate(options, pool) {
851
- return (async function* () {
852
- const runtime0 = buildRuntime();
853
- const { switchCodes, cooldownMs, maxCooldownMs, switchNotify, rateLimitThreshold } = runtime0;
854
- let lastFailure = null;
855
- const reqStore = { pool, pickedRef: undefined, startMs: Date.now() };
856
- _rotateStartMs = reqStore.startMs;
857
- let attemptList = (pool.weightedRefs ?? pool.refs).slice();
858
- if (runtime0.concurrencyLimit > 0 && concurrencyTracker.isEnabled()) {
859
- // #193: prefer least-loaded key within limit
860
- const available = attemptList.filter((r) => {
861
- const fu = pool.state.failedUntil.get(r) ?? 0;
862
- if (fu > Date.now()) return false;
863
- const exp = pool.expiresAt ? pool.expiresAt[r] : undefined;
864
- if (exp !== undefined && Date.now() >= exp) return false;
865
- return true;
866
- });
867
- const preferred = concurrencyTracker.pickLeastLoaded(available);
868
- if (preferred && attemptList[0] !== preferred) {
869
- const list = attemptList.slice();
870
- const i = list.indexOf(preferred);
871
- if (i > 0) { list.splice(i, 1); list.unshift(preferred); }
872
- attemptList = list;
873
- }
874
- }
875
-
876
- const penalizeRef = (targetRef, errCode, errMsg) => {
877
- if (!targetRef) return;
878
- const _retry = parseRetryAfter(errMsg);
879
- const _base = pool.cooldownMs ?? cooldownMs;
880
- const _max = pool.maxCooldownMs ?? maxCooldownMs;
881
- const _effBase = _retry !== undefined ? Math.max(_base, Math.min(_retry, _max ?? _base * 8)) : _base;
882
- const _b = recordFailure(pool, targetRef, Date.now(), _effBase, _max);
883
- pushEvent(pool, targetRef, errCode ?? 'UNKNOWN', _b);
884
- if (!pool.state.authFailCounts) pool.state.authFailCounts = new Map();
885
- if (!pool.state.brokenUntil) pool.state.brokenUntil = new Map();
886
- const _cStr = String(errCode ?? '');
887
- if (_cStr === 'AUTH' || /auth/i.test(errMsg)) {
888
- const _c2 = (pool.state.authFailCounts.get(targetRef) ?? 0) + 1;
889
- pool.state.authFailCounts.set(targetRef, _c2);
890
- if (_c2 >= 3) {
891
- pool.state.brokenUntil.set(targetRef, Date.now() + 86400000 * 30);
892
- pool.state.failedUntil.set(targetRef, Date.now() + 86400000 * 30);
893
- }
894
- } else {
895
- pool.state.authFailCounts.delete(targetRef);
896
- }
897
- };
898
-
899
- for (let attempt = 0; attempt < attemptList.length; attempt++) {
900
- let yielded = false;
901
- let switching = false;
902
- let inner;
903
- try {
904
- // mark the internal dispatch so the interceptor does not re-rotate
905
- inner = dispatchStorage.run(reqStore, () => ctx.llm.stream({ ...options, [MARKER]: true }));
906
- } catch (e) {
907
- const curRef = reqStore.pickedRef ?? pool.state.lastUsed;
908
- penalizeRef(curRef, e?.code ?? 'TRANSPORT', String(e?.message ?? ''));
909
- lastFailure = finishError(e?.code ?? 'TRANSPORT',
910
- `dsh-key-rotation: dispatch failed: ${String(e?.message ?? e)}`);
911
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(curRef ?? '?')} threw ${String(e?.code ?? e?.message ?? e)}`);
912
- continue;
913
- }
914
-
915
- const _pickedRef = reqStore.pickedRef ?? pool.state.lastUsed;
916
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.acquire(_pickedRef);
917
- try {
918
- for await (const chunk of inner) {
919
- // Only actual content deltas lock the stream (no more rotation).
920
- // Structural/metadata chunks (block-start/end, usage) do not.
921
- if (chunk && (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta' || chunk.type === 'tool-call-delta')) {
922
- yielded = true;
923
- yield chunk;
924
- continue;
925
- }
926
- if (chunk && chunk.type === 'finish') {
927
- const kind = chunk.reason?.kind;
928
- const failure = chunk.reason?.failure;
929
- const code = failure?.code;
930
- const message = failure?.message ?? '';
931
- const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
932
- const switchable = !yielded && kind === 'error' && isSwitchableError(failure, effectiveSwitchCodes);
933
- const activeRef = reqStore.pickedRef ?? pool.state.lastUsed;
934
- if (switchable) {
935
- penalizeRef(activeRef, code ?? 'UNKNOWN', message);
936
- pool.state.switches = (pool.state.switches ?? 0) + 1;
937
- pool.state.lastReason = String(code ?? 'UNKNOWN');
938
- pool.state.lastSwitchAt = Date.now();
939
- lastFailure = chunk;
940
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(activeRef ?? '?')} failed (${String(code)} ${String(message).slice(0, 100)}) - next key`);
941
- // #216: per-switch webhook (opt-in switchNotify), deduped per provider
942
- if (switchNotify && activeRef) {
943
- notifySwitch(runtime0, pool, {
944
- provider: options.provider,
945
- from: activeRef,
946
- code: String(code ?? 'UNKNOWN'),
947
- at: pool.state.lastSwitchAt,
948
- });
949
- }
950
- switching = true;
951
- break;
952
- }
953
- // cost tracking if provider returns usage.cost
954
- const todayIso = activeRef ? new Date().toISOString().slice(0, 10) : undefined;
955
- if (chunk.usage?.cost != null && activeRef) {
956
- const c = Number(chunk.usage.cost);
957
- if (!isNaN(c)) {
958
- if (!pool.state.costPerKey) pool.state.costPerKey = new Map();
959
- pool.state.costPerKey.set(activeRef, (pool.state.costPerKey.get(activeRef) ?? 0) + c);
960
- // #208: cost per day per key (mirrors usageDays) for budget checks
961
- if (!pool.state.costDays) pool.state.costDays = new Map();
962
- const cMap = pool.state.costDays.get(activeRef) || new Map();
963
- cMap.set(todayIso, (cMap.get(todayIso) ?? 0) + c);
964
- pool.state.costDays.set(activeRef, cMap);
965
- }
966
- }
967
- // Usage by day (#119)
968
- if (activeRef) {
969
- if (!pool.state.usageDays) pool.state.usageDays = new Map();
970
- const dayMap = pool.state.usageDays.get(activeRef) || new Map();
971
- dayMap.set(todayIso, (dayMap.get(todayIso) ?? 0) + 1);
972
- pool.state.usageDays.set(activeRef, dayMap);
973
- }
974
- // Per-model request detail (#121)
975
- if (activeRef && options.model) {
976
- if (!pool.state.byModel) pool.state.byModel = new Map();
977
- let byRef = pool.state.byModel.get(activeRef);
978
- if (!byRef) { byRef = new Map(); pool.state.byModel.set(activeRef, byRef); }
979
- byRef.set(options.model, (byRef.get(options.model) ?? 0) + 1);
980
- }
981
- // Proactive rate-limit (#115): if response headers say this key is near
982
- // its quota, cool it down so the NEXT request starts on a different key.
983
- // We do NOT re-run this (already successful) request — that would double-send.
984
- const rate = extractRateLimit(chunk?.metadata?.headers ?? chunk?.headers);
985
- if (rate && activeRef) {
986
- if (isRateLimited(rate, rateLimitThreshold ?? 0.1)) {
987
- const cool = rate.reset && rate.reset > Date.now() ? (rate.reset - Date.now()) : pool.cooldownMs;
988
- recordFailure(pool, activeRef, Date.now(), cool, pool.maxCooldownMs);
989
- pushEvent(pool, activeRef, 'RATE_LIMIT', cool);
990
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${activeRef} near quota (remaining ${String(rate.remaining)}/${String(rate.limit)}) — next request will rotate`);
991
- }
992
- }
993
- // #7: persist quota snapshot regardless of threshold (so dashboard widget can show it).
994
- if (rate && activeRef && Number.isFinite(rate.remaining)) {
995
- quotaStore.set(activeRef, { remaining: rate.remaining, limit: rate.limit, reset: rate.reset, at: Date.now() });
996
- }
997
- yield chunk;
998
- recordLatency(pool, reqStore);
999
- return;
1000
- }
1001
- yield chunk;
1002
- }
1003
- } catch (e) {
1004
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
1005
- const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
1006
- const activeRef = _pickedRef ?? reqStore.pickedRef ?? pool.state.lastUsed;
1007
- if (!yielded && isSwitchableError(e, effectiveSwitchCodes)) {
1008
- penalizeRef(activeRef, e?.code ?? 'TRANSPORT', String(e?.message ?? e));
1009
- pool.state.switches = (pool.state.switches ?? 0) + 1;
1010
- pool.state.lastReason = String(e?.code ?? 'TRANSPORT');
1011
- pool.state.lastSwitchAt = Date.now();
1012
- lastFailure = finishError(e?.code ?? 'TRANSPORT', String(e?.message ?? e));
1013
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(activeRef ?? '?')} stream threw ${String(e?.code ?? e?.message ?? e)} - failover to next key`);
1014
- if (switchNotify && activeRef) {
1015
- notifySwitch(runtime0, pool, {
1016
- provider: options.provider,
1017
- from: activeRef,
1018
- code: String(e?.code ?? 'TRANSPORT'),
1019
- at: pool.state.lastSwitchAt,
1020
- });
1021
- }
1022
- continue; // Failover to next key!
1023
- }
1024
- yield finishError(e?.code ?? 'TRANSPORT', String(e?.message ?? e));
1025
- return;
1026
- }
1027
-
1028
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
1029
- if (switching) continue; // try the next key
1030
- return; // clean end — served
1031
- }
1032
-
1033
- // pool exhausted — all keys cooling or missing
1034
- pool.state.lastExhaustionAt = Date.now();
1035
- pool.state.exhaustionCount = (pool.state.exhaustionCount ?? 0) + 1;
1036
- console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — all ${pool.refs.length} keys cooling`);
1037
- // notify via extracted helper (see notifyExhaustion above)
1038
- notifyExhaustion(buildRuntime(), pool, { provider: options.provider });
1039
-
1040
- // #194: cross-provider cascade failover (guarded against infinite recursion)
1041
- const runtime = buildRuntime();
1042
- if (!options.__isCascade && Array.isArray(runtime.cascade) && runtime.cascade.length > 0) {
1043
- const pools = runtime.providerToPool;
1044
- const fb = pickCascadeFallback(options.provider, runtime, pools);
1045
- if (fb && fb.pool && fb.pool !== pool) {
1046
- console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — cascading to ${fb.provider}`);
1047
- pool.state.lastReason = 'CASCADE';
1048
- pool.state.lastSwitchAt = Date.now();
1049
- // Re-dispatch on the fallback pool (depth-1 via __isCascade guard)
1050
- const innerCascade = rotate({ ...options, provider: fb.provider, __isCascade: true }, fb.pool);
1051
- for await (const chunk of innerCascade) {
1052
- yield chunk;
1053
- }
1054
- return;
1055
- }
1056
- }
1057
-
1058
- const exhaustionMsg = formatExhaustionMessage(options.provider, pool);
1059
- yield lastFailure ?? finishError('QUOTA', exhaustionMsg);
1060
- })();
1061
- }
1062
-
1063
- // ── status route: what the settings card cannot know on its own ──
1064
- //
1065
- // Reports, per configured provider, which key is in use, which are cooling
1066
- // down and until when, whether an env name resolves to a credential at all
1067
- // (a typo is otherwise silent), and how often rotation has fired.
1068
- //
1069
- // Key VALUES never leave the host — only the boolean fact that one exists.
1070
- ctx.effect(() => ctx.webServer.register({
1071
- kind: 'exact',
1072
- path: STATUS_PATH,
1073
- handler: async (req, res) => {
1074
- if (req.method !== 'GET') {
1075
- json(res, 405, { error: { code: 'method', message: 'GET only' } });
1076
- return;
1077
- }
1078
- if (!isTrustedBridgeRequest(req)) {
1079
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: status is local-only' } });
1080
- return;
1081
- }
1082
- const { poolByRef, providerTags, providerBudgets } = buildRuntime();
1083
- const base = ctx.get('credentials');
1084
- const now = Date.now();
1085
- const latencySloMs = buildRuntime().latencySloMs;
1086
- const seen = new Set();
1087
- const providers = [];
1088
- for (const pool of poolByRef.values()) {
1089
- if (seen.has(pool.base)) continue;
1090
- seen.add(pool.base);
1091
- try {
1092
- const keys = [];
1093
- for (const ref of pool.refs) {
1094
- let present = false;
1095
- let tail = '';
1096
- let source = null;
1097
- let writable = true;
1098
- try {
1099
- // The resolve patch is installed on this same service, so ask for
1100
- // the exact ref: a pool ref would otherwise round-robin to another
1101
- // key and report a missing name as present.
1102
- let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
1103
- present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
1104
- if (present) tail = keyTail(hit.value);
1105
- // fallback: env var bootstrapping (issue #7)
1106
- if (!present) {
1107
- const ev = envValue(ref);
1108
- if (ev !== undefined) { present = true; tail = keyTail(ev); source = 'env'; writable = false; }
1109
- }
1110
- } catch {
1111
- present = false;
1112
- }
1113
- try {
1114
- const described = await base?.describe?.(ref);
1115
- source = described?.source ?? null;
1116
- writable = described?.writable !== false;
1117
- } catch {
1118
- /* describe is optional — the card falls back to editable */
1119
- }
1120
- const until = pool.state.failedUntil.get(ref);
1121
- keys.push({
1122
- ref,
1123
- present,
1124
- tail,
1125
- source,
1126
- writable,
1127
- active: pool.state.lastUsed === ref,
1128
- cooldownMsLeft: until !== undefined && until > now ? until - now : 0,
1129
- // #210: RPM capacity snapshot (null when rpmLimit is off)
1130
- rpm: bucketInfo(pool.state.rpmWindows, ref, pool.rpmLimit, now),
1131
- // #215: effective round-robin weight of this key
1132
- weight: pool.weights?.[pool.refs.indexOf(ref)] ?? 1,
1133
- usage: pool.state.usageCounts?.get(ref) ?? 0,
1134
- byModel: pool.state.byModel?.get(ref) ? Object.fromEntries(pool.state.byModel.get(ref)) : {},
1135
- usageDays: pool.state.usageDays?.get(ref) ? Object.fromEntries(pool.state.usageDays.get(ref)) : {},
1136
- cost: pool.state.costPerKey?.get(ref) ?? 0,
1137
- lastUsedAt: pool.state.lastUsedAt?.get(ref) ?? null,
1138
- expiresAt: pool.expiresAt?.[ref] ?? null,
1139
- expired: pool.expiresAt?.[ref] !== undefined && now >= pool.expiresAt[ref],
1140
- broken: pool.state.brokenUntil?.has(ref) ?? false,
1141
- });
1142
- }
1143
- providers.push({
1144
- provider: pool.base,
1145
- keys,
1146
- tags: providerTags.get(pool.base) ?? [],
1147
- switches: pool.state.switches ?? 0,
1148
- lastReason: pool.state.lastReason ?? null,
1149
- lastSwitchAt: pool.state.lastSwitchAt ?? null,
1150
- lastExhaustionAt: pool.state.lastExhaustionAt ?? null,
1151
- exhaustionCount: pool.state.exhaustionCount ?? 0,
1152
- totalUsage: (() => { let s = 0; if (pool.state.usageCounts) for (const v of pool.state.usageCounts.values()) s += v; return s; })(),
1153
- // #225: aggregate p95 across the pool's keys
1154
- p95: (() => {
1155
- const vals = (pool.refs ?? []).map((r) => latencyHistogram.snapshot(r)).filter((s) => s && s.p95 != null).map((s) => s.p95);
1156
- return vals.length ? Math.round(Math.max(...vals)) : null;
1157
- })(),
1158
- latencySloMs,
1159
- events: (pool.state.events ?? []).slice(-50),
1160
- healthScore: computeHealthScore(pool.state),
1161
- // #208: today/week spend + configured budget for the card
1162
- todayCost: costForDay(pool.state.costDays),
1163
- weeklyCost: costForWeek(pool.state.costDays, now),
1164
- budgetDaily: providerBudgets.get(pool.base)?.costBudgetDaily ?? 0,
1165
- budgetWeekly: providerBudgets.get(pool.base)?.costBudgetWeekly ?? 0,
1166
- pauseOnBudget: providerBudgets.get(pool.base)?.pauseOnBudget ?? false,
1167
- });
1168
- } catch (e) {
1169
- console.warn(`[dsh-key-rotation] status: pool ${pool.base} failed: ${String(e?.message ?? e)} ${e?.stack ?? ''}`);
1170
- providers.push({ provider: pool.base, keys: [], statusError: String(e?.message ?? e) });
1171
- }
1172
- }
1173
- json(res, 200, { providers });
1174
- },
1175
- }), 'dsh-key-rotation: status route');
1176
-
1177
- // #209: usage report - per-key requests/cost over the last N days.
1178
- // ?format=csv returns text/csv; ?days=N window (1..90, default 7).
1179
- ctx.effect(() => ctx.webServer.register({
1180
- kind: 'exact',
1181
- path: USAGE_PATH,
1182
- handler: (req, res) => {
1183
- if (req.method !== 'GET') { json(res, 405, { error: { code: 'method', message: 'GET only' } }); return; }
1184
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: usage is local-only' } }); return; }
1185
- const url = new URL(req.url ?? USAGE_PATH, 'http://localhost');
1186
- const days = Math.min(90, Math.max(1, Number(url.searchParams.get('days')) || 7));
1187
- const csv = url.searchParams.get('format') === 'csv';
1188
- const provider = url.searchParams.get('provider') ?? '';
1189
- const runtime = buildRuntime();
1190
- const now = Date.now();
1191
- const seen = new Set();
1192
- const report = [];
1193
- for (const pool of runtime.poolByRef.values()) {
1194
- if (seen.has(pool.base)) continue;
1195
- seen.add(pool.base);
1196
- if (provider && pool.base !== provider) continue;
1197
- report.push({ provider: pool.base, rows: usageRows(pool, days, now) });
1198
- }
1199
- if (csv) {
1200
- res.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'attachment; filename="dsh-key-rotation-usage.csv"' });
1201
- const parts = [];
1202
- for (const p of report) {
1203
- if (parts.length > 0) parts.push('');
1204
- parts.push('# ' + p.provider);
1205
- parts.push(usageCsv(p.rows));
1206
- }
1207
- res.end(parts.join('\n') + '\n');
1208
- return;
1209
- }
1210
- json(res, 200, { at: now, days, providers: report });
1211
- },
1212
- }), 'dsh-key-rotation: usage route');
1213
-
1214
- // #218: full config snapshot - one JSON file to move between machines.
1215
- // Secret values never travel: only credential/env names. Token fields are
1216
- // exported as empty strings; on import they keep existing values when empty.
1217
- ctx.effect(() => ctx.webServer.register({
1218
- kind: 'exact',
1219
- path: SNAPSHOT_PATH,
1220
- handler: async (req, res) => {
1221
- if (req.method !== 'GET' && req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'GET (export) or POST (import) only' } }); return; }
1222
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: snapshot is local-only' } }); return; }
1223
- if (req.method === 'GET') {
1224
- const descriptor = descriptorOf(ctx, NS);
1225
- const value = descriptor?.value ?? {};
1226
- const exportable = { ...value };
1227
- // token-shaped fields stay empty in the file; refs are names, not secrets
1228
- exportable.webhookActionToken = '';
1229
- json(res, 200, { at: Date.now(), version: 1, snapshot: exportable });
1230
- return;
1231
- }
1232
- // POST = import: { snapshot } -> merge with current section, PUT semantics
1233
- let body;
1234
- try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1235
- const snap = body?.snapshot;
1236
- if (!snap || typeof snap !== 'object' || Array.isArray(snap)) { json(res, 400, { error: { code: 'bad-format', message: 'dsh-key-rotation: POST requires {"snapshot": {...}}' } }); return; }
1237
- // #200 leak guard applies to imported content too
1238
- try {
1239
- const masked = structuredClone(snap);
1240
- if (masked.webhookActionToken) masked.webhookActionToken = '***';
1241
- if (masked.notifyWebhook) masked.notifyWebhook = '***';
1242
- const findings = findSecrets(JSON.stringify(masked));
1243
- if (findings.length > 0) { json(res, 400, { error: { code: 'secret-in-snapshot', message: 'dsh-key-rotation: snapshot carries a live-looking credential', findings } }); return; }
1244
- } catch { /* scanning must never block a valid import */ }
1245
- const settings = ctx.get('settings');
1246
- if (!settings) { json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider' } }); return; }
1247
- const desc = descriptorOf(ctx, NS);
1248
- if (desc === void 0) { json(res, 500, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: namespace missing' } }); return; }
1249
- const cur = desc.value ?? {};
1250
- // empty token fields in the file keep the current values (never wipe a secret)
1251
- const merged = { ...cur, ...snap };
1252
- if (!snap.webhookActionToken) merged.webhookActionToken = cur.webhookActionToken ?? '';
1253
- try {
1254
- await settings.replace(NS, merged, desc.revision);
1255
- const after = descriptorOf(ctx, NS);
1256
- json(res, 200, { ok: true, revision: after?.revision });
1257
- } catch (e) {
1258
- json(res, e?.code === 'SETTINGS_CONFLICT' ? 409 : 400, { error: { code: 'settings-rejected', message: String(e?.message ?? e) } });
1259
- }
1260
- },
1261
- }), 'dsh-key-rotation: snapshot route');
1262
-
1263
- // ── key route: store a key value without leaving the rotation card ──
1264
- //
1265
- // Adding a key used to mean two screens: create the credential elsewhere,
1266
- // then type its env name here. The value is write-only from the browser —
1267
- // it is never sent back, only its last few characters are (see the status
1268
- // route) — and the route is loopback- and same-origin-gated like the config
1269
- // bridge next to it.
1270
- ctx.effect(() => ctx.webServer.register({
1271
- kind: 'exact',
1272
- path: KEY_PATH,
1273
- handler: async (req, res) => {
1274
- if (req.method !== 'PUT' && req.method !== 'DELETE') {
1275
- json(res, 405, { error: { code: 'method', message: 'PUT or DELETE only' } });
1276
- return;
1277
- }
1278
- if (!isTrustedBridgeRequest(req)) {
1279
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: keys are local-only' } });
1280
- return;
1281
- }
1282
- const credentialsService = ctx.get('credentials');
1283
- if (!credentialsService || typeof credentialsService.set !== 'function') {
1284
- json(res, 503, { error: { code: 'no-credentials', message: 'dsh-key-rotation: no credentials service is mounted' } });
1285
- return;
1286
- }
1287
- let body;
1288
- try {
1289
- body = await readJson(req);
1290
- } catch (error) {
1291
- json(res, 400, { error: { code: 'bad-request', message: String(error?.message ?? error) } });
1292
- return;
1293
- }
1294
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1295
- if (!isValidRef(ref)) {
1296
- json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } });
1297
- return;
1298
- }
1299
- try {
1300
- if (req.method === 'DELETE') {
1301
- await credentialsService.unset(ref);
1302
- json(res, 200, { ok: true, ref });
1303
- return;
1304
- }
1305
- const value = typeof body?.value === 'string' ? body.value.trim() : '';
1306
- if (value.length === 0) {
1307
- json(res, 400, { error: { code: 'empty-value', message: 'dsh-key-rotation: an empty key cannot be stored' } });
1308
- return;
1309
- }
1310
- await credentialsService.set(ref, value);
1311
- // #200: leak-detector hint - stored value should look like a credential
1312
- const secretShape = looksLikeApiSecret(value);
1313
- json(res, 200, { ok: true, ref, tail: keyTail(value), looksLikeSecret: secretShape });
1314
- } catch (error) {
1315
- // A ref supplied by the launching environment is read-only, and the
1316
- // service says so in plain words — pass that through to the card.
1317
- json(res, 409, { error: { code: 'write-rejected', message: String(error?.message ?? error) } });
1318
- }
1319
- },
1320
- }), 'dsh-key-rotation: key route');
1321
-
1322
- // ── reset route: clear cooldown for a provider (or a single ref) ──
1323
- ctx.effect(() => ctx.webServer.register({
1324
- kind: 'exact',
1325
- path: RESET_PATH,
1326
- handler: async (req, res) => {
1327
- if (req.method !== 'POST') {
1328
- json(res, 405, { error: { code: 'method', message: 'POST only' } });
1329
- return;
1330
- }
1331
- if (!isTrustedBridgeRequest(req)) {
1332
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: reset is local-only' } });
1333
- return;
1334
- }
1335
- let body;
1336
- try { body = await readJson(req); } catch (e) {
1337
- json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } });
1338
- return;
1339
- }
1340
- const provider = typeof body?.provider === 'string' ? body.provider.trim() : '';
1341
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1342
- if (provider) {
1343
- const st = poolState.get(provider);
1344
- if (!st) { json(res, 404, { error: { code: 'not-found', message: `dsh-key-rotation: no pool for '${provider}'` } }); return; }
1345
- const cleared = st.failedUntil.size;
1346
- st.failedUntil.clear();
1347
- st.failCounts?.clear();
1348
- st.authFailCounts?.clear();
1349
- st.brokenUntil?.clear();
1350
- st.switches = 0; st.lastReason = undefined; st.lastSwitchAt = undefined;
1351
- json(res, 200, { ok: true, provider, cleared });
1352
- return;
1353
- }
1354
- if (ref) {
1355
- let found = false;
1356
- for (const st of poolState.values()) {
1357
- if (st.failedUntil.has(ref) || st.failCounts?.has(ref)) {
1358
- st.failedUntil.delete(ref);
1359
- st.failCounts?.delete(ref);
1360
- st.authFailCounts?.delete(ref);
1361
- st.brokenUntil?.delete(ref);
1362
- if (st.lastUsed === ref) st.lastUsed = undefined;
1363
- found = true; break;
1364
- }
1365
- }
1366
- // idempotent: even if ref was not cooling, report ok if it looks like a valid ref name
1367
- if (!found && !isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1368
- json(res, 200, { ok: true, ref });
1369
- return;
1370
- }
1371
- json(res, 400, { error: { code: 'bad-request', message: 'dsh-key-rotation: POST requires {"provider": "..."} or {"ref": "..."}' } });
1372
- },
1373
- }), 'dsh-key-rotation: reset route');
1374
-
1375
- ctx.effect(() => ctx.webServer.register({
1376
- kind: 'exact',
1377
- path: IMPORT_PATH,
1378
- handler: async (req, res) => {
1379
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1380
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: import is local-only' } }); return; }
1381
- let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1382
- const url = typeof body?.url === 'string' ? body.url.trim() : '';
1383
- if (!url || !url.startsWith('https://')) { json(res, 400, { error: { code: 'bad-url', message: 'dsh-key-rotation: only HTTPS URLs are allowed' } }); return; }
1384
- try {
1385
- const resp = await fetch(url);
1386
- if (!resp.ok) { json(res, 400, { error: { code: 'fetch-failed', message: 'dsh-key-rotation: fetch returned ' + resp.status } }); return; }
1387
- const data = await resp.json();
1388
- if (!Array.isArray(data)) { json(res, 400, { error: { code: 'bad-format', message: 'dsh-key-rotation: expected JSON array of providers' } }); return; }
1389
- const settings = ctx.get('settings');
1390
- if (!settings) { json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider' } }); return; }
1391
- const desc = settings.describe({ redactSecrets: true }).find((c) => c.ns === NS);
1392
- const cur = desc?.value?.providers ?? [];
1393
- const merged = new Map();
1394
- for (const p of cur) if (p && p.provider) merged.set(p.provider, p);
1395
- for (const p of data) if (p && p.provider && typeof p.provider === 'string') merged.set(p.provider, p);
1396
- const mergedArr = [...merged.values()];
1397
- await settings.replace(NS, { ...(desc?.value ?? {}), providers: mergedArr }, desc?.revision);
1398
- json(res, 200, { ok: true, providersImported: data.length, total: mergedArr.length });
1399
- } catch (e) { json(res, 400, { error: { code: 'import-failed', message: String(e?.message ?? e) } }); }
1400
- },
1401
- }), 'dsh-key-rotation: import route');
1402
-
1403
- // Health for external panels (Beszel/Uptime)
1404
- ctx.effect(() => ctx.webServer.register({
1405
- kind: 'exact',
1406
- path: HEALTH_PATH,
1407
- handler: async (req, res) => {
1408
- if (!isTrustedBridgeRequest(req) && req.socket?.remoteAddress !== '127.0.0.1' && req.socket?.remoteAddress !== '::1') { } // allow same-origin already checked
1409
- if (!isTrustedBridgeRequest(req)) {
1410
- // also allow plain loopback without Origin
1411
- if (!isLoopbackAddress(req.socket?.remoteAddress)) { res.writeHead(403); res.end(); return; }
1412
- if (req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); res.end(); return; }
1413
- }
1414
- if (req.method !== 'GET') { json(res, 405, { error: { code: 'method', message: 'GET only' } }); return; }
1415
- const now = Date.now();
1416
- const pools = {};
1417
- let exhaustedAny = false;
1418
- const { poolByRef: pr, providerTags } = buildRuntime();
1419
- const seenH = new Set();
1420
- for (const pool of pr.values()) {
1421
- if (seenH.has(pool.base)) continue;
1422
- seenH.add(pool.base);
1423
- let healthy = 0;
1424
- for (const ref of pool.refs) {
1425
- const until = pool.state.failedUntil.get(ref);
1426
- if (until !== undefined && until > now) continue;
1427
- const exp = pool.expiresAt?.[ref];
1428
- if (exp !== undefined && now >= exp) continue;
1429
- healthy++;
1430
- }
1431
- const total = pool.refs.length;
1432
- const exhausted = healthy === 0 && total > 0;
1433
- if (exhausted) exhaustedAny = true;
1434
- pools[pool.base] = { healthy, total, exhausted, healthScore: computeHealthScore(pool.state) };
1435
- }
1436
- json(res, 200, { status: exhaustedAny ? 'degraded' : 'ok', pools, exhaustedAny, latency: latencyHistogram.snapshotAll(), quota: quotaStore.snapshot() });
1437
- },
1438
- }), 'dsh-key-rotation: health');
1439
-
1440
- // ── test route: dry-run a single key without rotation ──
1441
- ctx.effect(() => ctx.webServer.register({
1442
- kind: 'exact',
1443
- path: TEST_PATH,
1444
- handler: async (req, res) => {
1445
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1446
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: test is local-only' } }); return; }
1447
- let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1448
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1449
- if (!isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1450
- // Optional value for pre-save validation (issue #118)
1451
- const testValue = typeof body?.value === 'string' && body.value.length > 0 ? body.value : undefined;
1452
- const probe = body?.probe === 'models' || body?.probe === 'chat' ? body.probe : undefined;
1453
- const base = ctx.get('credentials');
1454
- try {
1455
- let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
1456
- let present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
1457
- const effectiveValue = testValue || hit?.value;
1458
- const valid = present ? Boolean(effectiveValue && typeof effectiveValue === 'string' && effectiveValue.length > 0) : Boolean(testValue);
1459
- const tail = valid ? keyTail(effectiveValue) : '';
1460
- let source = null;
1461
- try { const d = await base?.describe?.(ref); source = d?.source ?? null; } catch {}
1462
- if (!present && !testValue) { json(res, 200, { ok: false, ref, code: 'no-credential', message: 'no such credential' }); return; }
1463
- if (!present && testValue) { source = 'pre-save'; }
1464
- else if (!present) {
1465
- const ev = envValue(ref);
1466
- if (ev !== undefined) { present = true; json(res, 200, { ok: true, ref, tail: keyTail(ev), source: 'env' }); return; }
1467
- }
1468
- // sandbox probe (models is free; chat is hook-only, see sandbox.js)
1469
- if (probe) {
1470
- const keyForProbe = effectiveValue;
1471
- const runner = ensureSandboxRunner(ctx);
1472
- const result = probe === 'chat' ? await runner.probeChat(ref, keyForProbe) : await runner.probeModels(ref, keyForProbe);
1473
- const cached = { ...result, at: Date.now() };
1474
- lastTestCache.set(ref, cached);
1475
- if (cached.ok) {
1476
- for (const st of poolState.values()) {
1477
- if (st.failedUntil?.has(ref) || st.failCounts?.has(ref) || st.brokenUntil?.has(ref)) {
1478
- st.failedUntil?.delete(ref);
1479
- st.failCounts?.delete(ref);
1480
- st.authFailCounts?.delete(ref);
1481
- st.brokenUntil?.delete(ref);
1482
- }
1483
- }
1484
- }
1485
- json(res, 200, { ok: cached.ok, ref, tail, source, probe, code: cached.code, latencyMs: cached.latencyMs, modelsCount: cached.modelsCount });
1486
- return;
1487
- }
1488
- json(res, 200, { ok: true, ref, tail, source });
1489
- } catch (e) {
1490
- json(res, 200, { ok: false, ref, code: 'error', message: String(e?.message ?? e) });
1491
- }
1492
- },
1493
- }), 'dsh-key-rotation: test route');
1494
-
1495
- // Intercept the llm/stream waterfall: rotate any request whose provider maps
1496
- // to a configured key pool; pass everything else (and internal dispatches)
1497
- // straight through.
1498
- // Read-only cache snapshot for clients (badge polling).
1499
- ctx.effect(() => ctx.webServer.register({
1500
- kind: 'exact',
1501
- path: SANDBOX_CACHE_PATH,
1502
- handler: (req, res) => {
1503
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: cache is local-only' } }); return; }
1504
- json(res, 200, lastTestCache.snapshot());
1505
- },
1506
- }), 'dsh-key-rotation: sandbox cache');
1507
-
1508
-
1509
-
1510
- // #199 webhook-action: interactive webhook buttons call back here.
1511
- // Auth: bearer token from Config (external services like Telegram/Discord
1512
- // cannot be same-origin, so a shared secret is the gate).
1513
- ctx.effect(() => ctx.webServer.register({
1514
- kind: 'exact',
1515
- path: '/dsh-key-rotation/webhook-action',
1516
- handler: async (req, res) => {
1517
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1518
- const runtime = buildRuntime();
1519
- const expected = runtime.webhookActionToken;
1520
- if (!expected) { json(res, 503, { error: { code: 'no-token', message: 'dsh-key-rotation: webhookActionToken is not configured' } }); return; }
1521
- const auth = String(req.headers.authorization ?? '');
1522
- if (auth !== `Bearer ${expected}`) { json(res, 401, { error: { code: 'unauthorized', message: 'dsh-key-rotation: bad webhook action token' } }); return; }
1523
- let body;
1524
- try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1525
- // Accept callback payloads from formatInteractive (Telegram/Discord/Slack) or plain {action}
1526
- let action = typeof body?.action === 'string' ? body.action : '';
1527
- if (!action && typeof body?.data === 'string') {
1528
- try { action = String(JSON.parse(body.data)?.id ?? ''); } catch { action = ''; }
1529
- }
1530
- if (!action && typeof body?.callback_data === 'string') {
1531
- try { action = String(JSON.parse(body.callback_data)?.id ?? ''); } catch { action = ''; }
1532
- }
1533
- // #222: Telegram update envelope {update_id, callback_query:{data}}
1534
- if (!action && typeof body?.callback_query?.data === 'string') {
1535
- try { action = String(JSON.parse(body.callback_query.data)?.id ?? ''); } catch { action = ''; }
1536
- }
1537
- // #222: Telegram setWebhook registration helper
1538
- if (typeof body?.setWebhook === 'object' && body.setWebhook) {
1539
- const botToken = typeof body.setWebhook.botToken === 'string' ? body.setWebhook.botToken : '';
1540
- if (!botToken) { json(res, 400, { error: { code: 'bad-request', message: 'dsh-key-rotation: setWebhook.botToken required' } }); return; }
1541
- // derive the public URL from request headers; explicit URL wins
1542
- const url = typeof body.setWebhook.url === 'string' && body.setWebhook.url ? body.setWebhook.url : `https://${String(req.headers.host ?? '')}/dsh-key-rotation/webhook-action`;
1543
- try {
1544
- const hookRes = await fetch(`https://api.telegram.org/bot${botToken}/setWebhook`, {
1545
- method: 'POST', headers: { 'content-type': 'application/json' },
1546
- body: JSON.stringify({ url, allowed_updates: ['callback_query'] }),
1547
- });
1548
- const hookData = await hookRes.json().catch(() => ({}));
1549
- json(res, 200, { ok: hookRes.ok, url, telegram: hookData });
1550
- } catch (e) {
1551
- json(res, 502, { error: { code: 'telegram-failed', message: String(e?.message ?? e) } });
1552
- }
1553
- return;
1554
- }
1555
- if (!action) { json(res, 400, { error: { code: 'bad-action', message: 'dsh-key-rotation: no action in payload' } }); return; }
1556
- const provider = action.startsWith('pause-') || action.startsWith('reset-') ? action.replace(/^(pause|reset)-/, '') : '';
1557
- try {
1558
- if (action === 'disable-rotation') {
1559
- rotationDisabled = true;
1560
- console.warn('[dsh-key-rotation] rotation DISABLED via webhook action');
1561
- json(res, 200, { ok: true, action });
1562
- return;
1563
- }
1564
- if (action === 'enable-rotation') {
1565
- rotationDisabled = false;
1566
- json(res, 200, { ok: true, action });
1567
- return;
1568
- }
1569
- if (action.startsWith('pause-') || action.startsWith('reset-')) {
1570
- const st = poolState.get(provider);
1571
- if (!st) { json(res, 404, { error: { code: 'not-found', message: `dsh-key-rotation: no pool for '${provider}'` } }); return; }
1572
- if (action.startsWith('pause-')) {
1573
- const until = Date.now() + 3600000; // 1h pause
1574
- for (const ref of (st.failedUntil ? [...st.failedUntil.keys()] : [])) st.failedUntil.set(ref, Math.max(st.failedUntil.get(ref) ?? 0, until));
1575
- // also pause every key currently healthy
1576
- for (const p of buildRuntime().poolByRef.values()) {
1577
- if (p.base !== provider) continue;
1578
- for (const ref of p.refs) st.failedUntil.set(ref, Math.max(st.failedUntil.get(ref) ?? 0, until));
1579
- }
1580
- console.warn(`[dsh-key-rotation] pool ${provider} PAUSED 1h via webhook action`);
1581
- json(res, 200, { ok: true, action, provider, until: Date.now() + 3600000 });
1582
- return;
1583
- }
1584
- const cleared = st.failedUntil.size;
1585
- st.failedUntil.clear(); st.failCounts?.clear(); st.brokenUntil?.clear();
1586
- console.warn(`[dsh-key-rotation] pool ${provider} RESET via webhook action`);
1587
- json(res, 200, { ok: true, action, provider, cleared });
1588
- return;
1589
- }
1590
- json(res, 400, { error: { code: 'unknown-action', message: `dsh-key-rotation: unknown action '${action}'` } });
1591
- } catch (e) {
1592
- json(res, 500, { error: { code: 'action-failed', message: String(e?.message ?? e) } });
1593
- }
1594
- },
1595
- }), 'dsh-key-rotation: webhook-action');
1596
-
1597
-
691
+ // Operational routes (status/usage/snapshot/key/import/test/health/webhook) (#253)
692
+ registerOpsRoutes(ctx, {
693
+ buildRuntime,
694
+ latencyHistogram,
695
+ lastTestCache,
696
+ ensureSandboxRunner,
697
+ poolState,
698
+ getRotationDisabled: () => rotationDisabled,
699
+ setRotationDisabled: (v) => { rotationDisabled = v; },
700
+ });
1598
701
 
1599
702
  ctx.effect(() => ctx.on('llm/stream', (options, next) => {
1600
703
  if (options[MARKER]) return next();
@@ -1603,7 +706,9 @@ export function apply(ctx, config = {}) {
1603
706
  // #195: exact model pool -> longest model-family prefix -> provider pool
1604
707
  const pool = selectPool(modelPoolByProvider, providerToPool, options.provider, options.model);
1605
708
  if (!pool) return next();
1606
- console.warn(`[dsh-key-rotation] rotating ${options.provider}/${options.model} across ${(pool.weightedRefs ?? pool.refs).length} slots (${pool.refs.length} keys)`);
709
+ if (buildRuntime()?.verboseLogging) {
710
+ console.warn(`[dsh-key-rotation] rotating ${options.provider}/${options.model} across ${(pool.weightedRefs ?? pool.refs).length} slots (${pool.refs.length} keys)`);
711
+ }
1607
712
  return rotate(options, pool);
1608
713
  }), 'dsh-key-rotation: llm/stream');
1609
714