@fish-under-sea/magpie-dragonapi 0.1.4 → 0.2.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  把 [DragonAPI](https://newapi.dragon3api.com/) 接进 magpie:模型广场、余额、用量,外加一个能按分组建钥匙的本地界面。
4
4
 
5
- > 当前版本 **0.1.4**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
5
+ > 当前版本 **0.2.0**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
6
6
 
7
7
  ## 它是什么
8
8
 
@@ -25,7 +25,7 @@
25
25
  | **命令行** | `magpie plugin add @fish-under-sea/magpie-dragonapi` |
26
26
 
27
27
  npm 拉不到时(内网、镜像抽风):到 [Releases](https://github.com/Fish-under-sea/magpie-dragonapi/releases) 下
28
- `fish-under-sea-magpie-dragonapi-0.1.4.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
28
+ `fish-under-sea-magpie-dragonapi-0.2.0.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
29
29
  `plugin add` 认 `path`,和从文件夹加插件是同一条路。
30
30
 
31
31
  装好后:Settings → Plugins 里出现 **DragonAPI** 行(带一张页面),供应商列表里出现 **DragonAPI**。
@@ -84,14 +84,24 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
84
84
 
85
85
  **PAT 存在本地**:`<magpie 配置目录>/dragonapi-state.json`,权限 0600。它必须明文存——每次建钥匙都要用。文件里**不存任何 `sk-` 钥匙明文**,那些由 magpie 自己的 `plugin-auth.json` 保管。
86
86
 
87
+ 保存 PAT 时插件会先探三个只读端点(账户资料 / 钥匙列表 / 用量)来确认它真的能用:
88
+
89
+ | 情况 | 行为 |
90
+ | --- | --- |
91
+ | 三个端点都说令牌无效(401/403) | 拒收,并说清是权限不够还是令牌失效 |
92
+ | 能用一个、缺另一个 | **照样存下**,提示缺哪一格、哪些功能会失败(例如只缺 `profile:read` 时建钥匙会失败,但读用量照常) |
93
+ | 站点连不上 / 返回验证页 | **照样存下**,标成「未验证」,稍后刷新即可再确认 |
94
+ | 写不进状态文件 | 直接报错并给出文件路径——不会出现「提示已保存、重启后消失」 |
95
+
87
96
  ## 界面里有什么
88
97
 
89
98
  | 页 | 内容 |
90
99
  | --- | --- |
91
- | **模型广场** | 左侧分组筛选(14 组,带倍率与数量)、右侧双列卡片网格:每张卡给出名称/厂商/说明/计费方式/输入·输出·缓存价/分组倍率/端点数。**纯展示,没有启用/停用开关**——本站做不到 NearToken 那种按分组启停,所以这里不给假开关,也不伪造健康度数据 |
100
+ | **模型广场** | 左侧筛选(14 个分组带倍率与数量、11 家厂商带品牌图标)+ 右侧搜索、类型分段、分组横幅,双列卡片:供应商图标、名称/厂商、说明、计费方式、输入·输出·缓存价、分组倍率、端点。**纯展示,没有启用/停用开关**——本站做不到 NearToken 那种按分组启停,所以这里不给假开关,也不伪造健康度数据 |
101
+ | **模型详情** | 点卡片上的「详情」打开:价签 → 概览 → 计费方式(把 `p/c/cr` 系数、`service_tier` 倍率翻成中文)→ 每一档的实际单价 → 按用量单价。站点原文的计费表达式收在折叠块里 |
92
102
  | **余额与用量** | 每个账号的余额与已用;按天/周/月汇总;逐条流水(模型、token、费用、吞吐、首字延迟) |
93
103
  | **密钥** | 列出现有钥匙(打码)、按分组建新钥匙、建完显示一次完整明文并提供复制、删除、查看完整明文 |
94
- | **访问令牌** | 填入/清除 PAT,说明需要哪些权限 |
104
+ | **访问令牌** | 填入/清除 PAT,说明需要哪些权限,并显示实际验到的 scope |
95
105
 
96
106
  ## 价格怎么算
97
107
 
@@ -128,26 +138,53 @@ node serve.mjs
128
138
  ## 开发
129
139
 
130
140
  ```powershell
131
- npm test # 122 个用例:价格解析、目录构建、用量解析、源与刷新链路、服务冒烟、插件入口、界面
141
+ npm test # 156 个用例:价格解析、详情页 billing 折算、目录构建、用量解析、PAT 保存的四种结局、入口只导出默认工厂、源与刷新链路、服务冒烟、插件入口、界面
132
142
  ```
133
143
 
134
144
  测试用站点 2026-11-10 的真实快照([证据-站点定价快照-2026-11-10.json](证据-站点定价快照-2026-11-10.json))当夹具,站点改了写法就会被发现。
135
145
 
146
+ ### 本地实时预览(改界面时用这个)
147
+
148
+ ```powershell
149
+ node dev.mjs # http://127.0.0.1:3671/?theme=dark
150
+ node dev.mjs --sandbox # 套一层 magpie 同款沙箱 iframe
151
+ ```
152
+
153
+ 改 `ui/` 里任何文件(html / css / js)都会自动整页刷新,不需要装 magpie,也不用重装插件。
154
+
155
+ 它起两个进程内的服务:内部服务(`3672`)是真的 `lib/service.mjs`,带真实站点目录与 `/api/*`;
156
+ 开发服务(`3671`)只负责发静态文件、注入热刷新脚本、把 `/api/*` 反代过去。所以界面走的
157
+ 还是生产那条请求路径,只是文件每次从磁盘现读。
158
+
159
+ **两种模式都要看一遍**,尤其是改请求、存储、导航的时候:
160
+
161
+ | 模式 | 地址 | 什么时候用 |
162
+ | --- | --- | --- |
163
+ | 顶层直开 | `/?theme=dark` | 日常改样式最快,devtools 干净 |
164
+ | 沙箱 iframe | `/__sandbox?theme=dark` | 和 magpie 里一致:`sandbox="allow-scripts"`,安全源不透明(`localStorage` 会抛 `SecurityError`) |
165
+
166
+ 这个差异造成过真实事故:顶层一切正常,装进 magpie 后所有接口都「连不上本地服务」——
167
+ 不透明源里相对路径的 `fetch` 会被判 `Failed to fetch`。沙箱模式就是为了提前看见这类问题。
168
+
169
+ 预览状态写在 `.dev-state/`(含 PAT,已进 `.gitignore`)。
170
+
136
171
  目录结构:
137
172
 
138
173
  ```text
139
174
  index.mjs 供应商插件入口:config / auth / provider.models + 起本地服务
140
- lib/site.mjs 站点客户端(sk- 与 PAT 两条通道分开)
141
- lib/pricing.mjs 两种计费规则的解析与降级
175
+ lib/site.mjs 站点客户端(sk- 与 PAT 两条通道分开,错误带 status/kind)
176
+ lib/pricing.mjs 两种计费规则的解析与降级;详情页用的 prices / multipliers / usageRows
142
177
  lib/catalog.mjs /api/pricing → magpie 模型表(分组×模型)
143
178
  lib/catalog-source.mjs 目录的唯一所有者:缓存、条件请求、刷新、健康记录
144
179
  lib/status-source.mjs 站点参数的唯一所有者:缓存与降级
145
180
  lib/usage.mjs 日志解析、汇总、窗口
146
- lib/store.mjs 本地状态(PAT、账号元数据),原子写 0600
181
+ lib/store.mjs 本地状态(PAT、账号元数据),原子写 0600,写失败返回结构化结果
147
182
  lib/service.mjs 本地 HTTP 服务 + 全部 API(只管呈现,不缓存)
148
183
  page/ 带路页(把自己导航到本地服务)
149
184
  ui/ 真正的界面
185
+ ui/vendor-icons/ 厂商品牌图标(来自同期 magpie-neartoken 仓库,MIT)
150
186
  serve.mjs 独立启动
187
+ dev.mjs 本地实时预览(不打包进 npm)
151
188
  ```
152
189
 
153
190
  ### 两个「源」为什么单独存在
package/index.mjs CHANGED
@@ -68,7 +68,10 @@ function makeContext(input, options) {
68
68
  })
69
69
 
70
70
  function persist() {
71
- saveState(dir, state)
71
+ const r = saveState(dir, state)
72
+ // 存不下不抛(插件不能因此停摆),但必须留痕:页面按返回值报错,日志留一份。
73
+ if (!r.saved) console.error(`[dragonapi] 状态没能写进 ${r.path}:${r.error}`)
74
+ return r
72
75
  }
73
76
 
74
77
  /** 从一份 auth 里把钥匙记进内存,并把账号元数据补进 state。 */
@@ -110,11 +113,6 @@ function makeContext(input, options) {
110
113
  }
111
114
  }
