@fish-under-sea/magpie-dragonapi 0.2.1 → 0.3.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/lib/site.mjs CHANGED
@@ -1,401 +1,437 @@
1
- // 站点客户端:DragonAPI 的每一次出站请求都从这里走。
2
- //
3
- // 两条通道,凭据不同,能做的事也不同:
4
- //
5
- // sk- 钥匙 中转鉴权用。能调模型、能读这把钥匙的余额与逐条用量。
6
- // nap_ 令牌 控制台鉴权(PAT,带 scope)。能读账户、分组、钥匙列表,
7
- // 也能建钥匙 / 删钥匙 / 看完整钥匙。建不了 PAT:站点要求
8
- // 浏览器会话,插件代不了。
9
- //
10
- // 所以这里把两者分开:调用方必须说清用的是哪一种,不允许「有哪个用哪个」
11
- // 的隐式回退——那把 PAT 当成钥匙发出去,会得到一条让人摸不着头脑的 401。
12
-
13
- /** 站点根地址。可以由插件 options 覆盖(自建站、测试站)。 */
14
- export const DEFAULT_SITE = 'https://newapi.dragon3api.com'
15
-
16
- /** 一次请求最多等多久。站点正常时都在 1 秒内,超过这个数就该报错而不是挂着。 */
17
- const TIMEOUT_MS = 20_000
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
-
46
- /** keyOf 把「凭据 + 种类」说清。调用方给错就直接抛,不留隐式回退。 */
47
- function headersFor(auth) {
48
- const h = { accept: 'application/json', 'user-agent': 'magpie-dragonapi' }
49
- if (!auth) return h
50
- const raw = String(auth.token || '').trim()
51
- if (!raw) return h
52
- if (auth.kind === 'key') {
53
- // 中转鉴权只认 sk-;站点自己也会 TrimPrefix("sk-"),但我们保留前缀,
54
- // 因为 /api/usage/token/ 的实现里同样会 TrimPrefix,两种写法都认。
55
- h.authorization = 'Bearer ' + raw
56
- return h
57
- }
58
- if (auth.kind === 'pat') {
59
- // 控制台鉴权:PAT 形如 nap_xxx,直接放 Bearer。
60
- h.authorization = 'Bearer ' + raw
61
- return h
62
- }
63
- throw new Error(`未知的凭据种类:${String(auth.kind)}`)
64
- }
65
-
66
- /** siteCall 发一次请求并把 JSON 解析出来;非 2xx 抛出带站点原话的错误。 */
67
- export async function siteCall(site, path, { method = 'GET', body, auth, timeoutMs = TIMEOUT_MS, headers } = {}) {
68
- const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
69
- const url = base + path
70
- const init = {
71
- method,
72
- headers: { ...headersFor(auth), ...(headers || {}) },
73
- signal: AbortSignal.timeout(timeoutMs),
74
- }
75
- if (body !== undefined) {
76
- init.headers['content-type'] = 'application/json'
77
- init.body = JSON.stringify(body)
78
- }
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
- }
87
- const text = await res.text()
88
- let parsed = null
89
- try {
90
- parsed = text ? JSON.parse(text) : null
91
- } catch {
92
- // 站点偶尔会回一页 HTML(Cloudflare 挑战、502 页)。原样带一点正文出来,
93
- // 否则排查时只剩「不是 JSON」这一句,看不出发生了什么。
94
- throw new SiteError(`${path} 返回的不是 JSON(HTTP ${res.status}):${text.slice(0, 160).replace(/\s+/g, ' ')}`, {
95
- status: res.status,
96
- kind: 'response',
97
- })
98
- }
99
- if (!res.ok) {
100
- const why = parsed?.message || parsed?.error?.message || parsed?.error || ''
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 })
103
- }
104
- return parsed
105
- }
106
-
107
- /** 站点参数。钱怎么显示、额度怎么折算全在这里。 */
108
- export async function readStatus(site) {
109
- const env = await siteCall(site, '/api/status')
110
- const d = env?.data
111
- if (!d || typeof d !== 'object') throw new Error('/api/status 没有 data')
112
- return {
113
- siteName: String(d.system_name || 'DragonAPI'),
114
- version: String(d.version || ''),
115
- quotaPerUnit: Number(d.quota_per_unit) > 0 ? Number(d.quota_per_unit) : 500000,
116
- // 站点自己的显示规则:quota_display_type 是 USD / CNY / TOKENS / CUSTOM,
117
- // display_in_currency 决定是否按货币展示。这两个都要读,只读一个会算错。
118
- displayType: String(d.quota_display_type || 'USD').toUpperCase(),
119
- displayInCurrency: d.display_in_currency === true,
120
- usdExchangeRate: Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate) > 0
121
- ? Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate)
122
- : 1,
123
- customSymbol: typeof d.custom_currency_symbol === 'string' ? d.custom_currency_symbol.trim() : '',
124
- customRate: Number(d.custom_currency_exchange_rate) > 0 ? Number(d.custom_currency_exchange_rate) : 1,
125
- turnstile: d.turnstile_check === true,
126
- logo: String(d.logo || ''),
127
- raw: d,
128
- }
129
- }
130
-
131
- /**
132
- * currencyOf 把站点参数折成「怎么印钱」。
133
- *
134
- * 符号优先级:quota_display_type 认识的码 → 非占位符的自定义符号 → 默认。
135
- * 站点给的 custom_currency_symbol 常常是通用占位符 ¤,直接显示很难看。
136
- * 读不到就返回一组保守默认值,但绝不把 per 折成 1——那会把额度原值当金额,
137
- * 余额直接放大五十万倍。
138
- */
139
- export function currencyOf(status) {
140
- const byCode = { CNY: '¥', USD: '$', EUR: '€', GBP: '£', JPY: '¥' }
141
- const code = String(status?.displayType || 'USD').toUpperCase()
142
- const custom = String(status?.customSymbol || '')
143
- const symbol = byCode[code]
144
- || (custom && custom !== '¤' ? custom : (code === 'CNY' ? '¥' : '$'))
145
- const per = Number(status?.quotaPerUnit) > 0 ? Number(status.quotaPerUnit) : 500000
146
- // 币种汇率:USD 恒为 1;CNY 用站点汇率;CUSTOM 用自定义汇率。
147
- const rate = code === 'USD' ? 1
148
- : code === 'CNY' ? (Number(status?.usdExchangeRate) > 0 ? Number(status.usdExchangeRate) : 1)
149
- : code === 'CUSTOM' ? (Number(status?.customRate) > 0 ? Number(status.customRate) : 1)
150
- : 1
151
- return { symbol, per, rate, code, display: status?.displayInCurrency !== false }
152
- }
153
-
154
- /** money 把 quota 折成站点显示的那笔钱(保留两位,用于余额与流水)。 */
155
- export function money(quota, cur) {
156
- const n = Number(quota)
157
- if (!Number.isFinite(n)) return '—'
158
- const base = n / (cur.per > 0 ? cur.per : 1)
159
- const value = cur.display && cur.rate > 0 ? base * cur.rate : base
160
- return value.toFixed(2)
161
- }
162
-
163
- /** text 是带符号的一笔钱。 */
164
- export function text(quota, cur) {
165
- return cur.symbol + money(quota, cur)
166
- }
167
-
168
- /** 公开目录。不需要任何凭据,站点本来就把它给所有人看。 */
169
- export async function readPricing(site, { etag, lastModified } = {}) {
170
- const headers = {}
171
- // 条件请求:实测站点认 If-None-Match 与 If-Modified-Since,命中回 304。
172
- // 目录动得不勤,这一条能把轮询成本压到几乎为零。
173
- if (etag) headers['if-none-match'] = etag
174
- if (lastModified) headers['if-modified-since'] = lastModified
175
- const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
176
- const res = await fetch(base + '/api/pricing', {
177
- headers: { accept: 'application/json', 'user-agent': 'magpie-dragonapi', ...headers },
178
- signal: AbortSignal.timeout(TIMEOUT_MS),
179
- })
180
- if (res.status === 304) return { notModified: true, etag, lastModified }
181
- const nextEtag = res.headers.get('etag') || ''
182
- const nextLast = res.headers.get('last-modified') || ''
183
- const text_ = await res.text()
184
- let env
185
- try {
186
- env = JSON.parse(text_)
187
- } catch {
188
- throw new Error(`/api/pricing 返回的不是 JSON(HTTP ${res.status})`)
189
- }
190
- if (!res.ok || env?.success === false) {
191
- throw new Error(`/api/pricing HTTP ${res.status}:${env?.message || '站点拒绝'}`)
192
- }
193
- return { notModified: false, env, etag: nextEtag, lastModified: nextLast }
194
- }
195
-
196
- /** 一把钥匙的额度与用量。这是 sk- 通道里最要紧的一个端点。 */
197
- export async function readTokenUsage(site, key) {
198
- const env = await siteCall(site, '/api/usage/token/', { auth: { kind: 'key', token: key } })
199
- const d = env?.data
200
- if (!d || typeof d !== 'object') throw new Error('/api/usage/token/ 没有 data')
201
- return {
202
- name: String(d.name || ''),
203
- granted: Number(d.total_granted) || 0,
204
- used: Number(d.total_used) || 0,
205
- available: Number(d.total_available) || 0,
206
- unlimited: d.unlimited_quota === true,
207
- expiresAt: Number(d.expires_at) || 0,
208
- modelLimits: d.model_limits && typeof d.model_limits === 'object' ? d.model_limits : null,
209
- modelLimitsEnabled: d.model_limits_enabled === true,
210
- // 钥匙允许查用户额度时才有;不允许就没有这个字段,别当成 0。
211
- userQuota: d.user_quota && typeof d.user_quota === 'object'
212
- ? { available: Number(d.user_quota.total_available) || 0, used: Number(d.user_quota.total_used) || 0 }
213
- : null,
214
- }
215
- }
216
-
217
- /** 逐条用量。站点按钥匙给最近 1000 条。 */
218
- export async function readTokenLogs(site, key, { pageSize = 100 } = {}) {
219
- const env = await siteCall(site, `/api/log/token?p=0&page_size=${Math.max(1, Math.min(1000, pageSize))}`, {
220
- auth: { kind: 'key', token: key },
221
- })
222
- if (env?.success === false) throw new Error(env?.message || '站点拒绝读用量')
223
- const d = env?.data
224
- const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : Array.isArray(d?.data) ? d.data : []
225
- return items
226
- }
227
-
228
- /** PAT 能读到的账户资料。 */
229
- export async function readSelf(site, pat) {
230
- const env = await siteCall(site, '/api/user/self', { auth: { kind: 'pat', token: pat } })
231
- const d = env?.data
232
- if (!d || typeof d !== 'object') throw new Error('/api/user/self 没有 data')
233
- return {
234
- id: Number(d.id) || 0,
235
- username: String(d.username || ''),
236
- displayName: String(d.display_name || ''),
237
- group: String(d.group || ''),
238
- quota: Number(d.quota) || 0,
239
- usedQuota: Number(d.used_quota) || 0,
240
- affCode: String(d.aff_code || ''),
241
- raw: d,
242
- }
243
- }
244
-
245
- /** 当前账号可用的分组。建钥匙时要从这里挑,不能凭目录里的分组名瞎猜。 */
246
- export async function readUsableGroups(site, pat) {
247
- const env = await siteCall(site, '/api/user/self/groups', { auth: { kind: 'pat', token: pat } })
248
- const d = env?.data
249
- // 这个端点历史上给过两种形状:字符串数组,或 {组名: 说明} 对象。
250
- if (Array.isArray(d)) return d.map((x) => String(x)).filter(Boolean)
251
- if (d && typeof d === 'object') return Object.keys(d)
252
- return []
253
- }
254
-
255
- /** 钥匙列表。站点只给打码后的 key。 */
256
- export async function readKeys(site, pat, { pageSize = 100 } = {}) {
257
- const env = await siteCall(site, `/api/token/?p=0&size=${Math.max(1, Math.min(100, pageSize))}`, {
258
- auth: { kind: 'pat', token: pat },
259
- })
260
- const d = env?.data
261
- const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : []
262
- return items.map((t) => ({
263
- id: Number(t?.id) || 0,
264
- name: String(t?.name || ''),
265
- key: String(t?.key || ''),
266
- group: String(t?.group || ''),
267
- status: Number(t?.status) || 0,
268
- used: Number(t?.used_quota) || 0,
269
- remain: Number(t?.remain_quota) || 0,
270
- unlimited: t?.unlimited_quota === true,
271
- createdAt: Number(t?.created_time) || 0,
272
- expiredAt: Number(t?.expired_time) || 0,
273
- }))
274
- }
275
-
276
- /**
277
- * 建一把钥匙。
278
- *
279
- * 关键点:这个端点不需要浏览器会话,也不需要二次验证(上游 AddToken 里
280
- * 没有 RequireSecurityProof),所以带着 api_key:write 的 PAT 就能建。
281
- * 但**响应里不含钥匙明文**——只有 {success, message},明文得再调一次 reveal。
282
- * 也就是说「建钥匙」与「拿明文」是两次请求,中间失败会留下一把没人知道
283
- * 明文的钥匙,所以调用方必须把这两步当成一件事处理(见 service.mjs)。
284
- */
285
- export async function createKey(site, pat, { name, group, unlimited = true, remainQuota = 0, expiredAt = -1 }) {
286
- const body = {
287
- name: String(name || '').slice(0, 50),
288
- group: String(group || ''),
289
- unlimited_quota: unlimited === true,
290
- remain_quota: unlimited ? 0 : Math.max(0, Math.floor(Number(remainQuota) || 0)),
291
- expired_time: Number.isFinite(expiredAt) ? Math.floor(expiredAt) : -1,
292
- model_limits_enabled: false,
293
- model_limits: '',
294
- allow_ips: '',
295
- allow_user_quota_query: true,
296
- }
297
- const env = await siteCall(site, '/api/token/', { method: 'POST', body, auth: { kind: 'pat', token: pat } })
298
- if (env?.success === false) throw new Error(env?.message || '站点拒绝建钥匙')
299
- return { ok: true }
300
- }
301
-
302
- /** 读一把钥匙的明文。需要 api_key:reveal 权限。 */
303
- export async function revealKey(site, pat, id) {
304
- const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}/key`, {
305
- method: 'POST',
306
- auth: { kind: 'pat', token: pat },
307
- })
308
- if (env?.success === false) throw new Error(env?.message || '站点拒绝给出钥匙')
309
- const secret = String(env?.data?.key || '')
310
- if (!secret) throw new Error('站点没有返回钥匙明文')
311
- return secret
312
- }
313
-
314
- /** 删一把钥匙。 */
315
- export async function deleteKey(site, pat, id) {
316
- const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}`, {
317
- method: 'DELETE',
318
- auth: { kind: 'pat', token: pat },
319
- })
320
- if (env?.success === false) throw new Error(env?.message || '站点拒绝删除钥匙')
321
- return { ok: true }
322
- }
323
-
324
- /**
325
- * 校验一份凭据是不是真的能用,并尽量取回它代表的名字。
326
- *
327
- * 这里刻意分成两条:sk- 走 /api/usage/token/,PAT 走 /api/user/self。
328
- * 用错通道会得到 401,而 401 的正文长得差不多,很容易被误读成「钥匙失效」。
329
- */
330
- export async function verifyKey(site, key) {
331
- const usage = await readTokenUsage(site, key)
332
- return { ok: true, kind: 'key', name: usage.name, usage }
333
- }
334
-
335
- export async function verifyPat(site, pat) {
336
- const self = await readSelf(site, pat)
337
- return { ok: true, kind: 'pat', user: self }
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
- }
1
+ // 站点客户端:DragonAPI 的每一次出站请求都从这里走。
2
+ //
3
+ // 两条通道,凭据不同,能做的事也不同:
4
+ //
5
+ // sk- 钥匙 中转鉴权用。能调模型、能读这把钥匙的余额与逐条用量。
6
+ // nap_ 令牌 控制台鉴权(PAT,带 scope)。能读账户、分组、钥匙列表,
7
+ // 也能建钥匙 / 删钥匙 / 看完整钥匙。建不了 PAT:站点要求
8
+ // 浏览器会话,插件代不了。
9
+ //
10
+ // 所以这里把两者分开:调用方必须说清用的是哪一种,不允许「有哪个用哪个」
11
+ // 的隐式回退——那把 PAT 当成钥匙发出去,会得到一条让人摸不着头脑的 401。
12
+
13
+ /** 站点根地址。可以由插件 options 覆盖(自建站、测试站)。 */
14
+ export const DEFAULT_SITE = 'https://newapi.dragon3api.com'
15
+
16
+ /** 一次请求最多等多久。站点正常时都在 1 秒内,超过这个数就该报错而不是挂着。 */
17
+ const TIMEOUT_MS = 20_000
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
+
46
+ /** keyOf 把「凭据 + 种类」说清。调用方给错就直接抛,不留隐式回退。 */
47
+ function headersFor(auth) {
48
+ const h = { accept: 'application/json', 'user-agent': 'magpie-dragonapi' }
49
+ if (!auth) return h
50
+ const raw = String(auth.token || '').trim()
51
+ if (!raw) return h
52
+ if (auth.kind === 'key') {
53
+ // 中转鉴权只认 sk-;站点自己也会 TrimPrefix("sk-"),但我们保留前缀,
54
+ // 因为 /api/usage/token/ 的实现里同样会 TrimPrefix,两种写法都认。
55
+ h.authorization = 'Bearer ' + raw
56
+ return h
57
+ }
58
+ if (auth.kind === 'pat') {
59
+ // 控制台鉴权:PAT 形如 nap_xxx,直接放 Bearer。
60
+ h.authorization = 'Bearer ' + raw
61
+ return h
62
+ }
63
+ throw new Error(`未知的凭据种类:${String(auth.kind)}`)
64
+ }
65
+
66
+ /** siteCall 发一次请求并把 JSON 解析出来;非 2xx 抛出带站点原话的错误。 */
67
+ export async function siteCall(site, path, { method = 'GET', body, auth, timeoutMs = TIMEOUT_MS, headers } = {}) {
68
+ const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
69
+ const url = base + path
70
+ const init = {
71
+ method,
72
+ headers: { ...headersFor(auth), ...(headers || {}) },
73
+ signal: AbortSignal.timeout(timeoutMs),
74
+ }
75
+ if (body !== undefined) {
76
+ init.headers['content-type'] = 'application/json'
77
+ init.body = JSON.stringify(body)
78
+ }
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
+ }
87
+ const text = await res.text()
88
+ let parsed = null
89
+ try {
90
+ parsed = text ? JSON.parse(text) : null
91
+ } catch {
92
+ // 站点偶尔会回一页 HTML(Cloudflare 挑战、502 页)。原样带一点正文出来,
93
+ // 否则排查时只剩「不是 JSON」这一句,看不出发生了什么。
94
+ throw new SiteError(`${path} 返回的不是 JSON(HTTP ${res.status}):${text.slice(0, 160).replace(/\s+/g, ' ')}`, {
95
+ status: res.status,
96
+ kind: 'response',
97
+ })
98
+ }
99
+ if (!res.ok) {
100
+ const why = parsed?.message || parsed?.error?.message || parsed?.error || ''
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 })
103
+ }
104
+ return parsed
105
+ }
106
+
107
+ /** 站点参数。钱怎么显示、额度怎么折算全在这里。 */
108
+ export async function readStatus(site) {
109
+ const env = await siteCall(site, '/api/status')
110
+ const d = env?.data
111
+ if (!d || typeof d !== 'object') throw new Error('/api/status 没有 data')
112
+ return {
113
+ siteName: String(d.system_name || 'DragonAPI'),
114
+ version: String(d.version || ''),
115
+ quotaPerUnit: Number(d.quota_per_unit) > 0 ? Number(d.quota_per_unit) : 500000,
116
+ // 站点自己的显示规则:quota_display_type 是 USD / CNY / TOKENS / CUSTOM,
117
+ // display_in_currency 决定是否按货币展示。这两个都要读,只读一个会算错。
118
+ displayType: String(d.quota_display_type || 'USD').toUpperCase(),
119
+ displayInCurrency: d.display_in_currency === true,
120
+ usdExchangeRate: Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate) > 0
121
+ ? Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate)
122
+ : 1,
123
+ customSymbol: typeof d.custom_currency_symbol === 'string' ? d.custom_currency_symbol.trim() : '',
124
+ customRate: Number(d.custom_currency_exchange_rate) > 0 ? Number(d.custom_currency_exchange_rate) : 1,
125
+ turnstile: d.turnstile_check === true,
126
+ logo: String(d.logo || ''),
127
+ raw: d,
128
+ }
129
+ }
130
+
131
+ /**
132
+ * currencyOf 把站点参数折成「怎么印钱」。
133
+ *
134
+ * 符号优先级:quota_display_type 认识的码 → 非占位符的自定义符号 → 默认。
135
+ * 站点给的 custom_currency_symbol 常常是通用占位符 ¤,直接显示很难看。
136
+ * 读不到就返回一组保守默认值,但绝不把 per 折成 1——那会把额度原值当金额,
137
+ * 余额直接放大五十万倍。
138
+ */
139
+ export function currencyOf(status) {
140
+ const byCode = { CNY: '¥', USD: '$', EUR: '€', GBP: '£', JPY: '¥' }
141
+ const code = String(status?.displayType || 'USD').toUpperCase()
142
+ const custom = String(status?.customSymbol || '')
143
+ const symbol = byCode[code]
144
+ || (custom && custom !== '¤' ? custom : (code === 'CNY' ? '¥' : '$'))
145
+ const per = Number(status?.quotaPerUnit) > 0 ? Number(status.quotaPerUnit) : 500000
146
+ // 币种汇率:USD 恒为 1;CNY 用站点汇率;CUSTOM 用自定义汇率。
147
+ const rate = code === 'USD' ? 1
148
+ : code === 'CNY' ? (Number(status?.usdExchangeRate) > 0 ? Number(status.usdExchangeRate) : 1)
149
+ : code === 'CUSTOM' ? (Number(status?.customRate) > 0 ? Number(status.customRate) : 1)
150
+ : 1
151
+ return { symbol, per, rate, code, display: status?.displayInCurrency !== false }
152
+ }
153
+
154
+ /** money 把 quota 折成站点显示的那笔钱(保留两位,用于余额与流水)。 */
155
+ export function money(quota, cur) {
156
+ const n = Number(quota)
157
+ if (!Number.isFinite(n)) return '—'
158
+ const base = n / (cur.per > 0 ? cur.per : 1)
159
+ const value = cur.display && cur.rate > 0 ? base * cur.rate : base
160
+ return value.toFixed(2)
161
+ }
162
+
163
+ /** text 是带符号的一笔钱。 */
164
+ export function text(quota, cur) {
165
+ return cur.symbol + money(quota, cur)
166
+ }
167
+
168
+ /** 公开目录。不需要任何凭据,站点本来就把它给所有人看。 */
169
+ export async function readPricing(site, { etag, lastModified } = {}) {
170
+ const headers = {}
171
+ // 条件请求:实测站点认 If-None-Match 与 If-Modified-Since,命中回 304。
172
+ // 目录动得不勤,这一条能把轮询成本压到几乎为零。
173
+ if (etag) headers['if-none-match'] = etag
174
+ if (lastModified) headers['if-modified-since'] = lastModified
175
+ const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
176
+ const res = await fetch(base + '/api/pricing', {
177
+ headers: { accept: 'application/json', 'user-agent': 'magpie-dragonapi', ...headers },
178
+ signal: AbortSignal.timeout(TIMEOUT_MS),
179
+ })
180
+ if (res.status === 304) return { notModified: true, etag, lastModified }
181
+ const nextEtag = res.headers.get('etag') || ''
182
+ const nextLast = res.headers.get('last-modified') || ''
183
+ const text_ = await res.text()
184
+ let env
185
+ try {
186
+ env = JSON.parse(text_)
187
+ } catch {
188
+ throw new Error(`/api/pricing 返回的不是 JSON(HTTP ${res.status})`)
189
+ }
190
+ if (!res.ok || env?.success === false) {
191
+ throw new Error(`/api/pricing HTTP ${res.status}:${env?.message || '站点拒绝'}`)
192
+ }
193
+ return { notModified: false, env, etag: nextEtag, lastModified: nextLast }
194
+ }
195
+
196
+ /** 一把钥匙的额度与用量。这是 sk- 通道里最要紧的一个端点。 */
197
+ export async function readTokenUsage(site, key) {
198
+ const env = await siteCall(site, '/api/usage/token/', { auth: { kind: 'key', token: key } })
199
+ const d = env?.data
200
+ if (!d || typeof d !== 'object') throw new Error('/api/usage/token/ 没有 data')
201
+ return {
202
+ name: String(d.name || ''),
203
+ granted: Number(d.total_granted) || 0,
204
+ used: Number(d.total_used) || 0,
205
+ available: Number(d.total_available) || 0,
206
+ unlimited: d.unlimited_quota === true,
207
+ expiresAt: Number(d.expires_at) || 0,
208
+ modelLimits: d.model_limits && typeof d.model_limits === 'object' ? d.model_limits : null,
209
+ modelLimitsEnabled: d.model_limits_enabled === true,
210
+ // 钥匙允许查用户额度时才有;不允许就没有这个字段,别当成 0。
211
+ userQuota: d.user_quota && typeof d.user_quota === 'object'
212
+ ? { available: Number(d.user_quota.total_available) || 0, used: Number(d.user_quota.total_used) || 0 }
213
+ : null,
214
+ }
215
+ }
216
+
217
+ /** 逐条用量。站点按钥匙给最近 1000 条。 */
218
+ export async function readTokenLogs(site, key, { pageSize = 100 } = {}) {
219
+ const env = await siteCall(site, `/api/log/token?p=0&page_size=${Math.max(1, Math.min(1000, pageSize))}`, {
220
+ auth: { kind: 'key', token: key },
221
+ })
222
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝读用量')
223
+ const d = env?.data
224
+ const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : Array.isArray(d?.data) ? d.data : []
225
+ return items
226
+ }
227
+
228
+ /** PAT 能读到的账户资料。 */
229
+ export async function readSelf(site, pat) {
230
+ const env = await siteCall(site, '/api/user/self', { auth: { kind: 'pat', token: pat } })
231
+ const d = env?.data
232
+ if (!d || typeof d !== 'object') throw new Error('/api/user/self 没有 data')
233
+ return {
234
+ id: Number(d.id) || 0,
235
+ username: String(d.username || ''),
236
+ displayName: String(d.display_name || ''),
237
+ group: String(d.group || ''),
238
+ quota: Number(d.quota) || 0,
239
+ usedQuota: Number(d.used_quota) || 0,
240
+ affCode: String(d.aff_code || ''),
241
+ raw: d,
242
+ }
243
+ }
244
+
245
+ /**
246
+ * 推荐计划的数据:邀请码、已邀请人数、累计奖励额度。
247
+ *
248
+ * `/api/user/aff` 是 New API 的可选端点,不是每个站点都开;形状也可能变,
249
+ * 所以这里全部按可选处理——拿不到就返回 null,让界面如实显示「站点没有提供」,
250
+ * 而不是把 undefined 印出来。
251
+ */
252
+ export async function readAff(site, pat) {
253
+ const env = await siteCall(site, '/api/user/aff', { auth: { kind: 'pat', token: pat } })
254
+ const d = env && env.data
255
+ if (!d || typeof d !== 'object') return null
256
+ return {
257
+ code: String(d.aff_code ?? d.affCode ?? ''),
258
+ count: Number(d.aff_count ?? d.affCount ?? 0) || 0,
259
+ quota: Number(d.aff_quota ?? d.affQuota ?? 0) || 0,
260
+ historyQuota: Number(d.aff_history_quota ?? 0) || 0,
261
+ // 「待确认」列:站点没给这个数字就不渲染那一列(New API 各部署键名不一,
262
+ // 两个常见写法都认;拿不到时界面只少一列,不报错)
263
+ pending: Number.isFinite(Number(d.aff_pending_quota ?? d.pending_quota)) ? Number(d.aff_pending_quota ?? d.pending_quota) : undefined,
264
+ }
265
+ }
266
+
267
+ /**
268
+ * 把推荐计划的累计奖励转入余额。
269
+ *
270
+ * 端点 `/api/user/aff_transfer` 是 New API 的标准接口(无请求体,整笔转入)。
271
+ * 我们没有它的返回结构可依,所以原样把站点的 message 带回去——
272
+ * 成功失败都以站点为准,不在这里替它编一句「已转入」。
273
+ */
274
+ export async function transferAff(site, pat) {
275
+ const env = await siteCall(site, '/api/user/aff_transfer', {
276
+ method: 'POST',
277
+ auth: { kind: 'pat', token: pat },
278
+ })
279
+ return { ok: env?.success !== false, message: String(env?.message || ''), data: env?.data ?? null }
280
+ }
281
+ /** 当前账号可用的分组。建钥匙时要从这里挑,不能凭目录里的分组名瞎猜。 */
282
+ export async function readUsableGroups(site, pat) {
283
+ const env = await siteCall(site, '/api/user/self/groups', { auth: { kind: 'pat', token: pat } })
284
+ const d = env?.data
285
+ // 这个端点历史上给过两种形状:字符串数组,或 {组名: 说明} 对象。
286
+ if (Array.isArray(d)) return d.map((x) => String(x)).filter(Boolean)
287
+ if (d && typeof d === 'object') return Object.keys(d)
288
+ return []
289
+ }
290
+
291
+ /** 钥匙列表。站点只给打码后的 key。 */
292
+ export async function readKeys(site, pat, { pageSize = 100 } = {}) {
293
+ const env = await siteCall(site, `/api/token/?p=0&size=${Math.max(1, Math.min(100, pageSize))}`, {
294
+ auth: { kind: 'pat', token: pat },
295
+ })
296
+ const d = env?.data
297
+ const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : []
298
+ return items.map((t) => ({
299
+ id: Number(t?.id) || 0,
300
+ name: String(t?.name || ''),
301
+ key: String(t?.key || ''),
302
+ group: String(t?.group || ''),
303
+ status: Number(t?.status) || 0,
304
+ used: Number(t?.used_quota) || 0,
305
+ remain: Number(t?.remain_quota) || 0,
306
+ unlimited: t?.unlimited_quota === true,
307
+ createdAt: Number(t?.created_time) || 0,
308
+ expiredAt: Number(t?.expired_time) || 0,
309
+ }))
310
+ }
311
+
312
+ /**
313
+ * 建一把钥匙。
314
+ *
315
+ * 关键点:这个端点不需要浏览器会话,也不需要二次验证(上游 AddToken 里
316
+ * 没有 RequireSecurityProof),所以带着 api_key:write 的 PAT 就能建。
317
+ * 但**响应里不含钥匙明文**——只有 {success, message},明文得再调一次 reveal。
318
+ * 也就是说「建钥匙」与「拿明文」是两次请求,中间失败会留下一把没人知道
319
+ * 明文的钥匙,所以调用方必须把这两步当成一件事处理(见 service.mjs)。
320
+ */
321
+ export async function createKey(site, pat, { name, group, unlimited = true, remainQuota = 0, expiredAt = -1 }) {
322
+ const body = {
323
+ name: String(name || '').slice(0, 50),
324
+ group: String(group || ''),
325
+ unlimited_quota: unlimited === true,
326
+ remain_quota: unlimited ? 0 : Math.max(0, Math.floor(Number(remainQuota) || 0)),
327
+ expired_time: Number.isFinite(expiredAt) ? Math.floor(expiredAt) : -1,
328
+ model_limits_enabled: false,
329
+ model_limits: '',
330
+ allow_ips: '',
331
+ allow_user_quota_query: true,
332
+ }
333
+ const env = await siteCall(site, '/api/token/', { method: 'POST', body, auth: { kind: 'pat', token: pat } })
334
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝建钥匙')
335
+ return { ok: true }
336
+ }
337
+
338
+ /** 读一把钥匙的明文。需要 api_key:reveal 权限。 */
339
+ export async function revealKey(site, pat, id) {
340
+ const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}/key`, {
341
+ method: 'POST',
342
+ auth: { kind: 'pat', token: pat },
343
+ })
344
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝给出钥匙')
345
+ const secret = String(env?.data?.key || '')
346
+ if (!secret) throw new Error('站点没有返回钥匙明文')
347
+ return secret
348
+ }
349
+
350
+ /** 删一把钥匙。 */
351
+ export async function deleteKey(site, pat, id) {
352
+ const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}`, {
353
+ method: 'DELETE',
354
+ auth: { kind: 'pat', token: pat },
355
+ })
356
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝删除钥匙')
357
+ return { ok: true }
358
+ }
359
+
360
+ /**
361
+ * 校验一份凭据是不是真的能用,并尽量取回它代表的名字。
362
+ *
363
+ * 这里刻意分成两条:sk- 走 /api/usage/token/,PAT 走 /api/user/self。
364
+ * 用错通道会得到 401,而 401 的正文长得差不多,很容易被误读成「钥匙失效」。
365
+ */
366
+ export async function verifyKey(site, key) {
367
+ const usage = await readTokenUsage(site, key)
368
+ return { ok: true, kind: 'key', name: usage.name, usage }
369
+ }
370
+
371
+ export async function verifyPat(site, pat) {
372
+ const self = await readSelf(site, pat)
373
+ return { ok: true, kind: 'pat', user: self }
374
+ }
375
+
376
+ /**
377
+ * PAT 通道的用量流水(`/api/log/self`)。
378
+ *
379
+ * 注意别拿 `readTokenLogs` 冒充:那条走的是 sk- 钥匙的 `/api/log/token`,
380
+ * 用 PAT 打过去、或者干脆传空串,都只会拿到 401。之前探测 `usage:read`
381
+ * 用的正是 `readTokenLogs(site, '')`,所以这个 scope 永远探不出来。
382
+ */
383
+ export async function readUsageSelf(site, pat, { pageSize = 1 } = {}) {
384
+ const env = await siteCall(site, `/api/log/self?p=0&page_size=${Math.max(1, Math.min(100, pageSize))}`, {
385
+ auth: { kind: 'pat', token: pat },
386
+ })
387
+ if (env?.success === false) throw new Error(env?.message || '站点拒绝读用量')
388
+ return env?.data
389
+ }
390
+
391
+ /**
392
+ * probePat 一次性探三个只读端点,判断这份 PAT 到底能干什么。
393
+ *
394
+ * 为什么要「宽松」:站点把一份令牌的 scope 卡得很细,`/api/user/self` 要
395
+ * `profile:read`。只用它做准入门槛时,一份只能读钥匙列表的 PAT 会被整份
396
+ * 拒收——用户看到的是「保存失败」,实际只是权限少了一格。
397
+ *
398
+ * 所以判定分三种,调用方据此决定「拒收 / 收下但警告 / 收下」:
399
+ *
400
+ * authRejected / 三个端点全部 401/403 —— 令牌本身不行,拒收
401
+ * verified / 至少一个端点通了 —— 令牌有效,记录能用的 scope
402
+ * networkOnly / 一个都没通,但错误都不是鉴权错误 —— 站点连不上,令牌先存下
403
+ */
404
+ export async function probePat(site, pat) {
405
+ const checks = [
406
+ { scope: 'profile:read', run: () => readSelf(site, pat) },
407
+ { scope: 'api_key:read', run: () => readKeys(site, pat, { pageSize: 1 }) },
408
+ { scope: 'usage:read', run: () => readUsageSelf(site, pat) },
409
+ ]
410
+
411
+ const results = []
412
+ for (const check of checks) {
413
+ try {
414
+ results.push({ scope: check.scope, ok: true, value: await check.run() })
415
+ } catch (error) {
416
+ results.push({ scope: check.scope, ok: false, error })
417
+ }
418
+ }
419
+
420
+ const ok = results.filter((r) => r.ok)
421
+ const failed = results.filter((r) => !r.ok)
422
+ const authFails = failed.filter((r) => r.error?.isAuth === true)
423
+ const otherFails = failed.filter((r) => r.error?.isAuth !== true)
424
+ const user = results[0].ok ? results[0].value : null
425
+
426
+ return {
427
+ user,
428
+ scopes: ok.map((r) => r.scope),
429
+ missing: failed.map((r) => r.scope),
430
+ verified: ok.length > 0,
431
+ authRejected: ok.length === 0 && authFails.length === failed.length && failed.length === checks.length,
432
+ networkOnly: ok.length === 0 && otherFails.length === failed.length,
433
+ // 只报第一个失败原因:三个都是同一件事时,列三遍没有帮助。
434
+ error: failed.length ? failed[0].error : null,
435
+ failures: failed.map((r) => ({ scope: r.scope, kind: r.error?.kind || 'http', message: String(r.error?.message || r.error) })),
436
+ }
437
+ }