dsh-ustc-quota 2.0.4 → 2.0.7

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/client.js CHANGED
@@ -55,7 +55,7 @@ window.__ModuleLoader__.load({
55
55
  return 0;
56
56
  }
57
57
  }
58
- const CLIENT_VERSION = '2.0.4';
58
+ const CLIENT_VERSION = '2.0.7';
59
59
  const UPDATE_INTERVAL_MS = 24 * 60 * 60 * 1000;
60
60
  const CLIENT_VERSION_KEY = `${NS}:client-version`;
61
61
  const CLIENT_RELOAD_KEY = `${NS}:client-reload`;
package/index.js CHANGED
@@ -23,7 +23,7 @@ import { UpdateService } from './update.js';
23
23
  import { keysFromConfig, removeProviderRow, syncKeyRow } from './pool-config.js';
24
24
  import { readKeys as readStoredKeys } from './pool-store.js';
25
25
  import { registerPoolApi } from './pool-api.js';
26
- import { findProfile, retireManager } from './retire.js';
26
+ import { findProfile, profileDirFor, retireManager } from './retire.js';
27
27
 
28
28
  const ROUTE_PATH = '/plugins/dsh-ustc-quota/snapshot'
29
29
  const POOL_CALL_PATH = '/plugins/dsh-ustc-quota/pool/last'
