@fish-under-sea/magpie-dragonapi 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -77,18 +77,18 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
77
77
  - `api_key:write` —— 建钥匙 / 删钥匙
78
78
  - `api_key:reveal` —— 看钥匙完整明文
79
79
  - `usage:read` —— 读用量流水
80
- - `wallet:read` —— 读余额与邀请(可选)
80
+ - `wallet:read` —— 读订阅、套餐与邀请(只读展示)
81
81
  3. 复制 `nap-` 开头的令牌,粘到插件页面的「访问令牌」页。
82
82
 
83
83
  > 旧版访问令牌已停用(站点返回 `ACCESS_TOKEN_LEGACY_RETIRED`),必须用新的 `nap-` 令牌。
84
84
 
85
85
  **PAT 存在本地**:`<magpie 配置目录>/dragonapi-state.json`,权限 0600。它必须明文存——每次建钥匙都要用。文件里**不存任何 `sk-` 钥匙明文**,那些由 magpie 自己的 `plugin-auth.json` 保管。
86
86
 
87
- 保存 PAT 时插件会先探三个只读端点(账户资料 / 钥匙列表 / 用量)来确认它真的能用:
87
+ 保存 PAT 时插件会并行探四个只读端点(账户资料 / 钥匙列表 / 用量 / 订阅),每次最多等待 12 秒:
88
88
 
89
89
  | 情况 | 行为 |
90
90
  | --- | --- |
91
- | 三个端点都说令牌无效(401/403) | 拒收,并说清是权限不够还是令牌失效 |
91
+ | 四个端点都说令牌无效(401/403) | 拒收,并说清是权限不够还是令牌失效 |
92
92
  | 能用一个、缺另一个 | **照样存下**,提示缺哪一格、哪些功能会失败(例如只缺 `profile:read` 时建钥匙会失败,但读用量照常) |
93
93
  | 站点连不上 / 返回验证页 | **照样存下**,标成「未验证」,稍后刷新即可再确认 |
94
94
  | 写不进状态文件 | 直接报错并给出文件路径——不会出现「提示已保存、重启后消失」 |
@@ -96,7 +96,7 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
96
96
  ## 界面里有什么
97
97
 
98
98
  四个标签页:账户概览 / 模型广场 / 使用日志 / 访问令牌。整页限高——页头、标签、页脚固定不动,
99
- 超长内容在各自的卡片里滚动。
99
+ 超长内容在面板或卡片里滚动;账户页统一面板滚动,确保订阅、推荐和密钥始终可达。
100
100
 
101
101
  | 页 | 内容 |
102
102
  | --- | --- |
@@ -107,7 +107,11 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
107
107
  | **使用日志** | 对标 NearToken 的详细程度:日/周/月 + 模型名 / 分组 / 类型 / 令牌名 / 请求 ID 筛选,用量·请求·Token 统计条(带隐私遮罩),明细 9 列(时间、分组、模型、费用、请求体大小、流式吞吐、Token/缓存、首字·耗时、详情),分页与「载入更多」 |
108
108
  | **访问令牌** | 填入/清除 PAT,说明需要哪些权限,并显示实际验到的 scope;健康与诊断记录 |
109
109
 
110
- 预览时可以加 `?demo` 用虚拟数据把四个页面都填满(不发任何写请求)。
110
+ 预览时可以加 `?demo` 用虚拟数据把四个页面都填满(订阅示例包括不限量、取消、到期与超额)。
111
+
112
+ 仅设置 PAT、没有绑定 `sk-` 也能读取账户钱包与账户级用量。`profile:read` 用于账户资料与钱包余额,`usage:read` 用于账户日志;有 PAT 时默认只统计账户日志,不再叠加绑定钥匙日志。钱包余额与钥匙额度分别展示,不求和。
113
+
114
+ 账户概览内置只读「订阅套餐」:我的订阅、到期、下次重置、额度与进度,以及站点返回的套餐列表。需要 `wallet:read`,不购买、不支付、不修改扣费偏好。套餐标价保留原币,quota 按站点参数换算。日志只取最近一批,页面会明确标注不完整,不能当作全量账单。
111
115
 