112
115
 
113
- /** 让本地服务能拿到某个账号的钥匙(按 tail)。 */
114
- export function keyForTail(ctx, tail) {
115
- return ctx.secrets.get(String(tail || '')) || ''
116
- }
117
-
118
116
  export default async function dragonapi(input, options) {
119
117
  void input
120
118
  const ctx = makeContext(input, options)
@@ -146,14 +144,17 @@ export default async function dragonapi(input, options) {
146
144
  pat: ctx.state.pat,
147
145
  patHint: ctx.state.patHint,
148
146
  patScopes: ctx.state.patScopes,
147
+ patVerified: ctx.state.patVerified === true,
149
148
  enabledGroups: ctx.state.enabledGroups || [],
150
149
  }),
151
- setPat: async ({ pat, hint, scopes, user }) => {
150
+ setPat: async ({ pat, hint, scopes, user, verified }) => {
152
151
  ctx.state.pat = pat
153
152
  ctx.state.patHint = hint
154
153
  ctx.state.patScopes = scopes
154
+ ctx.state.patVerified = verified === true
155
155
  if (user) ctx.state.user = { id: user.id, name: user.username }
156
- ctx.persist()
156
+ // 把落盘结果交回去:写失败时页面必须知道,不能弹「已保存」。
157
+ return ctx.persist()
157
158
  },
158
159
  })