@@ -56,7 +56,11 @@ export function nextSelectionFor(current, keys, sessionId, options = {}) {
56
56
  .filter((entry) => entry && entry.provider === current.provider)
57
57
  .map((entry) => Math.max(0, ...(Array.isArray(entry.windows) ? entry.windows : []).map((window) => (window && typeof window.ratio === 'number' ? window.ratio : 0)), 0))
58
58
  .reduce((a, b) => Math.max(a, b), 0)
59
- if (!delegated && worst < WALL_RATIO) {
59
+ const held = (Array.isArray(keys) ? keys : []).find((entry) => entry && entry.provider === current.provider)
60
+ // A key that is blocked, failing its quota probe or disabled must never be kept: sticky is a
61
+ // cache-affinity preference, not a promise to keep using a broken key.
62
+ const healthy = held !== undefined && held.blocked !== true && held.ok !== false && held.enabled !== false
63
+ if (!delegated && healthy && worst < WALL_RATIO) {
60
64
  // Respect the key this conversation is already on: a manual choice must survive, and a
61
65
  // healthy key must not be abandoned just because another one is quieter.
62
66
  if (typeof sessionId === 'string') poolSticky.set(sessionId, current.provider)
@@ -124,6 +128,23 @@ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
124
128
  * loopback interface must not read the snapshot or trigger an update (DNS rebinding), and
125
129
  * another machine must not borrow the loopback Host name.
126
130
  */
131
+ /**
132
+ * Whether a request came from a page served by this very origin.
133
+ *
134
+ * Comparing only the host let any other loopback page (another port) drive the destructive
135
+ * routes; the port is part of the origin, so it must match too.
136
+ */
137
+ function originAllowed(rawOrigin, rawHost, protocol) {
138
+ if (typeof rawOrigin !== 'string' || rawOrigin === '' || rawOrigin === 'null') return false
139
+ let origin
140
+ try { origin = new URL(rawOrigin) } catch { return false }
141
+ if (typeof rawHost !== 'string' || rawHost === '') return false
142
+ const originPort = origin.port !== '' ? origin.port : (origin.protocol === 'https:' ? '443' : '80')
143
+ const hostPort = rawHost.includes(':') ? rawHost.slice(rawHost.lastIndexOf(':') + 1) : ''
144
+ if (origin.host.toLowerCase() !== rawHost.toLowerCase()) return false
145
+ return originPort === hostPort && (protocol === undefined || origin.protocol === protocol)
146
+ }
147
+
127
148
  export function guardRequest(request) {
128
149
  const raw = request && request.headers ? request.headers.host : ''
129
150
  if (typeof raw !== 'string' || raw === '') return 'untrusted-host'
@@ -163,7 +184,7 @@ function rejectGuard(response, reason) {
163
184
  const UPDATE_PATH = '/plugins/dsh-ustc-quota/update';
164
185
  const UPDATE_APPLY_PATH = '/plugins/dsh-ustc-quota/update/apply';
165
186
  const UPDATE_TOKEN_TTL_MS = 30 * 60 * 1000;
166
- const PLUGIN_VERSION = '2.0.4';
187
+ const PLUGIN_VERSION = '2.0.7';
167
188
  const KEY_INFO_PATH = 'key/info';
168
189
  const USER_INFO_PATH = 'user/info';
169
190
  const DISCOVERY_TTL_MS = 10_000;
@@ -178,9 +199,12 @@ export const inject = ['webServer'];
178
199
  export function apply(ctx, config) {
179
200
  const settings = normalizeConfig(config);
180
201
  const poolProviders = () => new Set(keysFromConfig({ keys: ownKeys() }).map((key) => 'ustc-' + key.id))
202
+ // The file is authoritative once it exists: an explicitly empty list means "no keys", and
203
+ // falling back to the plugin config would resurrect keys the user just deleted.
181
204
  const ownKeys = () => {
182
205
  const stored = readStoredKeys()
183
- if (Array.isArray(stored) && stored.length > 0) return stored
206
+ if (stored.ok === false) return config && Array.isArray(config.keys) ? config.keys : []
207
+ if (stored.reason !== 'absent') return stored.keys
184
208
  return config && Array.isArray(config.keys) ? config.keys : []
185
209
  }
186
210
  const poolKeySource = createPoolKeySource(ctx, ownKeys);
@@ -203,6 +227,11 @@ export function apply(ctx, config) {
203
227
  }
204
228
 
205
229
  let lastPoolMove = null
230
+ const poolMoves = []
231
+ const noteMove = (record) => {
232
+ poolMoves.unshift(record)
233
+ while (poolMoves.length > 40) poolMoves.pop()
234
+ }
206
235
  // Observation only: the waterfall hands us the frozen options and the next() chain, so we
207
236
  // record and pass through. Rewriting here is impossible (the host's fallback keeps the
208
237
  // original options), which is why selection happens through selectModel instead.
@@ -229,6 +258,8 @@ export function apply(ctx, config) {
229
258
  routeBase: '/plugins/dsh-ustc-quota',
230
259
  readKeys: ownKeys,
231
260
  onChange: () => {},
261
+ guard: guardRequest,
262
+ reject: rejectGuard,
232
263
  })
233
264
  // Every agent — top-level or delegated child — gets its key here.
234
265
  //
@@ -252,7 +283,8 @@ export function apply(ctx, config) {
252
283
  ...(decision.reasoningEffort === undefined ? {} : { reasoningEffort: decision.reasoningEffort }),
253
284
  })
254
285
  }
255
- lastPoolMove = { sessionId, from: current.provider, to: decision.provider, reason: decision.reason, changed: decision.changed, step, at: Date.now() }
286
+ lastPoolMove = { sessionId, from: current.provider, to: decision.provider, reason: decision.reason, changed: decision.changed, delegated: depth > 0, depth, step, at: Date.now() }
287
+ noteMove(lastPoolMove)
256
288
  }
257
289
  } catch { /* never break a step */ }
258
290
  return next()
@@ -272,7 +304,7 @@ export function apply(ctx, config) {
272
304
  const rotateDefault = async () => {
273
305
  try {
274
306
  const snapshot = await reader.snapshot(false, 'zh')
275
- const pick = pickPoolKey(snapshot && snapshot.keys, null)
307
+ const pick = pickPoolKey(snapshot && snapshot.keys, null, poolProviders())
276
308
  if (pick === null) return
277
309
  const editor = ctx.get('configEditor')
278
310
  if (!editor || typeof editor.configuration !== 'function' || typeof editor.edit !== 'function') return
@@ -314,7 +346,7 @@ export function apply(ctx, config) {
314
346
  kind: 'exact',
315
347
  path: '/plugins/dsh-ustc-quota/pool/last',
316
348
  handler: guarded((request, response) => {
317
- const body = JSON.stringify({ ok: true, last: lastCall, move: lastPoolMove })
349
+ const body = JSON.stringify({ ok: true, last: lastCall, move: lastPoolMove, moves: poolMoves.slice(0, 25) })
318
350
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
319
351
  response.end(body)
320
352
  }, ['GET']),
@@ -373,17 +405,11 @@ export function apply(ctx, config) {
373
405
  ok: true,
374
406
  rawKeys: listed && typeof listed === 'object' ? Object.keys(listed).slice(0, 12) : typeof listed,
375
407
  count: items.length,
376
- sessions: items.slice(0, 50).map((item) => {
377
- const proj = item && item.projections
378
- return {
379
- id: item && item.sessionId ? item.sessionId : null,
380
- blank: item && item.blank === true,
381
- selection: agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(proj),
382
- projType: proj === null || proj === undefined ? String(proj) : (proj instanceof Map ? 'Map' : Object.prototype.toString.call(proj)),
383
- projKeys: proj instanceof Map ? [...proj.keys()].slice(0, 8) : (proj && typeof proj === 'object' ? Object.keys(proj).slice(0, 8) : []),
384
- projSample: (() => { try { return JSON.stringify(proj instanceof Map ? [...proj.values()] : proj).slice(0, 240) } catch { return 'unserializable' } })(),
385
- }
386
- }),
408
+ sessions: items.slice(0, 50).map((item) => ({
409
+ id: item && item.sessionId ? item.sessionId : null,
410
+ blank: item && item.blank === true,
411
+ selection: agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(item && item.projections),
412
+ })),
387
413
  })
388
414
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
389
415
  response.end(body)
@@ -398,6 +424,7 @@ export function apply(ctx, config) {
398
424
  const controller = ctx.get('sessionController')
399
425
  const migrated = []
400
426
  const failed = []
427
+ const skipped = []
401
428
  try {
402
429
  if (!controller || typeof controller.list !== 'function' || typeof controller.selectModel !== 'function') {
403
430
  throw new Error('no-session-controller')
@@ -414,9 +441,15 @@ export function apply(ctx, config) {
414
441
  : Array.isArray(envelope) ? envelope : []
415
442
  for (const item of items) {
416
443
  const selection = agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(item && item.projections)
417
- if (selection === null || selection.provider !== 'ustc-lb') continue
418
444
  const sessionId = item && item.sessionId ? item.sessionId : null
419
445
  if (sessionId === null) continue
446
+ if (selection === null) {
447
+ // An unreadable selection is not proof the conversation is safe: retiring the old
448
+ // row now would break its next turn. Report it so the caller can refuse to retire.
449
+ skipped.push({ sessionId, reason: 'selection-unreadable' })
450
+ continue
451
+ }
452
+ if (selection.provider !== 'ustc-lb') continue
420
453
  try {
421
454
  await controller.selectModel({
422
455
  sessionId,
@@ -432,7 +465,7 @@ export function apply(ctx, config) {
432
465
  } catch (error) {
433
466
  failed.push({ reason: String(error && (error.message || error)).slice(0, 160) })
434
467
  }
435
- const body = JSON.stringify({ ok: failed.length === 0, migrated, failed })
468
+ const body = JSON.stringify({ ok: failed.length === 0 && skipped.length === 0, migrated, failed, skipped })
436
469
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
437
470
  response.end(body)
438
471
  })()
@@ -451,6 +484,11 @@ export function apply(ctx, config) {
451
484
  if (!controller || typeof controller.create !== 'function' || typeof controller.prompt !== 'function') {
452
485
  throw new Error('no-session-controller')
453
486
  }
487
+ // Callers may supply their own probe prompt (base64, because HTTP headers are
488
+ // latin1): that is how a delegation can be triggered without driving the UI.
489
+ const probeText = typeof request.headers['x-probe-b64'] === 'string' && request.headers['x-probe-b64'] !== ''
490
+ ? Buffer.from(request.headers['x-probe-b64'], 'base64').toString('utf8')
491
+ : '自动验收:请只回复 OK'
454
492
  const created = await controller.create({})
455
493
  const sessionId = created && created.sessionId ? created.sessionId : null
456
494
  if (sessionId === null) throw new Error('create-returned-no-session')
@@ -459,10 +497,25 @@ export function apply(ctx, config) {
459
497
  requestId: 'lb-probe-' + Date.now(),
460
498
  sessionId,
461
499
  mode: 'queue',
462
- content: [{ type: 'text', text: '自动验收:请只回复 OK' }],
500
+ content: [{ type: 'text', text: probeText }],
463
501
  }, new AbortController().signal)
464
502
  result.accepted = accepted !== null && accepted !== undefined
465
- result.ok = true
503
+ // Accepted only means "queued". A probe that reports success before the turn runs is
504
+ // exactly how a broken pool looks healthy, so wait for the agent to go idle and report
505
+ // what actually happened.
506
+ const agents = ctx.get('agents')
507
+ const deadline = Date.now() + 90_000
508
+ let state = 'unknown'
509
+ while (Date.now() < deadline) {
510
+ const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : null
511
+ if (agent === null || agent === undefined) break
512
+ state = typeof agent.status === 'string' ? agent.status : 'unknown'
513
+ if (state !== 'running') break
514
+ await new Promise((resolve) => setTimeout(resolve, 1000))
515
+ }
516
+ result.state = state
517
+ result.last = lastCall !== null && lastCall.sessionId === sessionId ? lastCall : null
518
+ result.ok = result.accepted && (state === 'idle' || state === 'unknown')
466
519
  } catch (error) {
467
520
  result.reason = String(error && (error.message || error)).slice(0, 160)
468
521
  }
@@ -478,10 +531,42 @@ export function apply(ctx, config) {
478
531
  path: '/plugins/dsh-ustc-quota/pool/retire-legacy',
479
532
  handler: guarded((request, response) => {
480
533
  void (async () => {
481
- const profile = findProfile()
482
- const result = profile === null ? { profile: null, reason: 'profile-not-found' } : retireManager(profile)
534
+ // Retiring rewrites a profile manifest, so the caller must say which profile. Guessing
535
+ // from the filesystem hit a different profile in practice (a link: install makes the
536
+ // plugin directory ambiguous), which would damage an unrelated installation.
537
+ let requested = null
538
+ try { requested = new URL(request.url, 'http://127.0.0.1').searchParams.get('profile') } catch { requested = null }
539
+ const profile = requested === null ? null : profileDirFor(requested)
540
+ if (profile === null) {
541
+ response.writeHead(400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
542
+ response.end(JSON.stringify({ ok: false, reason: 'profile-required', hint: 'append ?profile=<name>' }))
543
+ return
544
+ }
545
+ // Retiring removes the adapter an unmigrated conversation still points at, so the
546
+ // caller must have migrated first and say so.
547
+ let confirmed = false
548
+ try { confirmed = new URL(request.url, 'http://127.0.0.1').searchParams.get('migrated') === '1' } catch { confirmed = false }
549
+ let lingering = []
550
+ try {
551
+ const controller = ctx.get('sessionController')
552
+ if (controller && typeof controller.list === 'function') {
553
+ const listed = await controller.list(undefined)
554
+ const envelope = listed && typeof listed === 'object' && listed.items !== undefined ? listed.items : listed
555
+ const items = Array.isArray(envelope) ? envelope : []
556
+ for (const item of items) {
557
+ const selection = agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(item && item.projections)
558
+ if (selection !== null && selection.provider === PROVIDER) lingering.push(item.sessionId)
559
+ }
560
+ }
561
+ } catch { lingering = [] }
562
+ if (lingering.length > 0 || confirmed !== true) {
563
+ response.writeHead(409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
564
+ response.end(JSON.stringify({ ok: false, reason: lingering.length > 0 ? 'legacy-sessions-remain' : 'migration-not-confirmed', lingering }))
565
+ return
566
+ }
567
+ const result = retireManager(profile)
483
568
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
484
- response.end(JSON.stringify({ ok: profile !== null, ...result }))
569
+ response.end(JSON.stringify({ ok: result.manifest || result.patch || result.nodeModules, ...result }))
485
570
  })()
486
571
  }, ['POST']),
487
572
  }), 'dsh-ustc-quota: retire legacy pool')
@@ -491,7 +576,10 @@ export function apply(ctx, config) {
491
576
  path: '/plugins/dsh-ustc-quota/pool/cleanup',
492
577
  handler: guarded((request, response) => {
493
578
  void (async () => {
494
- const keep = new Set(ownKeys().map((key) => 'ustc-' + String(key.id)))
579
+ // Normalized ids match the rows that were actually written, and the legacy bridge row is
580
+ // kept until every conversation has moved off it.
581
+ const keep = new Set(keysFromConfig({ keys: ownKeys() }).map((key) => 'ustc-' + key.id))
582
+ keep.add(PROVIDER)
495
583
  const editor = ctx.get('configEditor')
496
584
  let rows = []
497
585
  try { rows = editor && typeof editor.configuration === 'function' ? editor.configuration() : [] } catch { rows = [] }
@@ -510,7 +598,8 @@ export function apply(ctx, config) {
510
598
  removed.push({ providerId, ...result })
511
599
  }
512
600
  }
513
- const body = JSON.stringify({ ok: true, removed })
601
+ const failed = removed.filter((entry) => entry.ok !== true && entry.reason !== 'not-pool-owned')
602
+ const body = JSON.stringify({ ok: failed.length === 0, removed })
514
603
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
515
604
  response.end(body)
516
605
  })()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ustc-quota",
3
- "version": "2.0.4",
3
+ "version": "2.0.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Live 3h/12h/24h USTC token quota card in the DSH sidebar (works with the USTC TokenWorks distribution).",
package/pool-api.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // The pool is no longer a proxy: a key is "using it" means the conversation selected the
4
4
  // native provider row this module writes. These routes only maintain that list.
5
5
 
6
- import { readKeys as readStoredKeys, writeKeys as writeStoredKeys } from './pool-store.js'
6
+ import { readKeys as readStoredKeys, withKeyLock, writeKeys as writeStoredKeys } from './pool-store.js'
7
7
  import {
8
8
  PI_AI_PLUGIN,
9
9
  RESERVED_KEY_IDS,
@@ -52,18 +52,55 @@ export function idForLabel(label) {
52
52
 
53
53
  /** Persist the key list to the plugin's own store. */
54
54
  export async function persistKeys(ctx, mutate) {
55
- const base = readStoredKeys()
56
- const next = mutate(base.map((key) => Object.assign({}, key)))
57
- if (!Array.isArray(next)) return { ok: false, reason: 'mutation did not return a key list' }
58
- const written = writeStoredKeys(next)
59
- if (written.ok !== true) return { ok: false, reason: written.reason }
60
- return { ok: true, keys: next }
55
+ const locked = withKeyLock(() => {
56
+ const current = readStoredKeys()
57
+ if (current.ok === false) return { ok: false, reason: 'store-' + current.reason }
58
+ const next = mutate(current.keys.map((key) => Object.assign({}, key)))
59
+ if (!Array.isArray(next)) return { ok: false, reason: 'mutation did not return a key list' }
60
+ const written = writeStoredKeys(next)
61
+ if (written.ok !== true) return { ok: false, reason: written.reason }
62
+ return { ok: true, keys: next }
63
+ })
64
+ if (locked.ok !== true) return { ok: false, reason: locked.reason }
65
+ return locked.value
66
+ }
67
+
68
+ /** Which provider row (other than `allowRow`) already points at this credential ref. */
69
+ export function credentialOwner(ctx, ref, allowRow) {
70
+ try {
71
+ const editor = ctx.get('configEditor')
72
+ if (!editor || typeof editor.configuration !== 'function') return null
73
+ for (const row of editor.configuration()) {
74
+ if (!row || !row.entry || !row.entry.options || row.entry.options.name !== PI_AI_PLUGIN) continue
75
+ const providers = row.entry.options.config && row.entry.options.config.providers
76
+ if (!providers || typeof providers !== 'object') continue
77
+ for (const [providerId, definition] of Object.entries(providers)) {
78
+ if (providerId === allowRow) continue
79
+ const owner = definition && typeof definition.apiKeyEnv === 'string' ? definition.apiKeyEnv : ''
80
+ if (owner === ref) return providerId
81
+ }
82
+ }
83
+ return null
84
+ } catch { return null }
61
85
  }
62
86
 
63
87
  export function registerPoolApi(ctx, options) {
64
88
  const base = options && typeof options.routeBase === 'string' ? options.routeBase : '/plugins/dsh-ustc-quota'
65
89
  const readKeys = options && typeof options.readKeys === 'function' ? options.readKeys : () => []
66
90
  const changed = options && typeof options.onChange === 'function' ? options.onChange : () => {}
91
+ // The host does not authenticate plugin routes, so every management route repeats the same
92
+ // Host/peer check and a method whitelist: without it any loopback page could add or delete keys.
93
+ const guard = options && typeof options.guard === 'function' ? options.guard : null
94
+ const deny = options && typeof options.reject === 'function' ? options.reject : null
95
+ const gate = (methods, handler) => (request, response) => {
96
+ if (guard !== null) {
97
+ const reason = guard(request)
98
+ if (reason !== null) { if (deny !== null) deny(response, reason); else json(response, { ok: false, reason }, 403); return }
99
+ }
100
+ const method = typeof request.method === 'string' ? request.method.toUpperCase() : 'GET'
101
+ if (!methods.includes(method)) { json(response, { ok: false, reason: 'method-not-allowed' }, 405); return }
102
+ return handler(request, response)
103
+ }
67
104
 
68
105
  const list = async () => keysFromConfig({ keys: readKeys() })
69
106
 
@@ -73,20 +110,43 @@ export function registerPoolApi(ctx, options) {
73
110
  const label = normalizeLabel(body.label ?? body.name ?? '')
74
111
  const secret = typeof body.secret === 'string' ? body.secret.trim() : ''
75
112
  if (label === '' || secret === '') { json(response, { ok: false, reason: 'label-and-secret-required' }, 400); return }
113
+ // A control character makes the credential unusable later: the Authorization header is built
114
+ // from it and fetch rejects invalid header values, so the key would silently never work.
115
+ if (/[\u0000-\u001f\u007f]/.test(secret) || secret.length > 4096) {
116
+ json(response, { ok: false, reason: 'invalid-secret' }, 400)
117
+ return
118
+ }
76
119
  const id = idForLabel(label)
77
120
  if (id === '') { json(response, { ok: false, reason: 'reserved-key-id' }, 400); return }
78
121
  const ref = refFor(label)
79
122
  const store = ctx.get('credentials')
80
123
  if (!store || typeof store.set !== 'function') { json(response, { ok: false, reason: 'credentials-unavailable' }, 503); return }
124
+ // Refuse to silently overwrite a credential another provider already uses: the user may be
125
+ // managing that ref by hand, and a rename would strand their provider row.
126
+ const occupiedBy = credentialOwner(ctx, ref, 'ustc-' + id)
127
+ if (occupiedBy !== null && body.overwrite !== true) {
128
+ json(response, { ok: false, reason: 'credential-in-use', owner: occupiedBy }, 409)
129
+ return
130
+ }
81
131
  try { await store.set(ref, secret) } catch { json(response, { ok: false, reason: 'credential-write-failed' }, 500); return }
82
132
  const persisted = await persistKeys(ctx, (keys) => {
83
133
  const rest = keys.filter((key) => String(key.id) !== id && String(key.credential) !== ref)
84
134
  rest.push({ id, label, credential: ref })
85
135
  return rest
86
136
  })
87
- if (persisted.ok !== true) { json(response, { ok: false, reason: persisted.reason }, 500); return }
137
+ const rollback = async () => {
138
+ try { if (typeof store.unset === 'function') await store.unset(ref) } catch { /* best effort */ }
139
+ }
140
+ if (persisted.ok !== true) { await rollback(); json(response, { ok: false, reason: persisted.reason }, 500); return }
88
141
  const row = await syncKeyRow(ctx, { id, label, ref })
89
- if (row.ok !== true) { json(response, { ok: false, reason: row.reason, key: { id, label, credential: ref } }, 500); return }
142
+ if (row.ok !== true) {
143
+ // Undo the list entry and the secret so a failed save cannot leave a key that the pool
144
+ // advertises but no provider row serves.
145
+ await persistKeys(ctx, (keys) => keys.filter((key) => String(key.id) !== id))
146
+ await rollback()
147
+ json(response, { ok: false, reason: row.reason, key: { id, label, credential: ref } }, 500)
148
+ return
149
+ }
90
150
  changed()
91
151
  json(response, { ok: true, key: { id, label, credential: ref } })
92
152
  }
@@ -101,9 +161,17 @@ export function registerPoolApi(ctx, options) {
101
161
  if (target === undefined) { json(response, { ok: false, reason: 'unknown-key' }, 404); return }
102
162
  const persisted = await persistKeys(ctx, (keys) => keys.filter((key) => String(key.id) !== id))
103
163
  if (persisted.ok !== true) { json(response, { ok: false, reason: persisted.reason }, 500); return }
104
- await syncKeyRow(ctx, { id, label: target.label, ref: target.credential, remove: true })
164
+ const row = await syncKeyRow(ctx, { id, label: target.label, ref: target.credential, remove: true })
165
+ // The secret must not stay behind: a deleted key whose credential still resolves can be
166
+ // re-adopted by a later import and keep spending quota.
167
+ let credentialRemoved = false
168
+ const store = ctx.get('credentials')
169
+ const ref = typeof target.credential === 'string' ? target.credential : ''
170
+ if (ref.startsWith('USTC_POOL_') && store && typeof store.unset === 'function') {
171
+ try { await store.unset(ref); credentialRemoved = true } catch { credentialRemoved = false }
172
+ }
105
173
  changed()
106
- json(response, { ok: true, removed: id })
174
+ json(response, { ok: row.ok === true || row.keep === true, removed: id, credentialRemoved, row })
107
175
  }
108
176
 
109
177
  const importKeys = async (request, response) => {
@@ -125,6 +193,10 @@ export function registerPoolApi(ctx, options) {
125
193
  // whoever wrote it. Deriving the id from the credential ref turned USTC_API_KEY into
126
194
  // "api_key" and produced a second provider row for the same key.
127
195
  if (ref === '' || ref === 'USTC_POOL_LB_EDGE_TOKEN') continue
196
+ // Only providers that talk to the USTC gateway may be adopted: importing a row that
197
+ // points elsewhere would send that key to the USTC quota endpoints.
198
+ const baseUrl = definition && typeof definition.baseURL === 'string' ? definition.baseURL : ''
199
+ if (baseUrl !== '' && !/^https?:\/\/api\.llm\.ustc\.edu\.cn(?:\/|$)/i.test(baseUrl)) continue
128
200
  const bare = providerId.startsWith('ustc-') ? providerId.slice(5) : ''
129
201
  if (bare === '' || bare === 'lb') continue
130
202
  candidates.set(bare, { ref, label: definition && typeof definition.displayName === 'string' ? definition.displayName : bare })
@@ -154,24 +226,24 @@ export function registerPoolApi(ctx, options) {
154
226
  ctx.effect(() => ctx.webServer.register({
155
227
  kind: 'exact',
156
228
  path: base + '/keys',
157
- handler: (request, response) => { void (async () => json(response, { ok: true, keys: await list() }))() },
229
+ handler: gate(['GET'], (request, response) => { void (async () => json(response, { ok: true, keys: await list() }))() }),
158
230
  }), 'dsh-ustc-quota: key list')
159
231
 
160
232
  ctx.effect(() => ctx.webServer.register({
161
233
  kind: 'exact',
162
234
  path: base + '/key',
163
- handler: (request, response) => { void saveKey(request, response) },
235
+ handler: gate(['POST'], (request, response) => { void saveKey(request, response) }),
164
236
  }), 'dsh-ustc-quota: key save')
165
237
 
166
238
  ctx.effect(() => ctx.webServer.register({
167
239
  kind: 'exact',
168
240
  path: base + '/key/delete',
169
- handler: (request, response) => { void deleteKey(request, response) },
241
+ handler: gate(['POST'], (request, response) => { void deleteKey(request, response) }),
170
242
  }), 'dsh-ustc-quota: key delete')
171
243
 
172
244
  ctx.effect(() => ctx.webServer.register({
173
245
  kind: 'exact',
174
246
  path: base + '/key/import',
175
- handler: (request, response) => { void importKeys(request, response) },
247
+ handler: gate(['POST'], (request, response) => { void importKeys(request, response) }),
176
248
  }), 'dsh-ustc-quota: key import')
177
249
  }
package/pool-store.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // restart discarded, which silently emptied the pool. A small JSON file next to the host's
5
5
  // home is boring and survives restarts.
6
6
 
7
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
7
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
8
8
  import { homedir } from 'node:os'
9
9
  import { dirname, join } from 'node:path'
10
10
 
@@ -15,16 +15,37 @@ export function keysFilePath() {
15
15
  return join(home, 'dsh-ustc-quota.keys.json')
16
16
  }
17
17
 
18
+ /**
19
+ * Read the stored key list.
20
+ *
21
+ * "No file yet" and "the file is broken" must not look the same: treating a parse or permission
22
+ * failure as an empty pool silently rewrites it with nothing on the next save. Returns
23
+ * `{ ok, keys, reason }`; only ENOENT is an ordinary empty list.
24
+ */
18
25
  export function readKeys() {
26
+ const file = keysFilePath()
27
+ let raw
28
+ try {
29
+ raw = readFileSync(file, 'utf8')
30
+ } catch (error) {
31
+ const code = error && error.code ? error.code : ''
32
+ if (code === 'ENOENT') return { ok: true, keys: [], reason: 'absent' }
33
+ return { ok: false, keys: [], reason: 'unreadable:' + code }
34
+ }
19
35
  try {
20
- const raw = readFileSync(keysFilePath(), 'utf8')
21
36
  const parsed = JSON.parse(raw)
22
- return parsed && Array.isArray(parsed.keys) ? parsed.keys : []
37
+ if (!parsed || !Array.isArray(parsed.keys)) return { ok: false, keys: [], reason: 'malformed' }
38
+ return { ok: true, keys: parsed.keys, reason: 'ok' }
23
39
  } catch {
24
- return []
40
+ return { ok: false, keys: [], reason: 'malformed' }
25
41
  }
26
42
  }
27
43
 
44
+ /** True when a key file exists at all, regardless of whether it parses. */
45
+ export function keysFileExists() {
46
+ return existsSync(keysFilePath())
47
+ }
48
+
28
49
  export function writeKeys(keys) {
29
50
  const file = keysFilePath()
30
51
  const body = JSON.stringify({ version: 1, keys: Array.isArray(keys) ? keys : [] }, null, 2) + '\n'
@@ -38,3 +59,39 @@ export function writeKeys(keys) {
38
59
  return { ok: false, reason: String(error && (error.message || error)).slice(0, 160) }
39
60
  }
40
61
  }
62
+
63
+ /**
64
+ * Run a read-modify-write of the key list under an exclusive lock file.
65
+ *
66
+ * Two DSH processes (or two profiles sharing DSH_HOME) can add keys at the same time; without
67
+ * a lock the later writer silently replaces the earlier one's list, because the whole file is
68
+ * rewritten. The lock is a sibling file created with O_EXCL and retried briefly.
69
+ */
70
+ export function withKeyLock(task, options = {}) {
71
+ const file = keysFilePath() + '.lock'
72
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 2000
73
+ const started = Date.now()
74
+ let handle = null
75
+ for (;;) {
76
+ try {
77
+ handle = openSync(file, 'wx')
78
+ break
79
+ } catch (error) {
80
+ const code = error && error.code ? error.code : ''
81
+ if (code !== 'EEXIST') return { ok: false, reason: 'lock-unavailable:' + code, value: null }
82
+ // A crashed writer leaves the lock behind; treat a stale one as reclaimable.
83
+ try {
84
+ if (Date.now() - statSync(file).mtimeMs > 15000) { try { unlinkSync(file) } catch { /* ignore */ } }
85
+ } catch { /* ignore */ }
86
+ if (Date.now() - started > timeoutMs) return { ok: false, reason: 'lock-timeout', value: null }
87
+ const until = Date.now() + 25
88
+ while (Date.now() < until) { /* tiny spin; no timers in a lock helper */ }
89
+ }
90
+ }
91
+ try {
92
+ return { ok: true, reason: 'ok', value: task() }
93
+ } finally {
94
+ try { closeSync(handle) } catch { /* ignore */ }
95
+ try { unlinkSync(file) } catch { /* ignore */ }
96
+ }
97
+ }
package/retire.js CHANGED
@@ -10,6 +10,15 @@ import { dirname, join, resolve } from 'node:path'
10
10
  import { fileURLToPath } from 'node:url'
11
11
 
12
12
  export const MANAGER_PACKAGE = 'dsh-ustc-provider-manager'
13
+ /** The patch entry id: profiles use the short form while package.json uses the scoped name. */
14
+ export const MANAGER_ENTRY_ID = 'ustc-provider-manager'
15
+
16
+ /** Write a file atomically: temp in the same directory, then rename over the target. */
17
+ function writeAtomic(path, text) {
18
+ const tmp = path + '.tmp-' + process.pid
19
+ writeFileSync(tmp, text, 'utf8')
20
+ renameSync(tmp, path)
21
+ }
13
22
 
14
23
  function stamp() {
15
24
  const now = new Date()
@@ -46,10 +55,45 @@ export function stripManifest(text) {
46
55
  return changed ? JSON.stringify(parsed, null, 2) + '\n' : null
47
56
  }
48
57
 
49
- /** Remove the manager's entry (and its indented block) from a patch document. */
58
+ /**
59
+ * Remove the manager's entry (and its indented block) from a patch document.
60
+ *
61
+ * A YAML parser would be ideal, but the patch is a hand-edited list and the plugin ships no
62
+ * parser; so this walks the document line by line, recognises an entry whose id or name names
63
+ * the manager, and drops that entry's whole block (including blank lines and nested items).
64
+ */
50
65
  export function stripPatchEntry(text) {
51
- const pattern = /^- id: ustc-provider-manager\r?\n(?:[ \t]+.*\r?\n)*/m
52
- return pattern.test(text) ? text.replace(pattern, '') : null
66
+ const lines = String(text).split(/\r?\n/)
67
+ const out = []
68
+ let removed = false
69
+ let dropping = false
70
+ const namesManager = (line) => {
71
+ // Accept "- id: x", "- id: x", " id: x", quoted values and trailing comments.
72
+ const id = /^\s*(?:-\s+)?(?:id|name):\s*['"]?([^'"\s#]+)['"]?/.exec(line)
73
+ if (id === null) return false
74
+ const value = id[1]
75
+ return value === MANAGER_PACKAGE || value === MANAGER_ENTRY_ID || value.endsWith('/' + MANAGER_ENTRY_ID)
76
+ }
77
+ for (const line of lines) {
78
+ const isEntryStart = /^\s*-(\s|$)/.test(line) || /^\s*[A-Za-z0-9_-]+:\s*/.test(line)
79
+ if (dropping) {
80
+ // Continue inside the entry while the line is indented or blank; a new top-level entry or
81
+ // a non-indented key ends it.
82
+ if (line.trim() === '' || /^\s+/.test(line)) continue
83
+ dropping = false
84
+ }
85
+ if (namesManager(line)) {
86
+ // Keep the leading "- " only when the id/name is its own line; drop the whole entry.
87
+ dropping = true
88
+ removed = true
89
+ continue
90
+ }
91
+ if (isEntryStart) { /* fallthrough */ }
92
+ out.push(line)
93
+ }
94
+ if (!removed) return null
95
+ const joined = out.join('\n')
96
+ return joined.endsWith('\n') ? joined : joined + '\n'
53
97
  }
54
98
 
55
99
  /**
@@ -91,7 +135,7 @@ export function findProfile(root = join(homedir(), '.dsh', 'profiles')) {
91
135
  }
92
136
 
93
137
  export function retireManager(profileDir) {
94
- const result = { profile: profileDir, manifest: false, patch: false, nodeModules: false, backups: [] }
138
+ const result = { profile: profileDir, manifest: false, patch: false, nodeModules: false, backups: [], errors: [] }
95
139
  if (typeof profileDir !== 'string' || !existsSync(profileDir)) return result
96
140
  const backupDir = join(profileDir, 'backups', 'retire-manager-' + stamp())
97
141
  mkdirSync(backupDir, { recursive: true })
@@ -104,10 +148,11 @@ export function retireManager(profileDir) {
104
148
  const backup = join(backupDir, 'package.json')
105
149
  writeFileSync(backup, text, 'utf8')
106
150
  result.backups.push(backup)
107
- writeFileSync(manifestPath, next, 'utf8')
151
+ writeAtomic(manifestPath, next)
152
+ JSON.parse(readFileSync(manifestPath, 'utf8'))
108
153
  result.manifest = true
109
154
  }
110
- } catch { /* leave the manifest alone on any error */ }
155
+ } catch (error) { result.errors.push('manifest:' + String(error && (error.message || error)).slice(0, 120)) }
111
156
  try {
112
157
  const text = readFileSync(patchPath, 'utf8')
113
158
  const next = stripPatchEntry(text)
@@ -115,16 +160,25 @@ export function retireManager(profileDir) {
115
160
  const backup = join(backupDir, 'cordis.patch.yml')
116
161
  writeFileSync(backup, text, 'utf8')
117
162
  result.backups.push(backup)
118
- writeFileSync(patchPath, next, 'utf8')
163
+ writeAtomic(patchPath, next)
164
+ if (!existsSync(patchPath)) throw new Error('patch write vanished')
119
165
  result.patch = true
120
166
  }
121
- } catch { /* leave the patch alone on any error */ }
167
+ } catch (error) { result.errors.push('patch:' + String(error && (error.message || error)).slice(0, 120)) }
122
168
  try {
123
169
  const dir = join(profileDir, 'node_modules', MANAGER_PACKAGE)
124
170
  if (existsSync(dir) && statSync(dir).isDirectory()) {
125
171
  renameSync(dir, join(backupDir, 'dsh-ustc-provider-manager'))
126
172
  result.nodeModules = true
127
173
  }
128
- } catch { /* keep the copy if it cannot be moved */ }
174
+ } catch (error) { result.errors.push('node_modules:' + String(error && (error.message || error)).slice(0, 120)) }
129
175
  return result
130
176
  }
177
+
178
+ /** Resolve an explicitly named profile directory, refusing anything that escapes profiles/. */
179
+ export function profileDirFor(name, root = join(homedir(), '.dsh', 'profiles')) {
180
+ if (typeof name !== 'string' || name === '' || /[\\/]|\.\./.test(name)) return null
181
+ const dir = join(root, name)
182
+ if (!existsSync(join(dir, 'package.json'))) return null
183
+ return dir
184
+ }