112
116
  ## 价格怎么算
113
117
 
@@ -131,7 +135,7 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
131
135
  | 一把钥匙一个分组 | 分组是钥匙的属性 | 多分组 = 多账号,账号列表会变长 |
132
136
  | 视频按秒计费只能给区间 | 价格随分辨率/规格变 | 实际扣费以控制台为准 |
133
137
  | `priceRate` 未验证 | 站点前端还有一个「充值价系数」,拿不到登录态确认不了 | 单价可能整体差一个系数;流水里的实际费用不受影响 |
134
- | 独立起服务时看不到余额 | 钥匙只在插件进程内存里 | 用 `node serve.mjs` 单独起时,余额显示「—」 |
138
+ | 独立服务拿不到绑定钥匙明文 | 钥匙只在插件进程内存里 | 钥匙额度显示「—」;已设置 PAT 的账户钱包与用量仍可读取 |
135
139
 
136
140
  ## 独立启动(插件宿主起不来时)
137
141
 
@@ -139,21 +143,28 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
139
143
  node serve.mjs
140
144
  ```
141
145
 
142
- 会在 `127.0.0.1:3517` 起同一个服务,界面可用(余额除外)。如果插件已经在跑,它会提示并退出,不会抢端口。
146
+ 会在 `127.0.0.1:3517` 起同一个服务,界面可用(绑定钥匙额度除外;PAT 账户钱包和日志可读取)。如果插件已经在跑,它会提示并退出,不会抢端口。
143
147
 
144
148
  ## 开发
145
149
 
146
- ```powershell
147
- npm test # 156 个用例:价格解析、详情页 billing 折算、目录构建、用量解析、PAT 保存的四种结局、入口只导出默认工厂、源与刷新链路、服务冒烟、插件入口、界面
150
+ ```bash
151
+ node --test "tests/*.test.mjs"
148
152
  ```
149
153
 
150
154
  测试用站点 2026-11-10 的真实快照([证据-站点定价快照-2026-11-10.json](证据-站点定价快照-2026-11-10.json))当夹具,站点改了写法就会被发现。
151
155
 
152
156
  ### 本地实时预览(改界面时用这个)
153
157
 
154
- ```powershell
155
- node dev.mjs # http://127.0.0.1:3671/?theme=dark
156
- node dev.mjs --sandbox # 套一层 magpie 同款沙箱 iframe
158
+ ```bash
159
+ node dev.mjs
160
+ ```
161
+
162
+ ```bash
163
+ node dev.mjs --sandbox
164
+ ```
165
+
166
+ ```bash
167
+ node dev.mjs --upstream http://127.0.0.1:3517
157
168
  ```
158
169
 
159
170
  改 `ui/` 里任何文件(html / css / js)都会自动整页刷新,不需要装 magpie,也不用重装插件。
@@ -172,7 +183,13 @@ node dev.mjs --sandbox # 套一层 magpie 同款沙箱 iframe
172
183
  这个差异造成过真实事故:顶层一切正常,装进 magpie 后所有接口都「连不上本地服务」——
173
184
  不透明源里相对路径的 `fetch` 会被判 `Failed to fetch`。沙箱模式就是为了提前看见这类问题。
174
185
 
175
- 预览状态写在 `.dev-state/`(含 PAT,已进 `.gitignore`)。
186
+ 默认访问 `http://127.0.0.1:3671/?theme=dark`。默认独立模式写 `.dev-state/`(含 PAT,已进 `.gitignore`),与插件实际状态分离。只有 `--upstream` 模式代理到指定插件服务,才操作那个服务实际使用的状态;该模式不启动内部服务。
187
+
188
+ Node 22 若不支持 npm 脚本的测试隔离参数,可直接运行:
189
+
190
+ ```bash
191
+ node --test "tests/*.test.mjs"
192
+ ```
176
193
 
177
194
  目录结构:
178
195
 
