dsh-cost-meter 1.9.0 → 1.9.2

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.
@@ -1116,7 +1116,7 @@ export function qwenTokenPlanWindows(days, entry, nowMs, includeCall, belongsToP
1116
1116
 
1117
1117
  /** 默认官方端点;MiniMax 可用显式 HTTPS origin 覆盖此列表。 */
1118
1118
  export const CODING_PLAN_ENDPOINTS = {
1119
- opendesign: [OPENDESIGN_API + '/workspaces/{workspaceId}/billing/coding-plan-usage', OPENDESIGN_API + '/workspaces/{workspaceId}/wallet/balance'],
1119
+ opendesign: [OPENDESIGN_API + '/workspaces/{workspaceId}/billing/preflight', OPENDESIGN_API + '/workspaces/{workspaceId}/wallet/balance'],
1120
1120
  factory: [FACTORY_QUOTA_URL],
1121
1121
  anthropic: ['https://api.anthropic.com/api/oauth/usage'],
1122
1122
  zai: [
@@ -18,6 +18,34 @@ import { isLoopbackHost } from './gateway-quotas.js'
18
18
 
19
19
  export const CUSTOM_BALANCE_ADAPTER_ID = 'custom'
20
20
 
21
+ /** A root-relative route follows the running host, never a persisted port or browser input. */
22
+ export const isHostRelativeBalanceUrl = value => typeof value === 'string' && value.startsWith('/')
23
+ export function customBalanceHostOrigin(ctx) {
24
+ try {
25
+ const server = ctx?.get?.('webServer'), port = server?.port
26
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null
27
+ const host = server.host === '::' || server.host === '::1' || server.host === '[::1]' ? '[::1]' : '127.0.0.1'
28
+ if (server.host !== undefined && !['0.0.0.0', '::'].includes(server.host) && !isLoopbackHost(server.host)) return null
29
+ return `http://${host}:${port}`
30
+ } catch { return null }
31
+ }
32
+
33
+ export function resolveCustomBalanceUrl(value, ctx) {
34
+ if (typeof value !== 'string' || /[\\\s\u0000-\u001f\u007f]/.test(value)) throw new Error('customBalance.request.url is not a valid URL')
35
+ let parsed
36
+ if (isHostRelativeBalanceUrl(value)) {
37
+ if (value.startsWith('//')) throw new Error('customBalance.request.url must be a single-slash host-relative path')
38
+ const origin = customBalanceHostOrigin(ctx)
39
+ if (!origin) throw new Error('DSH web server is not listening; retry the host-relative balance query after startup')
40
+ parsed = new URL(value, origin)
41
+ if (parsed.origin !== origin) throw new Error('customBalance.request.url must stay on the current DSH host')
42
+ } else {
43
+ try { parsed = new URL(value) } catch { throw new Error('customBalance.request.url is not a valid URL') }
44
+ }
45
+ if (parsed.username || parsed.password || parsed.hash) throw new Error('customBalance.request.url must not contain credentials or a fragment')
46
+ return parsed
47
+ }
48
+
21
49
  export function customBalanceCredentialVars(entry) {
22
50
  if (entry?.adapter === 'aliyun') return [...ALIYUN_BALANCE_CREDENTIAL_VARS]
23
51
  if (entry?.adapter === 'tokenrhythm') return [...TOKENRHYTHM_BALANCE_CREDENTIAL_VARS]
@@ -164,21 +192,15 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
164
192
  if (request === null || typeof request !== 'object' || typeof request.url !== 'string' || request.url.length === 0) {
165
193
  throw new Error('customBalance.request.url is required')
166
194
  }
167
- // 端点收紧(v1.6.8):URL 必须是 https。自定义余额请求头支持 {{ENV}} 凭据占位符
168
- // (解析自 DSH 凭据库或环境变量),明文 http 会把密钥暴露给同网段嗅探。
169
- // v1.7.26 起与 gatewayQuotas 同口径放行 **loopback** 明文 http:本机服务
170
- // (127.0.0.1 / localhost / [::1]) 流量不出网卡,且大量本机只读路由
171
- // (如 dsh-workbuddy-connect 的额度 status 路由)只监听回环、不提供 TLS;
172
- // 非回环主机依旧强制 https。
173
- let parsedUrl
174
- try {
175
- parsedUrl = new URL(request.url)
176
- } catch {
177
- throw new Error(`customBalance.request.url is not a valid URL: ${request.url}`)
178
- }
195
+ const parsedUrl = resolveCustomBalanceUrl(request.url, ctx)
179
196
  const loopbackTarget = isLoopbackHost(parsedUrl.hostname)
180
- if (parsedUrl.protocol !== 'https:' && !(parsedUrl.protocol === 'http:' && loopbackTarget)) {
181
- throw new Error(`customBalance.request.url must use https (got ${parsedUrl.protocol}); refusing to send credentials over plaintext`)
197
+ const host = parsedUrl.host.toLowerCase()
198
+ const allowed = Array.isArray(custom.allowedHosts)
199
+ ? custom.allowedHosts.filter(h => typeof h === 'string' && h.trim()).map(h => h.trim().toLowerCase()) : null
200
+ // #309: non-loopback HTTP requires both an explicit switch and the exact host:port.
201
+ if (parsedUrl.protocol !== 'https:' && !(parsedUrl.protocol === 'http:'
202
+ && (loopbackTarget || custom.allowInsecureHttp === true && allowed?.includes(host)))) {
203
+ throw new Error('customBalance.request.url must use https; non-loopback HTTP requires allowInsecureHttp and an exact allowedHosts entry (host:port)')
182
204
  }
183
205
  // 凭据外带防护(v1.6.8 → v1.7.6 扩展,issue #86):请求头里**解析出了真实凭据**
184
206
  // ({{VAR}} 占位符)或**值本身疑似明文密钥**(Authorization / X-Api-Key / Bearer /
@@ -192,11 +214,7 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
192
214
  const rawHeaders = request.headers ?? {}
193
215
  const usesCredentials = Object.entries(rawHeaders).some(([name, value]) =>
194
216
  hasCredentialPlaceholder(value) || looksLikeSecretHeaderValue(name, value))
195
- const host = parsedUrl.host.toLowerCase()
196
217
  if (usesCredentials) {
197
- const allowed = Array.isArray(custom.allowedHosts)
198
- ? custom.allowedHosts.filter(h => typeof h === 'string' && h.length > 0).map(h => h.toLowerCase())
199
- : null
200
218
  if (allowed !== null && allowed.length > 0 && !allowed.includes(host)) {
201
219
  throw new Error(`customBalance request host "${host}" is not in customBalance.allowedHosts; refusing to send credentials there (add it explicitly to allow)`)
202
220
  }
@@ -217,7 +235,7 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
217
235
  // 瞬时网络错误自动重试(issue #28 同一封装;body 为字符串可安全重放)。
218
236
  // redirect: 'manual'(v1.6.8):禁止自动跟随重定向——凭据头会被原样带到 3xx 的
219
237
  // 目标主机,一次跨源重定向就足以把密钥发去别处;遇到重定向直接报错。
220
- const response = await fetchWithRetry(request.url, init, { timeoutMs: 15000 })
238
+ const response = await fetchWithRetry(parsedUrl.href, init, { timeoutMs: 15000 })
221
239
  if (response.status >= 300 && response.status < 400) {
222
240
  try { await response.body?.cancel?.() } catch {}
223
241
  throw new Error(`custom balance endpoint redirected (HTTP ${String(response.status)}); redirects are refused to avoid forwarding credentials to another host`)
package/lib/index.js CHANGED
@@ -16,7 +16,7 @@ import { priceMultiplierSettings } from './price-multiplier.js'
16
16
  */
17
17
 
18
18
  import { z } from 'zod'
19
- import { hostLocaleOf, localeOf } from './locale.js'
19
+ import { hostLocaleOf, localeOf, invalidateHostLocale, forgetHostLocale } from './locale.js'
20
20
  import fs from 'node:fs'
21
21
  import { createHash, randomUUID } from 'node:crypto'
22
22
  import { join, dirname } from 'node:path'
@@ -49,7 +49,7 @@ import { detectChatgptSubscription, ensureChatgptSubscriptionPlan } from './chat
49
49
  // 会话存储兼容(T3):宿主装 better-session(@morlay/session-rdb,SQLite)后会话不再落
50
50
  // JSONL 文件,回填/导入/重定价改由统一记录源读数据库;探测失败按 JSONL 兼容。
51
51
  import { createSessionRecordSource, probeSessionStorage } from './session-storage-compat.js'
52
- import { customBalanceCredentialVars } from './custom-balance.js'
52
+ import { customBalanceCredentialVars, customBalanceHostOrigin, isHostRelativeBalanceUrl } from './custom-balance.js'
53
53
  import { readScnetSnapshot } from './scnet-snapshot.js'
54
54
  import { readExternalUsageSnapshot, externalTodayCostForReconcile } from './external-usage.js'
55
55
  import { queryQwenCli } from './qwen-cli.js'
@@ -1787,7 +1787,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1787
1787
  const customBalanceFingerprint = index => {
1788
1788
  // Currency conversion is presentation-only; it must preserve the API snapshot.
1789
1789
  const { convertToDisplayCurrency, labelEn, ...query } = customBalanceConfigs()[index] ?? {}
1790
- return JSON.stringify([query, localeOf(ledger.config, ctx)])
1790
+ return JSON.stringify([query, isHostRelativeBalanceUrl(query?.request?.url) ? customBalanceHostOrigin(ctx) : null, localeOf(ledger.config, ctx)])
1791
1791
  }
1792
1792
  const discardCustomBalanceCache = index => {
1793
1793
  customBalanceCaches[index]?.controller?.abort()
@@ -2221,8 +2221,12 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2221
2221
  for (const index of Object.keys(customBalanceCaches)) discardCustomBalanceCache(index)
2222
2222
  reconcileNotice = { ok: true, message: '' }
2223
2223
  }
2224
- ctx.on('settings/document-updated', syncMessageLocale)
2225
- ctx.on('locale/change', syncMessageLocale)
2224
+ const onLocaleChanged = () => {
2225
+ if (active && invalidateHostLocale(ctx)) syncMessageLocale()
2226
+ }
2227
+ ctx.on('settings/document-updated', onLocaleChanged)
2228
+ ctx.on('locale/change', onLocaleChanged)
2229
+ ctx.effect(() => () => forgetHostLocale(ctx), 'cost-meter: host locale cache')
2226
2230
 
2227
2231
  // ── 价格表下发去重 ────────────────────────────────────────────────────────
2228
2232
  // 版本绑定返回快照中的价格对象,不能在异步读取结束后改用 ledger 的新对象。
@@ -283,8 +283,15 @@ function mergeSamples(base, local, disk, now) {
283
283
  // Replay pending calls into both the baseline and current disk snapshot. The
284
284
  // remaining local-versus-baseline diff contains only edits/imports/repairs, so
285
285
  // repeated flushes cannot add an already committed call or hourly bucket twice.
286
- export function mergeLedger(base, local, disk, pending, now = Date.now(), hourRepairs = []) {
287
- const b = cloneLedgerSnapshot(base), l = cloneLedgerSnapshot(local), d = cloneLedgerSnapshot(disk ?? base)
286
+ export function mergeLedger(base, local, disk, pending, now = Date.now(), hourRepairs = [], options = {}) {
287
+ // 快路径:调用方持有的 local 若是自建快照(snapshot()),可把所有权移交给合并结果,
288
+ // 省掉一次全账本 structuredClone;本进程缓存与磁盘同版本时 disk === base,
289
+ // 两条基线初始值一致,共享同一份克隆(pending 只重放一次)。
290
+ const ownLocal = options.ownLocal === true
291
+ const sameDisk = disk !== undefined && disk === base
292
+ const b = cloneLedgerSnapshot(base)
293
+ const d = sameDisk ? b : cloneLedgerSnapshot(disk ?? base)
294
+ const l = ownLocal ? local : cloneLedgerSnapshot(local)
288
295
  // The baseline is our last known persisted state, but frozen FX fields can have
289
296
  // been backfilled in memory only; never let that backfill look like stale data.
290
297
  alignFrozenBaseline(b.days, d.days)
@@ -299,7 +306,7 @@ export function mergeLedger(base, local, disk, pending, now = Date.now(), hourRe
299
306
  for (const entry of pending) {
300
307
  if (remoteReset && !localReset && entry.recordedAt <= (reset?.at ?? 0)) continue
301
308
  applyAccount(b, entry)
302
- applyAccount(d, entry)
309
+ if (d !== b) applyAccount(d, entry)
303
310
  if (remoteReset && !localReset) applyAccount(l, entry)
304
311
  }
305
312
  const out = {
package/lib/locale.js CHANGED
@@ -1,4 +1,17 @@
1
1
  /** The browser locale face is optional; Host DSH exposes its saved preference through settings. */
2
+ export const HOST_LOCALE_MAX_AGE_MS = 1000
3
+ const preferences = new WeakMap()
4
+
5
+ /** describe() may itself emit settings/document-updated; do not recursively describe again. */
6
+ export function invalidateHostLocale(ctx) {
7
+ const cached = ctx && preferences.get(ctx)
8
+ if (cached?.reading) return false
9
+ if (cached) cached.expiresAt = 0
10
+ return true
11
+ }
12
+
13
+ export function forgetHostLocale(ctx) { if (ctx) preferences.delete(ctx) }
14
+
2
15
  export function supportedLocale(value) {
3
16
  if (typeof value !== 'string') return null
4
17
  const language = value.trim().toLowerCase().split(/[-_]/)[0]
@@ -11,12 +24,27 @@ export function hostLocaleOf(ctx) {
11
24
  const active = supportedLocale(locale?.getSnapshot?.().active)
12
25
  if (active) return active
13
26
  } catch { /* Older hosts have no locale face. */ }
27
+ if (!ctx || typeof ctx !== 'object' && typeof ctx !== 'function') return null
28
+ let cached = preferences.get(ctx)
29
+ if (cached && (cached.reading || Date.now() < cached.expiresAt)) return cached.locale
30
+ if (!cached) {
31
+ cached = { locale: null, expiresAt: 0, reading: false }
32
+ preferences.set(ctx, cached)
33
+ }
34
+ cached.reading = true
14
35
  try {
15
36
  const settings = ctx?.get?.('settings')
16
37
  // Read only the public, redacted descriptor; never inspect storage files or credentials.
17
38
  const rows = settings?.describe?.({ redactSecrets: true })
18
- return supportedLocale(Array.isArray(rows) ? rows.find(row => row?.ns === 'locale')?.value?.preference : undefined)
19
- } catch { return null }
39
+ cached.locale = supportedLocale(Array.isArray(rows) ? rows.find(row => row?.ns === 'locale')?.value?.preference : undefined)
40
+ } catch { cached.locale = null }
41
+ finally {
42
+ cached.reading = false
43
+ // Event-less older hosts still observe preference changes at the next read after one second.
44
+ // Store only the parsed language, never the descriptor or any unrelated plugin settings.
45
+ cached.expiresAt = Date.now() + HOST_LOCALE_MAX_AGE_MS
46
+ }
47
+ return cached.locale
20
48
  }
21
49
 
22
50
  export function localeOf(config, ctx) {
package/lib/opendesign.js CHANGED
@@ -63,7 +63,11 @@ export function parseOpenDesignPrices(value, checkedAt = new Date().toISOString(
63
63
  /** Each quota window is an independent simultaneous limit, not an additive balance. */
64
64
  export function parseOpenDesignUsage(value, workspaceId) {
65
65
  // Issue #274: the `billing/preflight` form wraps the identical window payload in `codingPlan`.
66
- if (object(value) && object(value.codingPlan)) value = { ...value, ...value.codingPlan, workspaceMemberId: value.workspaceMemberId ?? value.codingPlan.workspaceMemberId }
66
+ if (object(value) && object(value.codingPlan)) {
67
+ if ([value.workspaceId, value.codingPlan.workspaceId].some(id => id !== undefined && id !== workspaceId)
68
+ || value.workspaceMemberId !== undefined && value.codingPlan.workspaceMemberId !== undefined && value.workspaceMemberId !== value.codingPlan.workspaceMemberId) return null
69
+ value = { ...value, ...value.codingPlan, workspaceMemberId: value.workspaceMemberId ?? value.codingPlan.workspaceMemberId }
70
+ }
67
71
  if (!object(value) || value.workspaceId !== workspaceId || value.workspaceMemberId !== undefined && !id(value.workspaceMemberId) || typeof value.eligible !== 'boolean'
68
72
  || !Array.isArray(value.windows) || value.windows.length > 32) return null
69
73
  const windows = {}, seen = new Set()
@@ -100,8 +104,8 @@ export async function queryOpenDesignQuota(key, locale, t, { workspaceId, signal
100
104
  const controller = new AbortController(), combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
101
105
  const timer = setTimeout(() => controller.abort(), 15000); timer.unref?.()
102
106
  const prefix = OPENDESIGN_API + '/workspaces/' + encodeURIComponent(workspace)
103
- // Issue #274: the primary usage route can require a browser session, while the wallet and the
104
- // Cookie-free preflight route accept a Control Key. Read both sides independently and only fail
107
+ // The preflight and wallet routes accept a Control Key without a browser cookie.
108
+ // Read both sides independently and only fail
105
109
  // when both fail; a single 401 must never discard the other side's valid answer.
106
110
  const read = async (path, side) => {
107
111
  const url = prefix + path
@@ -141,15 +145,8 @@ export async function queryOpenDesignQuota(key, locale, t, { workspaceId, signal
141
145
  return queryError(zh ? 'OpenDesign:查询失败,请检查控制端凭据、工作区权限和网络。' : 'OpenDesign: query failed; check the control credential, workspace access and connection.', false, failure.kind)
142
146
  }
143
147
  try {
144
- // Issue #274: /billing/coding-plan-usage needs a browser session on some accounts, while
145
- // /billing/preflight accepts the same Control Key as a plain Bearer credential. Keep the
146
- // primary route first and fall back only when the credential is rejected there.
147
- const readUsage = async () => {
148
- const usage = await read('/billing/coding-plan-usage', 'usage')
149
- if (usage.ok || usage.kind !== OPEN_DESIGN_QUOTA_FAILURES.unauthorized) return usage
150
- return read('/billing/preflight', 'preflight')
151
- }
152
- const [usageRead, walletRead] = await Promise.all([readUsage(), read('/wallet/balance', 'wallet')])
148
+ // #274 / #313: do not spend a request on the browser-session-only usage route.
149
+ const [usageRead, walletRead] = await Promise.all([read('/billing/preflight', 'preflight'), read('/wallet/balance', 'wallet')])
153
150
  combined.throwIfAborted()
154
151
  // The preflight answer is already scoped by URL and x-vela-workspace-id; tolerate a body that
155
152
  // omits the redundant workspaceId, but never accept one that names a different workspace.
package/lib/store.js CHANGED
@@ -824,6 +824,7 @@ const VALIDATION_MESSAGES = {
824
824
  customBalanceLabelEn: 'customBalance.labelEn 必须是字符串',
825
825
  customBalanceUnit: 'customBalance.unit 必须是 USD / CNY / EUR / CREDITS',
826
826
  customBalanceConvert: 'customBalance.convertToDisplayCurrency 必须是布尔值',
827
+ customBalanceHttp: 'customBalance.allowInsecureHttp 必须是布尔值',
827
828
  customBalanceRequest: 'customBalance.request.url 必须是非空字符串',
828
829
  customBalanceHeaders: 'customBalance.request.headers 必须是字符串→字符串映射',
829
830
  customBalanceExtract: 'customBalance.extract 必须是对象',
@@ -932,6 +933,7 @@ const VALIDATION_MESSAGES = {
932
933
  customBalanceLabelEn: 'customBalance.labelEn must be a string',
933
934
  customBalanceUnit: 'customBalance.unit must be USD / CNY / EUR / CREDITS',
934
935
  customBalanceConvert: 'customBalance.convertToDisplayCurrency must be a boolean',
936
+ customBalanceHttp: 'customBalance.allowInsecureHttp must be a boolean',
935
937
  customBalanceRequest: 'customBalance.request.url must be a non-empty string',
936
938
  customBalanceHeaders: 'customBalance.request.headers must be a string→string map',
937
939
  customBalanceExtract: 'customBalance.extract must be an object',
@@ -1315,6 +1317,7 @@ export function applyConfigPatch(current, rawPatch) {
1315
1317
  if (entry.labelEn !== undefined && typeof entry.labelEn !== 'string') errors.push(vmsg(locale, fieldPrefix + 'LabelEn'))
1316
1318
  if (entry.unit !== undefined && !['USD', 'CNY', 'EUR', 'CREDITS'].includes(entry.unit)) errors.push(vmsg(locale, fieldPrefix + 'Unit'))
1317
1319
  if (entry.convertToDisplayCurrency !== undefined && typeof entry.convertToDisplayCurrency !== 'boolean') errors.push(vmsg(locale, fieldPrefix + 'Convert'))
1320
+ if (entry.allowInsecureHttp !== undefined && typeof entry.allowInsecureHttp !== 'boolean') errors.push(vmsg(locale, fieldPrefix + 'Http'))
1318
1321
  const request = entry.request
1319
1322
  // url 仅在启用时必填:默认禁用状态下不能阻断其它配置项的保存。
1320
1323
  if (request === null || typeof request !== 'object' || Array.isArray(request) || typeof request.url !== 'string' || (entry.enabled === true && request.url.length === 0)) {
@@ -1679,6 +1682,7 @@ export function sanitizeConfig(raw) {
1679
1682
  labelEn: typeof entry.labelEn === 'string' ? entry.labelEn : baseEntry.labelEn,
1680
1683
  unit: entry.adapter === 'tokenrhythm' ? 'CNY' : oneOf(entry.unit, ['USD', 'CNY', 'EUR', 'CREDITS'], baseEntry.unit),
1681
1684
  convertToDisplayCurrency: entry.convertToDisplayCurrency === true,
1685
+ allowInsecureHttp: entry.allowInsecureHttp === true,
1682
1686
  }
1683
1687
  if (entry.request === null || typeof entry.request !== 'object' || Array.isArray(entry.request)) {
1684
1688
  clean.request = { ...baseEntry.request }
@@ -2263,7 +2267,6 @@ export class Ledger {
2263
2267
  }
2264
2268
 
2265
2269
  scheduleWrite() {
2266
- advancePricingHistory(this.pricingHistory, this.config)
2267
2270
  this.pendingWrite = true
2268
2271
  if (this.writeTimer !== null) return
2269
2272
  this.writeTimer = setTimeout(() => {
@@ -2335,7 +2338,7 @@ export class Ledger {
2335
2338
  if (revision === this.diskRevision) return
2336
2339
  const disk = this.readDiskSnapshot()
2337
2340
  if (disk === null) return
2338
- this.adoptSnapshot(mergeLedger(this.writeBase, this.snapshot(), disk, []))
2341
+ this.adoptSnapshot(mergeLedger(this.writeBase, this.snapshot(), disk, [], Date.now(), [], { ownLocal: true }))
2339
2342
  // Keep the new baseline equal to the state we now hold: a freshly loaded legacy
2340
2343
  // ledger has frozen FX amounts backfilled in memory that the file does not carry
2341
2344
  // yet, and a baseline copied from that file would treat them as a local change
@@ -2359,8 +2362,9 @@ export class Ledger {
2359
2362
  if (!this.pendingWrite || this.closed) return
2360
2363
  try {
2361
2364
  withLedgerLock(this.path, () => {
2365
+ advancePricingHistory(this.pricingHistory, this.config)
2362
2366
  const disk = this.readDiskSnapshot()
2363
- const merged = mergeLedger(this.writeBase, this.snapshot(), disk, this.pendingAccounts, Date.now(), this.pendingPlanHourRepairs)
2367
+ const merged = mergeLedger(this.writeBase, this.snapshot(), disk, this.pendingAccounts, Date.now(), this.pendingPlanHourRepairs, { ownLocal: true })
2364
2368
  // Keep runtime-only secret fallbacks in memory, never in the file or baseline.
2365
2369
  writeLedger(this.path, merged, this.legacyPricingHistory)
2366
2370
  this.legacyPricingHistory = false