159
160
  .then((s) => {
package/lib/pricing.mjs CHANGED
@@ -118,6 +118,14 @@ export function usagePrices(expr) {
118
118
  export function priceOf(row, ratio, cur) {
119
119
  const groupRatio = Number(ratio) > 0 ? Number(ratio) : 1
120
120
  const symbol = cur?.symbol || '$'
121
+ // 数值单独给一份(货币单位 / 百万 token),页面要在 /1M 与 /1K 之间切换、
122
+ // 也要按价格排序——字符串没法算,所以两个都留着。
123
+ const perMNum = (v) => {
124
+ const n = Number(v)
125
+ // 保留 6 位小数:0.2 × 0.1 在浮点里是 0.020000000000000004,不收敛会让
126
+ // 「按价格排序」和显示都出现毛刺。
127
+ return Number.isFinite(n) ? Math.round(n * groupRatio * 1e6) / 1e6 : null
128
+ }
121
129
  const perM = (v) => {
122
130
  // 站点前端:单价 = 系数 × 分组倍率 ÷ 1e6,再乘「充值价系数」。
123
131
  // 我们不做充值价折算(拿不到 priceRate 时不能猜),只给系数 × 分组倍率。
@@ -190,6 +198,10 @@ export function priceOf(row, ratio, cur) {
190
198
  input: input || '—',
191
199
  output: output || '—',
192
200
  cache: cache || '—',
201
+ inputNum: co.input === undefined ? null : perMNum(co.input),
202
+ outputNum: co.output === undefined ? null : perMNum(co.output),
203
+ cacheNum: co.cacheRead === undefined ? null : perMNum(co.cacheRead),
204
+ tierCount: tiers.length,
193
205
  note: tiers.length > 1
194
206
  ? `${tiers.length} 档(${tiers.map((t) => t.name).join(' / ')}),上表是「${first.name}」档`
195
207
  : `表达式计费(${first.name})`,
@@ -213,6 +225,9 @@ export function priceOf(row, ratio, cur) {
213
225
  input: perM(input),
214
226
  output: perM(output),
215
227
  cache: cacheRatio > 0 ? perM(input * cacheRatio) : '—',
228
+ inputNum: perMNum(input),
229
+ outputNum: perMNum(output),
230
+ cacheNum: cacheRatio > 0 ? perMNum(input * cacheRatio) : null,
216
231
  note: `倍率 ${round(modelRatio)}${completion > 0 ? ` · 补全 ${round(completion)}` : ''}`,
217
232
  }
218
233
  }
@@ -220,6 +235,79 @@ export function priceOf(row, ratio, cur) {
220
235
  return { kind: 'unknown', input: '价格未知', output: '', cache: '', note: '站点没有给这个模型的计价规则' }
221
236
  }
222
237
 
238
+ /**
239
+ * parseMultipliers 取出表达式里「某个参数等于某个值时整单加倍」的规则。
240
+ *
241
+ * 站点写法:`* (param("service_tier") == "priority" ? 2 : 1)`。
242
+ * 这类修饰不属于 token 系数,混进价格里会算错,单独列出来给页面说清楚。
243
+ */
244
+ export function parseMultipliers(expr) {
245
+ if (typeof expr !== 'string' || !expr) return []
246
+ const out = []
247
+ const re = /param\(\s*"([^"]+)"\s*\)\s*==\s*"([^"]+)"\s*\?\s*([0-9.]+)\s*:\s*1/g
248
+ let m
249
+ while ((m = re.exec(expr))) {
250
+ const factor = Number(m[3])
251
+ if (!Number.isFinite(factor) || factor === 1) continue
252
+ out.push({ param: m[1], value: m[2], factor })
253
+ }
254
+ return out
255
+ }
256
+
257
+ /** coeffPrice 把一个 token 系数折成「每百万 token 多少钱」。 */
258
+ function coeffPrice(coeff, ratio, symbol) {
259
+ const n = Number(coeff)
260
+ if (coeff === undefined || coeff === null || !Number.isFinite(n)) return undefined
261
+ const value = n * (Number(ratio) > 0 ? Number(ratio) : 1)
262
+ return `${symbol}${value >= 0.01 ? value.toFixed(2) : value.toFixed(4)}/M`
263
+ }
264
+
265
+ /** zhText 从站点的多语文案里取中文,取不到就退回原文。 */
266
+ function zhText(spec) {
267
+ const d = spec?.description
268
+ if (d && typeof d === 'object') return String(d.zh || d.en || '')
269
+ if (typeof d === 'string') return d
270
+ return ''
271
+ }
272
+
273
+ /** 常见单位的中文说法:站点很多模型只给英文 unit,不给 unitLabel。 */
274
+ const UNIT_ZH = {
275
+ second: '秒', seconds: '秒', minute: '分钟', minutes: '分钟',
276
+ image: '张', images: '张', count: '次', unit: '次',
277
+ megapixel: '百万像素', megapixels: '百万像素',
278
+ token: 'token', tokens: 'token',
279
+ }
280
+
281
+ /**
282
+ * usageRowsOf 把「用量变量 × 单价」折成表格行。
283
+ *
284
+ * 视频类模型的价格随秒数 / 分辨率变化,页面上必须给出「字段 / 单位 / 单价」,
285
+ * 而不是一串 `u("seconds") * 0.16`。
286
+ */
287
+ function usageRowsOf(prices, schema, ratio, symbol) {
288
+ const out = []
289
+ for (const [field, range] of Object.entries(prices || {})) {
290
+ const spec = schema && typeof schema === 'object' ? schema[field] || {} : {}
291
+ const rawUnit = String(spec?.unit || '')
292
+ // 优先级:站点给的中文单位名 → 我们自己的常见单位表 → 站点的英文名 → 原始 unit。
293
+ // 英文名排在单位表之后:很多模型只给 unitLabel.en="second",直接用它就等于没翻。
294
+ const unit = String(spec?.unitLabel?.zh || UNIT_ZH[rawUnit] || spec?.unitLabel?.en || rawUnit)
295
+ const r = Number(ratio) > 0 ? Number(ratio) : 1
296
+ const lo = range.min * r
297
+ const hi = range.max * r
298
+ const fmt = (v) => `${symbol}${v.toFixed(4)}`
299
+ out.push({
300
+ field,
301
+ label: zhText(spec) || field,
302
+ unit,
303
+ price: lo === hi ? `${fmt(lo)}${unit ? '/' + unit : ''}` : `${fmt(lo)}–${fmt(hi)}${unit ? '/' + unit : ''}`,
304
+ min: lo,
305
+ max: hi,
306
+ })
307
+ }
308
+ return out
309
+ }
310
+
223
311
  /** 分辨率范围,从 billing_usage_schema 里读,读不到就看表达式里出现过的分辨率。 */
224
312
  function resolutionRange(row) {
225
313
  const schema = row?.billing_usage_schema
@@ -238,19 +326,57 @@ const round = (v) => String(Math.round(Number(v) * 10000) / 10000)
238
326
  /**
239
327
  * billingOf 给「模型详情」用的完整计费信息,比 priceOf 多给原始数字。
240
328
  * UI 只在用户点开单个模型时用它。
329
+ *
330
+ * 三个「已经折好、可以直接显示」的字段是详情页的关键:
331
+ *
332
+ * tiers[].prices 每一档的实际单价(X × 分组倍率),不是原始系数
333
+ * multipliers 整单倍率规则(如 service_tier=priority ×2)
334
+ * usageRows 视频/按秒模型的字段表:字段 / 单位 / 单价
335
+ *
336
+ * 之前的抽屉读的是 tiers[].input / tiers[].output——服务端从来没给过这两个
337
+ * 字段,所以分档表恒为「—」,页面只好把 mode 与原始表达式倒出来。
241
338
  */
242
- export function billingOf(row, ratio) {
339
+ export function billingOf(row, ratio, cur) {
243
340
  const mode = String(row?.billing_mode || '')
244
341
  const expr = String(row?.billing_expr || '')
342
+ const symbol = cur?.symbol || '$'
343
+ const groupRatio = Number(ratio) > 0 ? Number(ratio) : 1
245
344
  const tiers = parseTiers(expr)
345
+ const schema = row?.billing_usage_schema && typeof row.billing_usage_schema === 'object' ? row.billing_usage_schema : null
346
+ const usages = usagePrices(expr)
347
+ const isPerCall = Number(row?.quota_type) === 1
348
+
246
349
  return {
247
- mode: mode || (Number(row?.quota_type) === 1 ? 'per_call' : 'ratio'),
350
+ mode: mode || (isPerCall ? 'per_call' : 'ratio'),
351
+ modeLabel: mode === 'tiered_expr'
352
+ ? (isPerCall ? '表达式按用量计费' : '表达式分档计费')
353
+ : (isPerCall ? '按次计费' : '倍率计费'),
248
354
  expr,
249
- groupRatio: Number(ratio) > 0 ? Number(ratio) : 1,
250
- tiers: tiers.map((t) => ({ name: t.name, body: t.body, coeffs: chatCoeffs(t.body) })),
251
- usages: usagePrices(expr),
252
- schema: row?.billing_usage_schema && typeof row.billing_usage_schema === 'object' ? row.billing_usage_schema : null,
355
+ groupRatio,
356
+ currency: { symbol, code: String(cur?.code || '') },
357
+ tiers: tiers.map((t) => ({
358
+ name: t.name,
359
+ body: t.body,
360
+ coeffs: chatCoeffs(t.body),
361
+ prices: pricesOf(t.body, groupRatio, symbol),
362
+ })),
363
+ multipliers: parseMultipliers(expr),
364
+ usages,
365
+ usageRows: usageRowsOf(usages, schema, groupRatio, symbol),
366
+ schema,
253
367
  examples: Array.isArray(row?.billing_usage_examples) ? row.billing_usage_examples : [],
254
368
  variants: Array.isArray(row?.billing_plugin_variants) ? row.billing_plugin_variants : [],
255
369
  }
256
370
  }
371
+
372
+ /** pricesOf 把一档的 token 系数折成单价表;没有的系数就不出现在结果里。 */
373
+ function pricesOf(body, groupRatio, symbol) {
374
+ const co = chatCoeffs(body)
375
+ if (!co) return {}
376
+ const out = {}
377
+ for (const [key, coeff] of Object.entries(co)) {
378
+ const price = coeffPrice(coeff, groupRatio, symbol)
379
+ if (price) out[key] = price
380
+ }
381
+ return out
382
+ }
package/lib/service.mjs CHANGED
@@ -22,11 +22,11 @@ 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, readPricing, readTokenUsage, readTokenLogs, readSelf, readUsableGroups, readKeys, createKey, revealKey, deleteKey } from './site.mjs'
25
+ import { currencyOf, text, readTokenUsage, readTokenLogs, readUsableGroups, readKeys, createKey, revealKey, deleteKey, probePat } 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 { loadState, saveState, maskKey, tailOf } from './store.mjs'
29
+ import { maskKey, tailOf, statePath } from './store.mjs'
30
30
 
31
31
  const here = resolve(fileURLToPath(new URL('..', import.meta.url)))
32
32
 
@@ -85,6 +85,32 @@ class BadRequest extends Error {
85
85
  constructor(message) { super(message); this.badRequest = true }
86
86
  }
87
87
 
88
+ /**
89
+ * patWarning 给出「已保存,但你该知道」的那句话。
90
+ *
91
+ * 两种需要提醒的情况:
92
+ * 1. 令牌有效但少 scope —— 得指名道姓说清「丢的是哪几件事」,不是笼统一句「权限不足」;
93
+ * 2. 一个端点都没验通,且不是鉴权问题 —— 站连不上,令牌先存着,别吓人。
94
+ */
95
+ const SCOPE_LOSS = {
96
+ 'profile:read': '读账户资料与建钥匙',
97
+ 'api_key:read': '读钥匙列表',
98
+ 'usage:read': '读用量流水',
99
+ };
100
+
101
+ function patWarning(probe) {
102
+ if (probe.verified && probe.missing.length) {
103
+ const lost = probe.missing.map((s) => SCOPE_LOSS[s] || s).join('、');
104
+ const why = probe.failures?.[0]?.message || '权限不足';
105
+ return `已保存,但站点没有放行 ${probe.missing.join(' / ')}:${why}。会失败的是${lost},其它照常。`;
106
+ }
107
+ if (!probe.verified) {
108
+ const why = probe.failures?.[0]?.message || '站点没有响应';
109
+ return `已保存,但这次没能连上站点验证(${why})。令牌本身可能没问题,稍后点右上角「刷新」或在密钥页试一次就能确认。`;
110
+ }
111
+ return '';
112
+ }
113
+
88
114
  /** 读请求体,限制 1 MB:这里只会收 JSON 小对象。 */
89
115
  function readBody(req) {
90
116
  return new Promise((resolve_, reject) => {
@@ -108,8 +134,11 @@ function readBody(req) {
108
134
  * 静态文件:只允许 ui/ 与 page/ 两个目录,且必须在目录内。
109
135
  *
110
136
  * 路径穿越在这里不是理论风险——这个服务监听 127.0.0.1,本机任何程序都能打。
137
+ *
138
+ * 导出是给 dev.mjs 用的:本地预览也要按同样规则发静态文件,再自己实现一遍
139
+ * 只会多一份要同步维护的路径校验。返回值表示「有没有发出去」。
111
140
  */
112
- function serveFile(res, root, rel) {
141
+ export function serveFile(res, root, rel) {
113
142
  const clean = normalize(rel).replace(/^([/\\])+/, '')
114
143
  if (clean.includes('..')) return false
115
144
  const file = resolve(root, clean)
@@ -229,7 +258,13 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
229
258
  ok: true,
230
259
  site,
231
260
  siteName: site_?.siteName || 'DragonAPI',
232
- pat: { set: Boolean(st.pat), hint: st.patHint || '', scopes: st.patScopes || [] },
261
+ pat: {
262
+ set: Boolean(st.pat),
263
+ hint: st.patHint || '',
264
+ scopes: st.patScopes || [],
265
+ verified: st.patVerified === true,
266
+ stateFile: statePath(dir),
267
+ },
233
268
  currency: cur,
234
269
  accounts,
235
270
  groups: built.groups,
@@ -271,11 +306,28 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
271
306
  if (path === '/api/model' && req.method === 'GET') {
272
307
  const group = url.searchParams.get('group') || ''
273
308
  const model = url.searchParams.get('model') || ''
274
- const { cat, built } = await stateOf()
309
+ const { cat, built, cur } = await stateOf()
275
310
  const row = built.rows.find((r) => r.group === group && r.name === model)
276
311
  if (!row) { json(res, 404, { ok: false, error: '没有这个模型' }); return }
277
312
  const raw = (Array.isArray(cat.env?.data) ? cat.env.data : []).find((m) => String(m?.model_name) === model)
278
- json(res, 200, { ok: true, model: row, billing: raw ? billingOf(raw, row.groupRatio) : null })
313
+ // 同一个模型往往在好几个分组里卖(按分组定价)。详情页要能横向比较,
314
+ // 所以把同名的其他分组一起给出来,按倍率从低到高排。
315
+ const siblings = built.rows
316
+ .filter((r) => r.name === row.name)
317
+ .map((r) => ({
318
+ group: r.group,
319
+ groupRatio: r.groupRatio,
320
+ auto: r.groupAuto === true,
321
+ input: r.pricing?.input || '',
322
+ output: r.pricing?.output || '',
323
+ cache: r.pricing?.cache || '',
324
+ inputNum: Number.isFinite(r.pricing?.inputNum) ? r.pricing.inputNum : null,
325
+ outputNum: Number.isFinite(r.pricing?.outputNum) ? r.pricing.outputNum : null,
326
+ cacheNum: Number.isFinite(r.pricing?.cacheNum) ? r.pricing.cacheNum : null,
327
+ current: r.group === row.group,
328
+ }))
329
+ .sort((a, b) => (Number(a.groupRatio) || 0) - (Number(b.groupRatio) || 0) || a.group.localeCompare(b.group, 'zh'))
330
+ json(res, 200, { ok: true, model: row, billing: raw ? billingOf(raw, row.groupRatio, cur) : null, siblings })
279
331
  return
280
332
  }
281
333
 
@@ -409,24 +461,49 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
409
461
  const body = await readBody(req)
410
462
  const pat = String(body?.pat || '').trim()
411
463
  if (!pat) { json(res, 400, { ok: false, error: '访问令牌不能为空' }); return }
412
- let user
413
- try {
414
- user = await readSelf(site, pat)
415
- } catch (e) {
416
- json(res, 400, { ok: false, error: `这份访问令牌不可用:${String(e?.message || e)}` })
464
+
465
+ // 先探能力,再决定收不收:只有站点明确说「这份凭据不行」才拒收。
466
+ // 站点连不上、返回验证页这类情况照收——令牌本身可能完全正常,
467
+ // 把它当无效打回去,用户唯一的感受就是「保存失败」。
468
+ const probe = await probePat(site, pat)
469
+
470
+ if (probe.authRejected) {
471
+ json(res, 400, {
472
+ ok: false,
473
+ error: `这份访问令牌不能用:${String(probe.error?.message || probe.error || '站点拒绝')}`,
474
+ hint: '到控制台「安全 → 访问令牌」确认它没有过期或被停用,勾上 profile:read / api_key:read 后再试。',
475
+ failures: probe.failures,
476
+ })
477
+ return
478
+ }
479
+
480
+ const hint = maskKey(pat)
481
+ const saved = await setPat({ pat, hint, scopes: probe.scopes, user: probe.user, verified: probe.verified })
482
+
483
+ // 落盘失败必须说出来。之前这里不管写没写成功都回 ok,页面弹「已保存」,
484
+ // 重启后令牌就没了——那才是「访问令牌保存失败」最坑的一种表现。
485
+ if (saved && saved.saved === false) {
486
+ json(res, 500, {
487
+ ok: false,
488
+ error: `令牌本身能用,但没能写进 ${saved.path}:${saved.error || '未知原因'}。本次会话内它仍然有效,重启后会丢;请检查该文件或目录是否可写,再点一次保存。`,
489
+ pat: { set: true, hint, scopes: probe.scopes, verified: probe.verified, missing: probe.missing, persisted: false },
490
+ stateFile: saved.path,
491
+ })
417
492
  return
418
493
  }
419
- // 顺便把 scope 探出来:能读钥匙列表说明有 api_key:read,能读用量说明有 usage:read。
420
- const scopes = []
421
- if (await readKeys(site, pat).then(() => true).catch(() => false)) scopes.push('api_key:read')
422
- if (await readTokenLogs(site, '').then(() => true).catch(() => false)) scopes.push('usage:read')
423
- await setPat({ pat, hint: maskKey(pat), scopes, user })
424
- json(res, 200, { ok: true, pat: { set: true, hint: maskKey(pat), scopes }, user: { name: user.username, id: user.id } })
494
+
495
+ json(res, 200, {
496
+ ok: true,
497
+ pat: { set: true, hint, scopes: probe.scopes, verified: probe.verified, missing: probe.missing, persisted: true },
498
+ user: probe.user ? { name: probe.user.username, id: probe.user.id } : null,
499
+ warning: patWarning(probe),
500
+ stateFile: saved?.path || '',
501
+ })
425
502
  return
426
503
  }
427
504
 
428
505
  if (path === '/api/pat' && req.method === 'DELETE') {
429
- await setPat({ pat: '', hint: '', scopes: [], user: null })
506
+ await setPat({ pat: '', hint: '', scopes: [], user: null, verified: false })
430
507
  json(res, 200, { ok: true, pat: { set: false } })
431
508
  return
432
509
  }
package/lib/site.mjs CHANGED
@@ -16,6 +16,33 @@ export const DEFAULT_SITE = 'https://newapi.dragon3api.com'
16
16
  /** 一次请求最多等多久。站点正常时都在 1 秒内,超过这个数就该报错而不是挂着。 */
17
17
  const TIMEOUT_MS = 20_000
18
18
 
19
+ /**
20
+ * SiteError 是「站点这一层」的错误,带三个页面判断用的字段:
21
+ *
22
+ * status HTTP 状态码(网络层失败是 0)
23
+ * code 站点自己给的错误码,如 AUTH_UNAUTHORIZED
24
+ * kind http | network | response(不是 JSON)
25
+ *
26
+ * 为什么必须分得清:PAT 保存时「令牌无效」和「站点连不上」要给出完全不同的
27
+ * 处置——前者是用户去控制台改权限,后者是令牌本身可能没问题,不该直接拒收。
28
+ * 之前两者都只是一个 Error,结果一律被报成「这份访问令牌不可用」。
29
+ */
30
+ export class SiteError extends Error {
31
+ constructor(message, { status = 0, code = '', kind = 'http' } = {}) {
32
+ super(message)
33
+ this.name = 'SiteError'
34
+ this.status = status
35
+ this.code = code
36
+ this.kind = kind
37
+ }
38
+
39
+ /** isAuth:站点明确说「这份凭据不行」。只有这种才该拒绝保存。 */
40
+ get isAuth() {
41
+ if (this.kind !== 'http') return false
42
+ return this.status === 401 || this.status === 403 || /^AUTH_/.test(this.code)
43
+ }
44
+ }
45
+
19
46
  /** keyOf 把「凭据 + 种类」说清。调用方给错就直接抛,不留隐式回退。 */
20
47
  function headersFor(auth) {
21
48
  const h = { accept: 'application/json', 'user-agent': 'magpie-dragonapi' }
@@ -49,7 +76,14 @@ export async function siteCall(site, path, { method = 'GET', body, auth, timeout
49
76
  init.headers['content-type'] = 'application/json'
50
77
  init.body = JSON.stringify(body)
51
78
  }
52
- const res = await fetch(url, init)
79
+ let res
80
+ try {
81
+ res = await fetch(url, init)
82
+ } catch (e) {
83
+ // 连不上(DNS / TLS / 超时 / 被墙)与「站点说不行」是两件事,必须分开报。
84
+ const why = e?.name === 'TimeoutError' || e?.name === 'AbortError' ? `等满 ${timeoutMs} ms 没有响应` : String(e?.message || e)
85
+ throw new SiteError(`连不上站点(${path}):${why}`, { kind: 'network' })
86
+ }
53
87
  const text = await res.text()
54
88
  let parsed = null
55
89
  try {
@@ -57,12 +91,15 @@ export async function siteCall(site, path, { method = 'GET', body, auth, timeout
57
91
  } catch {
58
92
  // 站点偶尔会回一页 HTML(Cloudflare 挑战、502 页)。原样带一点正文出来,
59
93
  // 否则排查时只剩「不是 JSON」这一句,看不出发生了什么。
60
- throw new Error(`${path} 返回的不是 JSON(HTTP ${res.status}):${text.slice(0, 160).replace(/\s+/g, ' ')}`)
94
+ throw new SiteError(`${path} 返回的不是 JSON(HTTP ${res.status}):${text.slice(0, 160).replace(/\s+/g, ' ')}`, {
95
+ status: res.status,
96
+ kind: 'response',
97
+ })
61
98
  }
62
99
  if (!res.ok) {
63
100
  const why = parsed?.message || parsed?.error?.message || parsed?.error || ''
64
- const code = parsed?.code || parsed?.error?.code || ''
65
- throw new Error(`${path} HTTP ${res.status}${code ? ' ' + code : ''}${why ? ':' + why : ''}`)
101
+ const code = String(parsed?.code || parsed?.error?.code || '')
102
+ throw new SiteError(`${path} HTTP ${res.status}${code ? ' ' + code : ''}${why ? ':' + why : ''}`, { status: res.status, code })
66
103
  }
67
104
  return parsed
68
105
  }
@@ -299,3 +336,66 @@ export async function verifyPat(site, pat) {
299
336
  const self = await readSelf(site, pat)
300
337
  return { ok: true, kind: 'pat', user: self }
301
338
  }
339
+
340
+ /**
341
+ * PAT 通道的用量流水(`/api/log/self`)。
342
+ *
343
+ * 注意别拿 `readTokenLogs` 冒充:那条走的是 sk- 钥匙的 `/api/log/token`,
344
+ * 用 PAT 打过去、或者干脆传空串,都只会拿到 401。之前探测 `usage:read`
345
+ * 用的正是 `readTokenLogs(site, '')`,所以这个 scope 永远探不出来。
346
+ */
347
+ export async function readUsageSelf(site, pat, { pageSize = 1 } = {}) {
348
+ const env = await siteCall(site, `/api/log/self?p=0&page_size=${Math.max(1, Math.min(100, pageSize))}`, {
349
+ auth: { kind: 'pat', token: pat },
350
+ })
351
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝读用量')
352
+ return env?.data
353
+ }
354
+
355
+ /**
356
+ * probePat 一次性探三个只读端点,判断这份 PAT 到底能干什么。
357
+ *
358
+ * 为什么要「宽松」:站点把一份令牌的 scope 卡得很细,`/api/user/self` 要
359
+ * `profile:read`。只用它做准入门槛时,一份只能读钥匙列表的 PAT 会被整份
360
+ * 拒收——用户看到的是「保存失败」,实际只是权限少了一格。
361
+ *
362
+ * 所以判定分三种,调用方据此决定「拒收 / 收下但警告 / 收下」:
363
+ *
364
+ * authRejected / 三个端点全部 401/403 —— 令牌本身不行,拒收
365
+ * verified / 至少一个端点通了 —— 令牌有效,记录能用的 scope
366
+ * networkOnly / 一个都没通,但错误都不是鉴权错误 —— 站点连不上,令牌先存下
367
+ */
368
+ export async function probePat(site, pat) {
369
+ const checks = [
370
+ { scope: 'profile:read', run: () => readSelf(site, pat) },
371
+ { scope: 'api_key:read', run: () => readKeys(site, pat, { pageSize: 1 }) },
372
+ { scope: 'usage:read', run: () => readUsageSelf(site, pat) },
373
+ ]
374
+
375
+ const results = []
376
+ for (const check of checks) {
377
+ try {
378
+ results.push({ scope: check.scope, ok: true, value: await check.run() })
379
+ } catch (error) {
380
+ results.push({ scope: check.scope, ok: false, error })
381
+ }
382
+ }
383
+
384
+ const ok = results.filter((r) => r.ok)
385
+ const failed = results.filter((r) => !r.ok)
386
+ const authFails = failed.filter((r) => r.error?.isAuth === true)
387
+ const otherFails = failed.filter((r) => r.error?.isAuth !== true)
388
+ const user = results[0].ok ? results[0].value : null
389
+
390
+ return {
391
+ user,
392
+ scopes: ok.map((r) => r.scope),
393
+ missing: failed.map((r) => r.scope),
394
+ verified: ok.length > 0,
395
+ authRejected: ok.length === 0 && authFails.length === failed.length && failed.length === checks.length,
396
+ networkOnly: ok.length === 0 && otherFails.length === failed.length,
397
+ // 只报第一个失败原因:三个都是同一件事时,列三遍没有帮助。
398
+ error: failed.length ? failed[0].error : null,
399
+ failures: failed.map((r) => ({ scope: r.scope, kind: r.error?.kind || 'http', message: String(r.error?.message || r.error) })),
400
+ }
401
+ }