@@ -0,0 +1,69 @@
1
+ /**
2
+ * dashboard 数据看板聚合。
3
+ *
4
+ * 站点 `/api/data/self` 返回按「时间桶 × 模型」拆好的行:
5
+ * `{ created_at, model_name, count, quota, token_used, cache_read_tokens, cache_creation_tokens }`。
6
+ * 这里只做确定性的汇总,金额换算交给页面(页面才知道币种与倍率)。
7
+ */
8
+
9
+ const num = (v) => {
10
+ const n = Number(v);
11
+ return Number.isFinite(n) ? n : 0;
12
+ };
13
+
14
+ /**
15
+ * summarizeDashboard 汇总站点数据看板的行。
16
+ *
17
+ * @param {Array<object>} rows 站点 `/api/data/self` 的行
18
+ * @param {{ start: number, end: number }} span 时间窗(毫秒)
19
+ */
20
+ export function summarizeDashboard(rows, span = {}) {
21
+ const list = Array.isArray(rows) ? rows.filter(Boolean) : [];
22
+ const totals = { count: 0, quota: 0, tokens: 0, cacheRead: 0, cacheWrite: 0 };
23
+ const models = new Map();
24
+ const buckets = new Map();
25
+
26
+ for (const row of list) {
27
+ const at = Math.floor(num(row.created_at) * 1000) || 0;
28
+ const model = String(row.model_name || '');
29
+ const count = num(row.count);
30
+ const quota = num(row.quota);
31
+ const tokens = num(row.token_used);
32
+ const cacheRead = num(row.cache_read_tokens);
33
+ const cacheWrite = num(row.cache_creation_tokens);
34
+
35
+ totals.count += count;
36
+ totals.quota += quota;
37
+ totals.tokens += tokens;
38
+ totals.cacheRead += cacheRead;
39
+ totals.cacheWrite += cacheWrite;
40
+
41
+ const m = models.get(model) || { model, count: 0, quota: 0, tokens: 0, cacheRead: 0, cacheWrite: 0 };
42
+ m.count += count;
43
+ m.quota += quota;
44
+ m.tokens += tokens;
45
+ m.cacheRead += cacheRead;
46
+ m.cacheWrite += cacheWrite;
47
+ models.set(model, m);
48
+
49
+ const b = buckets.get(at) || { at, count: 0, quota: 0, tokens: 0, values: {} };
50
+ b.count += count;
51
+ b.quota += quota;
52
+ b.tokens += tokens;
53
+ b.values[model] = (b.values[model] || 0) + quota;
54
+ buckets.set(at, b);
55
+ }
56
+
57
+ const minutes = Math.max(1, (num(span.end) - num(span.start)) / 60000);
58
+ const sortedModels = [...models.values()].sort((a, b) => b.quota - a.quota || b.count - a.count);
59
+ return {
60
+ totals: {
61
+ ...totals,
62
+ avgRpm: totals.count / minutes,
63
+ avgTpm: totals.tokens / minutes,
64
+ },
65
+ models: sortedModels,
66
+ buckets: [...buckets.values()].sort((a, b) => a.at - b.at),
67
+ minutes,
68
+ };
69
+ }
package/lib/pricing.mjs CHANGED
@@ -108,6 +108,7 @@ export function usagePrices(expr) {
108
108
  *
109
109
  * ratio 倍率计费,算得准
110
110
  * tiered 表达式计费且取到了系数,算得准(取第一档,其余在 note 里)
111
+ * flat 单档表达式计费:单价是平的,只有 fast 这类整单倍率
111
112
  * percall 按次 / 按秒,价格是区间
112
113
  * unknown 算不准,只有 note 说明原因
113
114
  *
@@ -118,7 +119,7 @@ export function usagePrices(expr) {
118
119
  export function priceOf(row, ratio, cur) {
119
120
  const groupRatio = Number(ratio) > 0 ? Number(ratio) : 1
120
121
  const symbol = cur?.symbol || '$'
121
- // 数值单独给一份(货币单位 / 百万 token),页面要在 /1M 与 /1K 之间切换、
122
+ // 数值单独给一份(货币单位 / 百万 token),页面要在 /1M 与 /272K 之间切换、
122
123
  // 也要按价格排序——字符串没法算,所以两个都留着。
123
124
  const perMNum = (v) => {
124
125
  const n = Number(v)
@@ -193,8 +194,11 @@ export function priceOf(row, ratio, cur) {
193
194
  const output = co.output === undefined ? null : perM(co.output)
194
195
  const cache = co.cacheRead === undefined ? null : perM(co.cacheRead)
195
196
  if (input || output) {
197
+ const mult = multiplierText(expr)
196
198
  return {
197
- kind: 'tiered',
199
+ // 单档表达式(tier("standard", …))价格是平的,标成「分档计费」会
200
+ // 让人以为还有别的档可切——真实站点上这类模型只有 fast 这类整单倍率。
201
+ kind: tiers.length > 1 ? 'tiered' : 'flat',
198
202
  input: input || '—',
199
203
  output: output || '—',
200
204
  cache: cache || '—',
@@ -202,9 +206,9 @@ export function priceOf(row, ratio, cur) {
202
206
  outputNum: co.output === undefined ? null : perMNum(co.output),
203
207
  cacheNum: co.cacheRead === undefined ? null : perMNum(co.cacheRead),
204
208
  tierCount: tiers.length,
205
- note: tiers.length > 1
209
+ note: (tiers.length > 1
206
210
  ? `${tiers.length} 档(${tiers.map((t) => t.name).join(' / ')}),上表是「${first.name}」档`
207
- : `表达式计费(${first.name})`,
211
+ : `表达式计费(${first.name})`) + (mult ? `;整单倍率 ${mult}` : ''),
208
212
  }
209
213
  }
210
214
  }
@@ -254,6 +258,33 @@ export function parseMultipliers(expr) {
254
258
  return out
255
259
  }
256
260
 
261
+ /**
262
+ * multiplierText 把条件倍率写成一句紧凑的话,给卡片 tooltip 用。
263
+ *
264
+ * 例:`service_tier=priority/fast/ultrafast ×2`、`speed=fast ×2`。
265
+ * 同一个参数的不同取值合并到一处;不同系数分开写(gpt-6-astra 的
266
+ * ultrafast 是 ×6,不能和 ×2 混成一句)。没有这类规则就返回空串。
267
+ */
268
+ export function multiplierText(expr) {
269
+ const list = parseMultipliers(expr)
270
+ if (!list.length) return ''
271
+ // factor → param → [值…],保持站点表达式里的先后顺序
272
+ const byFactor = new Map()
273
+ for (const m of list) {
274
+ const perParam = byFactor.get(m.factor) || new Map()
275
+ const values = perParam.get(m.param) || []
276
+ values.push(m.value)
277
+ perParam.set(m.param, values)
278
+ byFactor.set(m.factor, perParam)
279
+ }
280
+ const parts = []
281
+ for (const [factor, perParam] of byFactor) {
282
+ const conds = [...perParam].map(([param, values]) => `${param}=${values.join('/')}`).join('、')
283
+ parts.push(`${conds} ×${factor}`)
284
+ }
285
+ return parts.join(';')
286
+ }
287
+
257
288
  /** coeffPrice 把一个 token 系数折成「每百万 token 多少钱」。 */
258
289
  function coeffPrice(coeff, ratio, symbol) {
259
290
  const n = Number(coeff)
package/lib/service.mjs CHANGED
@@ -22,12 +22,26 @@ import { readFileSync, existsSync, statSync } from 'node:fs'
22
22
  import { extname, join, normalize, resolve, sep } from 'node:path'
23
23
  import { fileURLToPath } from 'node:url'
24
24
 
25
- import { currencyOf, text, readTokenUsage, readTokenLogs, readUsableGroups, readKeys, createKey, revealKey, deleteKey, probePat, readAff, transferAff } from './site.mjs'
25
+ import { currencyOf, text, readTokenUsage, readTokenLogs, readSelf, readUsageSelf, readUsageSelfPage, readUsageStatsSelf, readDataSelf, readSubscriptions, normalizePat, readUsableGroups, readKeys, createKey, updateKey, revealKey, deleteKey, probePat, readAff, transferAff } from './site.mjs'
26
26
  import { buildCatalog, modelsOfGroup } from './catalog.mjs'
27
27
  import { billingOf } from './pricing.mjs'
28
28
  import { rowsOf, summarize, windowOf } from './usage.mjs'
29
+ import { summarizeDashboard } from './dashboard.mjs'
29
30
  import { maskKey, tailOf, statePath } from './store.mjs'
30
31
 
32
+ /** uniqRows 去重:站点分页偶尔因排序不稳定重叠,按 id(无 id 用关键字段)去重。 */
33
+ function uniqRows(rows) {
34
+ const seen = new Set()
35
+ const out = []
36
+ for (const r of rows) {
37
+ const key = Number(r.id) > 0 ? `i${r.id}` : `${r.at}|${r.model}|${r.costRaw}|${r.input}|${r.output}|${r.tokenName}`
38
+ if (seen.has(key)) continue
39
+ seen.add(key)
40
+ out.push(r)
41
+ }
42
+ return out
43
+ }
44
+
31
45
  const here = resolve(fileURLToPath(new URL('..', import.meta.url)))
32
46
 
33
47
  /** 插件版本,从 package.json 读一次。 */
@@ -96,6 +110,7 @@ const SCOPE_LOSS = {
96
110
  'profile:read': '读账户资料与建钥匙',
97
111
  'api_key:read': '读钥匙列表',
98
112
  'usage:read': '读用量流水',
113
+ 'wallet:read': '读订阅与扣费偏好',
99
114
  };
100
115
 
101
116
  function patWarning(probe) {
@@ -253,9 +268,20 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
253
268
 
254
269
  if (path === '/api/state' && req.method === 'GET') {
255
270
  const { st, cat, cur, built, status: site_ } = await stateOf()
256
- const accounts = await accountViews(st, cur)
271
+ const [accounts, userResult] = await Promise.all([
272
+ accountViews(st, cur),
273
+ st.pat ? readSelf(site, st.pat).then((u) => ({
274
+ user: {
275
+ id: u.id, username: u.username, displayName: u.displayName, group: u.group,
276
+ balanceRaw: u.quota, usedRaw: u.usedQuota,
277
+ balance: u.quota === null ? '—' : text(u.quota, cur),
278
+ used: u.usedQuota === null ? '—' : text(u.usedQuota, cur),
279
+ }, userError: '',
280
+ }), (e) => ({ user: null, userError: String(e?.message || e) })) : { user: null, userError: '' },
281
+ ])
257
282
  json(res, 200, {
258
283
  ok: true,
284
+ ...userResult,
259
285
  site,
260
286
  siteName: site_?.siteName || 'DragonAPI',
261
287
  pat: {
@@ -331,41 +357,110 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
331
357
  return
332
358
  }
333
359
 
334
- if (path === '/api/usage' && req.method === 'GET') {
360
+ if ((path === '/api/usage' || path === '/api/logs') && req.method === 'GET') {
335
361
  const range = url.searchParams.get('range') || 'day'
362
+ if (!['day', 'week', 'month'].includes(range)) throw new BadRequest('时间窗必须是 day / week / month')
363
+ const only = url.searchParams.get('account') || ''
364
+ const limit = Math.max(1, Math.min(2000, Number(url.searchParams.get('limit')) || 1000))
336
365
  const { st, cur } = await stateOf()
337
366
  const { start, end } = windowOf(range)
367
+ const options = { pageSize: 100, start, end }
338
368
  const all = []
339
- for (const [key, meta] of Object.entries(st.accounts || {})) {
340
- const secret = await readAccountKey(key)
341
- if (!secret) continue
342
- try {
343
- const items = await readTokenLogs(site, secret, { pageSize: 500 })
344
- all.push(...rowsOf(items, cur, meta?.label || key))
345
- } catch { /* 一把钥匙读不到不该让整页失败 */ }
369
+ let siteTotal = null
370
+ const source = st.pat && !only ? 'pat' : 'key'
371
+ if (source === 'pat') {
372
+ // 站点按 100 条一页;按 data.total 把整个时间窗翻完(最多 10 页 / 1000 条),
373
+ // 这样「总计」就是站点真实总条数,而不是本地这 100 行。
374
+ const collected = []
375
+ let page = 1
376
+ for (;;) {
377
+ const { items, total } = await readUsageSelfPage(site, st.pat, { page, pageSize: 100, start, end })
378
+ siteTotal = Number.isFinite(total) ? total : siteTotal
379
+ collected.push(...items)
380
+ if (!items.length || items.length < 100 || (siteTotal != null && collected.length >= siteTotal) || page >= 10) break
381
+ page += 1
382
+ }
383
+ all.push(...uniqRows(rowsOf(collected, cur)))
384
+ } else {
385
+ const entries = Object.entries(st.accounts || {}).filter(([key]) => !only || key === only)
386
+ if (only && !entries.length) throw new BadRequest('没有这个已绑定账号')
387
+ if (!entries.length) throw new BadRequest('需要访问令牌(PAT)或已绑定的 sk 钥匙才能读取用量')
388
+ // 明确请求某把钥匙时绝不回退 PAT;任一失败都不能假装它的用量是零。
389
+ const lists = await Promise.all(entries.map(async ([key, meta]) => {
390
+ const secret = await readAccountKey(key)
391
+ if (!secret) throw new Error(`账号 ${meta?.label || key} 的钥匙尚未载入,无法读取用量`)
392
+ return rowsOf(await readTokenLogs(site, secret, options), cur, meta?.label || key)
393
+ }))
394
+ all.push(...lists.flat())
395
+ }
396
+ all.sort((a, b) => b.at - a.at)
397
+ const rows = all.filter((r) => r.at >= start && r.at <= end)
398
+ const total = siteTotal != null ? siteTotal : rows.length
399
+ const coverage = {
400
+ source, partial: true,
401
+ note: source === 'pat' ? '按所选时间窗统计,最多载入 1000 条日志。' : '按所选时间窗统计每把钥匙最近最多 100 条日志,非完整用量。',
346
402
  }
347
- const sum = summarize(all, cur, start, end)
348
- const rows = all.filter((r) => r.at >= start && r.at <= end).slice(0, 200)
349
- json(res, 200, { ok: true, range, ...sum, rows })
403
+ json(res, 200, path === '/api/usage'
404
+ ? { ok: true, range, total, ...summarize(all, cur, start, end), ...coverage, rows: rows.slice(0, 1000) }
405
+ : { ok: true, range, start, end, total, ...coverage, rows: rows.slice(0, limit) })
350
406
  return
351
407
  }
352
408
 
353
- if (path === '/api/logs' && req.method === 'GET') {
354
- const limit = Math.max(1, Math.min(500, Number(url.searchParams.get('limit')) || 200))
355
- const only = url.searchParams.get('account') || ''
356
- const { st, cur } = await stateOf()
357
- const all = []
358
- for (const [key, meta] of Object.entries(st.accounts || {})) {
359
- if (only && key !== only) continue
360
- const secret = await readAccountKey(key)
361
- if (!secret) continue
409
+ // 数据看板:站点的 /api/data/self 行按时间桶 × 模型聚合,金额留在页面换算。
410
+ if (path === '/api/dashboard' && req.method === 'GET') {
411
+ const days = Math.max(1, Math.min(29, Number(url.searchParams.get('days')) || 1));
412
+ const granularity = url.searchParams.get('granularity') || 'hour';
413
+ if (!['hour', 'day', 'week'].includes(granularity)) throw new BadRequest('粒度必须是 hour / day / week');
414
+ const { st } = await stateOf();
415
+ const end = Date.now();
416
+ const start = end - days * 86400000;
417
+ if (!st.pat) {
418
+ json(res, 200, { ok: true, available: false, reason: '需要访问令牌(PAT)才能读取数据看板' });
419
+ return;
420
+ }
421
+ try {
422
+ const rows = await readDataSelf(site, st.pat, { start, end, granularity });
423
+ json(res, 200, { ok: true, available: true, days, granularity, start, end, ...summarizeDashboard(rows, { start, end }) });
424
+ } catch (err) {
425
+ json(res, 200, { ok: true, available: false, reason: String(err?.message || err) });
426
+ }
427
+ return;
428
+ }
429
+
430
+ // 日志页顶部三个胶囊:用量 / RPM / TPM,直接取站点的 /api/log/self/stat。
431
+ // 没有 PAT 时如实标 available:false,页面显示 —,不拿本地 100 行日志冒充全量。
432
+ if (path === '/api/logs/stats' && req.method === 'GET') {
433
+ const range = url.searchParams.get('range') || 'day'
434
+ if (!['day', 'week', 'month'].includes(range)) throw new BadRequest('时间窗必须是 day / week / month')
435
+ const { st } = await stateOf()
436
+ if (!st.pat) {
437
+ json(res, 200, { ok: true, available: false, quota: 0, rpm: 0, tpm: 0, reason: '需要访问令牌(PAT)才能读取统计' })
438
+ return
439
+ }
440
+ const { start, end } = windowOf(range)
441
+ try {
442
+ const stat = await readUsageStatsSelf(site, st.pat, { start, end })
443
+ // 站点的 stat 只给实时速率(常常 0);RPM/TPM 用 /api/data/self 的同窗口均值补上,
444
+ // 和日志页顶部「平均」的口径一致。
445
+ let rpm = stat.rpm
446
+ let tpm = stat.tpm
362
447
  try {
363
- const items = await readTokenLogs(site, secret, { pageSize: 500 })
364
- all.push(...rowsOf(items, cur, meta?.label || key))
365
- } catch { /* 同上 */ }
448
+ const rows = await readDataSelf(site, st.pat, { start, end, granularity: range === 'day' ? 'hour' : 'day' })
449
+ const agg = summarizeDashboard(rows, { start, end })
450
+ rpm = agg.totals.avgRpm
451
+ tpm = agg.totals.avgTpm
452
+ } catch { /* 数据看板取不到就退回站点给的实时速率 */ }
453
+ json(res, 200, { ok: true, available: true, quota: stat.quota, rpm, tpm })
454
+ } catch (err) {
455
+ json(res, 200, { ok: true, available: false, quota: 0, rpm: 0, tpm: 0, reason: String(err?.message || err) })
366
456
  }
367
- all.sort((a, b) => b.at - a.at)
368
- json(res, 200, { ok: true, rows: all.slice(0, limit) })
457
+ return
458
+ }
459
+
460
+ if (path === '/api/subscriptions' && req.method === 'GET') {
461
+ const { st, cur } = await stateOf()
462
+ if (!st.pat) throw new BadRequest('还没有设置访问令牌(PAT),读取订阅需要 wallet:read 权限')
463
+ json(res, 200, { ok: true, ...await readSubscriptions(site, st.pat, cur) })
369
464
  return
370
465
  }
371
466
 
@@ -381,24 +476,15 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
381
476
  }
382
477
  return
383
478
  }
384
- // 推荐计划:邀请码 / 已邀请人数 / 累计奖励。站点没开这个端点就如实说没有,
385
- // 不退化成「0 人邀请」——那会让人以为奖励被吞了。
479
+ // 推荐计划:合并邀请码与真实 self 指标,部分读取失败原话放 note。
386
480
  if (path === '/api/aff' && req.method === 'GET') {
387
481
  const { st } = await stateOf()
388
482
  if (!st.pat) { json(res, 400, { ok: false, error: '还没有设置访问令牌(PAT)' }); return }
389
- let aff = null
390
- let note = ''
391
- try {
392
- aff = await readAff(site, st.pat)
393
- if (!aff) note = '站点没有返回推荐计划数据'
394
- } catch (e) {
395
- // 401/404 都当作「站点没开」,不让整页报错
396
- note = '站点没有开放推荐计划接口'
397
- }
398
- const code = aff && aff.code ? aff.code : ''
483
+ const result = await readAff(site, st.pat)
484
+ const { code, note, ...aff } = result
399
485
  json(res, 200, {
400
486
  ok: true,
401
- aff: aff ? { count: aff.count, quota: aff.quota, ...(aff.pending !== undefined ? { pending: aff.pending } : {}) } : null,
487
+ aff: Object.keys(aff).length ? aff : null,
402
488
  code,
403
489
  link: code ? `${site}/sign-up?aff=${encodeURIComponent(code)}` : '',
404
490
  note,
@@ -414,7 +500,11 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
414
500
  const boundTails = new Set(Object.values(st.accounts || {}).map((a) => String(a?.tail || '')).filter(Boolean))
415
501
  json(res, 200, {
416
502
  ok: true,
417
- keys: keys.map((k) => ({ ...k, bound: boundTails.has(tailOf(k.key)) })),
503
+ keys: keys.map((k) => {
504
+ // 列表接口绝不能把明文钥匙发给页面:只给打码串,明文只在 reveal 时按需换取。
505
+ const { key, ...rest } = k
506
+ return { ...rest, masked: maskKey(key), bound: boundTails.has(tailOf(key)) }
507
+ }),
418
508
  groups,
419
509
  })
420
510
  return
@@ -470,6 +560,26 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
470
560
  return
471
561
  }
472
562
 
563
+ if (path.startsWith('/api/keys/') && req.method === 'PUT') {
564
+ const { st } = await stateOf()
565
+ if (!st.pat) { json(res, 400, { ok: false, error: '还没有设置访问令牌(PAT)' }); return }
566
+ const id = Number(path.split('/')[3])
567
+ if (!Number.isFinite(id) || id <= 0) { json(res, 400, { ok: false, error: '钥匙 id 不对' }); return }
568
+ const cur = (await readKeys(site, st.pat)).find((k) => k.id === id)
569
+ if (!cur) { json(res, 404, { ok: false, error: '没有这把钥匙' }); return }
570
+ const b = await readBody(req)
571
+ await updateKey(site, st.pat, id, {
572
+ name: b?.name ?? cur.name,
573
+ group: b?.group ?? cur.group,
574
+ unlimited: b?.unlimited != null ? b.unlimited : cur.unlimited,
575
+ remainQuota: b?.remain != null ? b.remain : cur.remain,
576
+ expiredAt: b?.expiredAt != null ? b.expiredAt : cur.expiredAt,
577
+ status: b?.status != null ? b.status : cur.status,
578
+ })
579
+ json(res, 200, { ok: true })
580
+ return
581
+ }
582
+
473
583
  if (path.startsWith('/api/keys/') && req.method === 'DELETE') {
474
584
  const { st } = await stateOf()
475
585
  if (!st.pat) { json(res, 400, { ok: false, error: '还没有设置访问令牌(PAT)' }); return }
@@ -496,7 +606,7 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
496
606
 
497
607
  if (path === '/api/pat' && req.method === 'POST') {
498
608
  const body = await readBody(req)
499
- const pat = String(body?.pat || '').trim()
609
+ const pat = normalizePat(body?.pat)
500
610
  if (!pat) { json(res, 400, { ok: false, error: '访问令牌不能为空' }); return }
501
611
 
502
612
  // 先探能力,再决定收不收:只有站点明确说「这份凭据不行」才拒收。
@@ -508,7 +618,7 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
508
618
  json(res, 400, {
509
619
  ok: false,
510
620
  error: `这份访问令牌不能用:${String(probe.error?.message || probe.error || '站点拒绝')}`,
511
- hint: '到控制台「安全 → 访问令牌」确认它没有过期或被停用,勾上 profile:read / api_key:read 后再试。',
621
+ hint: '到控制台「安全 → 访问令牌」确认它没有过期或被停用,勾上 profile:read / api_key:read / usage:read / wallet:read 中所需权限后再试。',
512
622
  failures: probe.failures,
513
623
  })
514
624
  return