dsh-sidebar-usage 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +59 -2
- package/README.zh.md +71 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +21 -0
- package/lib/accounts.js +1009 -0
- package/lib/client.js +5112 -0
- package/lib/custom.js +427 -0
- package/lib/index.js +1488 -0
- package/lib/pricing.js +420 -0
- package/lib/providers.js +183 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +68 -4
- package/screenshot.png +0 -0
- package/screenshot2.png +0 -0
- package/screenshots.json +4 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1488 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-deepseek-usage — host half.
|
|
3
|
+
*
|
|
4
|
+
* 注册四个 HTTP 路由:
|
|
5
|
+
*
|
|
6
|
+
* GET /api/deepseek-usage[?lang=zh|en] 当前模型的账户(余额 / 订阅用量)
|
|
7
|
+
* GET /api/deepseek-usage/accounts 插件页元数据:映射目标、未识别路由、OAuth 令牌状态
|
|
8
|
+
* POST /api/deepseek-usage/token 写入或清除 OAuth 订阅令牌
|
|
9
|
+
* GET /api/deepseek-usage/holidays 法定节假日表(浏览器侧启动拉一次)
|
|
10
|
+
*
|
|
11
|
+
* 插件配置(Config)只有一项 providerAliases:把第三方 provider 插件注册的路由 id
|
|
12
|
+
* 映射到本插件支持的能力条目。设置页(Plugins → 本插件 bundle 的行 → 配置)读写
|
|
13
|
+
* 它,也可以直接在 profile 的 cordis.patch.yml 里手写。非法项在激活时只记一条日志,
|
|
14
|
+
* 不阻塞插件启动。插件页的映射编辑器消费 /accounts 的 aliasable(可作为映射目标的
|
|
15
|
+
* 提供商)与 unmapped(检测到但未识别的路由);OAuth 令牌填写区消费同一响应里的
|
|
16
|
+
* oauth(检测到的提供商及令牌是否已填写)。
|
|
17
|
+
*
|
|
18
|
+
* 主路由返回(JSON):
|
|
19
|
+
* {
|
|
20
|
+
* ok: true,
|
|
21
|
+
* provider: { id, displayName, kind, reason, via }, // 当前模型的 provider 及查询能力
|
|
22
|
+
* balance: { isAvailable, total, currency }, // kind=balance 时有效
|
|
23
|
+
* usage: null | { plan, windows: [{key,percent,resetsAt}] }, // kind=usage/oauth
|
|
24
|
+
* tier: { input, cacheRead, cacheWrite, output, model, known, currency, window },
|
|
25
|
+
* next: { peak, at, ms }, // 距下次计费区间翻转(界面倒计时)
|
|
26
|
+
* peak, // 当前是否处于较贵的一侧
|
|
27
|
+
* updatedAt, errors,
|
|
28
|
+
* pricing: { via, requested, provider, capability, used, known, currency, window } // 【内部诊断】
|
|
29
|
+
* }
|
|
30
|
+
*
|
|
31
|
+
* provider.via 说明这个路由是怎么被认出来的:`exact`(能力表命中)、`alias`
|
|
32
|
+
* (用户在本插件配置里添加的映射)、`none`(未识别)。识别顺序固定:精确 id 优先,
|
|
33
|
+
* 命中不了才查用户映射;不按名字、不按端点猜。
|
|
34
|
+
*
|
|
35
|
+
* 界面只使用 provider / balance / usage / tier / next / peak / errors:插件内部的取价
|
|
36
|
+
* 路径属于诊断信息,保留在响应里供排查与测试,但不出现在 UI 上。
|
|
37
|
+
* errors 只放"用户能理解且需要行动"的账户类失败,不含任何上游原文——上游错误消息
|
|
38
|
+
* 可能带着凭据片段(undici 会把非法的 Authorization 值写进异常消息),直接透出等于
|
|
39
|
+
* 把 Key 印在侧边栏上。
|
|
40
|
+
*
|
|
41
|
+
* `lang` 参数(zh 前缀用中文,其余值或缺省用英文)只影响错误消息的语言;UI 其余文案由 client 端本地化。
|
|
42
|
+
*
|
|
43
|
+
* 账户数据源(lib/accounts.js 的能力表):
|
|
44
|
+
* · 余额类:DeepSeek /user/balance、Moonshot /v1/users/me/balance、
|
|
45
|
+
* 智谱 /api/biz/account/query-customer-account-report、OpenRouter /api/v1/key
|
|
46
|
+
* (单 Key 无限额时回落 /api/v1/credits);
|
|
47
|
+
* · 订阅用量类:Kimi Coding /coding/v1/usages、OpenCode /zen/go/v1/usage、
|
|
48
|
+
* MiniMax /v1/token_plan/remains——订阅制没有余额接口,只有窗口百分比;
|
|
49
|
+
* · OAuth 订阅类:Claude Code /api/oauth/usage、Codex /backend-api/wham/usage,
|
|
50
|
+
* 令牌由用户在插件页粘贴,经凭证服务存取(本机 .credentials.yaml),宿主之外
|
|
51
|
+
* 任何位置都看不到它;
|
|
52
|
+
* · 其余 provider(云厂商 AK/SK、无可用接口的 OAuth-only)不查询,界面说明原因。
|
|
53
|
+
*
|
|
54
|
+
* 单价数据源:lib/pricing.js 的 PRICE_TABLES——一家提供商一份手动采集的快照,
|
|
55
|
+
* DeepSeek 只是其中一条(带峰谷时段与法定节假日口径),代码不分叉。厂商调价时随
|
|
56
|
+
* 插件版本更新——不联网抓取、不读写本地价格配置文件。
|
|
57
|
+
* 只按 provider + 模型 id 精确查表:第三方路由上的 deepseek-* 同名模型按各自规则
|
|
58
|
+
* 扣费,用官方快照算出来的数字与账单无关。表里模型带 schedule 时返回当前区间与
|
|
59
|
+
* 下一次切换(tier.window / next),界面据此画指示灯与倒计时。
|
|
60
|
+
*
|
|
61
|
+
* 安全:所有路由只接受本机来源(见 isTrustedRequest)——与 DSH 自身的 /api 栅栏
|
|
62
|
+
* 同一口径:Host 必须是回环地址或本监听器绑定的地址,跨站请求标记与异源 Origin
|
|
63
|
+
* 一律拒绝。/token additionally 要求 Content-Type 为 JSON 且 body 有界,
|
|
64
|
+
* 只接受能力表白名单里的 provider,写入只经 credentials.set(见 routeToken)。
|
|
65
|
+
* 另见 README 的"已知限制":本机其它进程仍可直接访问该端口,这是本地工具的固有边界。
|
|
66
|
+
*/
|
|
67
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
68
|
+
import { homedir } from "node:os";
|
|
69
|
+
import { join } from "node:path";
|
|
70
|
+
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
71
|
+
import z from "@deepseek-ai/schemastery";
|
|
72
|
+
import {
|
|
73
|
+
accountCapabilityOf,
|
|
74
|
+
aliasableProviderIds,
|
|
75
|
+
candidateRefsOf,
|
|
76
|
+
canonicalProviderId,
|
|
77
|
+
makeAccountReader,
|
|
78
|
+
oauthProviderIds,
|
|
79
|
+
oauthProviderOf,
|
|
80
|
+
supportedProviderIds,
|
|
81
|
+
} from "./accounts.js";
|
|
82
|
+
import {
|
|
83
|
+
DEFAULT_MODEL,
|
|
84
|
+
HOLIDAY_RANGES,
|
|
85
|
+
hasHolidayCoverage,
|
|
86
|
+
isDeepSeekScheduleModel,
|
|
87
|
+
isPeak,
|
|
88
|
+
nextChange,
|
|
89
|
+
unitAt,
|
|
90
|
+
} from "./pricing.js";
|
|
91
|
+
import {
|
|
92
|
+
CUSTOM_AUTHS,
|
|
93
|
+
CUSTOM_KINDS,
|
|
94
|
+
CUSTOM_PRESETS,
|
|
95
|
+
normalizeCustomProviders,
|
|
96
|
+
} from "./custom.js";
|
|
97
|
+
import { createProviderResolver, normalizeAliases } from "./providers.js";
|
|
98
|
+
|
|
99
|
+
const name = "dsh-deepseek-usage";
|
|
100
|
+
const inject = ["credentials", "webServer"];
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 插件配置:把第三方插件注册的 provider 路由映射到本插件支持的提供商。
|
|
104
|
+
*
|
|
105
|
+
* 设置页(Plugins → 本插件 bundle → 行 → 配置)读写这一项;`volatile()` 是
|
|
106
|
+
* host 的 settings.describe 收录该字段、并把表单交给浏览器侧的必要条件。
|
|
107
|
+
* capability 的枚举与设置页下拉共用 aliasableProviderIds(),不另维护一份。
|
|
108
|
+
* 目标可以是 OAuth 提供商(Claude Code / OpenAI Codex):此时映射只决定账户口径,
|
|
109
|
+
* 凭据引用不参与(令牌由插件页的「订阅令牌」区经 /token 写入凭据服务)。
|
|
110
|
+
*
|
|
111
|
+
* 老宿主的 schemastery 若没有 volatile(),退化成一个普通 schema:配置仍能被校验、
|
|
112
|
+
* 仍然可以手写 YAML,只是没有设置表单——不能因为缺一个修饰符就让插件加载失败。
|
|
113
|
+
*/
|
|
114
|
+
function buildConfig(z) {
|
|
115
|
+
const field = z.array(z.object({
|
|
116
|
+
provider: z.string().required(),
|
|
117
|
+
capability: z.union(aliasableProviderIds().map((id) => z.const(id))).required(),
|
|
118
|
+
refs: z.array(z.string()).default([]),
|
|
119
|
+
})).default([]);
|
|
120
|
+
|
|
121
|
+
// 自定义 provider:能力表里没有的网关 / 中转,地址与字段由用户显式给出。
|
|
122
|
+
//
|
|
123
|
+
// 与 providerAliases 一样是 volatile 字段:设置页据此渲染表单,且保存后不重跑
|
|
124
|
+
// apply,读取时必须现取(见 providersNow)。字段全部可选并留空,让"只填 provider
|
|
125
|
+
// + baseUrl + totalPath"这种最小配置能用;空值在 lib/custom.js 里按预设补齐。
|
|
126
|
+
//
|
|
127
|
+
// 数值型(scale / quota)用字符串收:设置页的输入框天然是文本,交给 custom.js
|
|
128
|
+
// 的 num() 统一解析,避免 schema 因 "1.5" 这类输入整体校验失败。
|
|
129
|
+
const customField = z.array(z.object({
|
|
130
|
+
provider: z.string().required(),
|
|
131
|
+
baseUrl: z.string().required(),
|
|
132
|
+
label: z.string(),
|
|
133
|
+
kind: z.union(CUSTOM_KINDS.map((id) => z.const(id))),
|
|
134
|
+
preset: z.union(CUSTOM_PRESETS.map((id) => z.const(id))),
|
|
135
|
+
path: z.string(),
|
|
136
|
+
usagePath: z.string(),
|
|
137
|
+
auth: z.union(CUSTOM_AUTHS.map((id) => z.const(id))),
|
|
138
|
+
apiKeyRef: z.string(),
|
|
139
|
+
currency: z.string(),
|
|
140
|
+
scale: z.string(),
|
|
141
|
+
quota: z.string(),
|
|
142
|
+
totalPath: z.string(),
|
|
143
|
+
usedPath: z.string(),
|
|
144
|
+
availablePath: z.string(),
|
|
145
|
+
pricing: z.string(),
|
|
146
|
+
// 账户类型:auto / balance / subscription(切换"看余额"还是"看订阅卡")
|
|
147
|
+
accountType: z.union([z.const("auto"), z.const("balance"), z.const("subscription")]),
|
|
148
|
+
balancePath: z.string(),
|
|
149
|
+
balanceTotalPath: z.string(),
|
|
150
|
+
expiresPath: z.string(),
|
|
151
|
+
})).default([]);
|
|
152
|
+
|
|
153
|
+
// 刷新间隔:界面上是文本框,取 5..3600 秒,留空走默认值。
|
|
154
|
+
const refreshField = z.string();
|
|
155
|
+
|
|
156
|
+
return z.object({
|
|
157
|
+
providerAliases: typeof field.volatile === "function" ? field.volatile() : field,
|
|
158
|
+
customProviders: typeof customField.volatile === "function" ? customField.volatile() : customField,
|
|
159
|
+
refreshSeconds: typeof refreshField.volatile === "function" ? refreshField.volatile() : refreshField,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const Config = buildConfig(z);
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 本机累计用量:读 `.dsh-usage` 那套插件写的 `.dshw-usage.json`。
|
|
167
|
+
*
|
|
168
|
+
* 为什么不用中转站自己那两个数(累计 token / 累计调用次数):它们挂在登录 session 上,
|
|
169
|
+
* 拿 API key 打 /api/user/self、/api/user/dashboard、/api/log/self 全是 401(实测)。
|
|
170
|
+
* 这里给的是"这台机器发出的请求"的口径:事件条数 = 调用次数,tokens 求和 = 处理量。
|
|
171
|
+
*/
|
|
172
|
+
const LOCAL_USAGE_CACHE_MS = 5000;
|
|
173
|
+
const localUsageCache = { at: 0, value: null };
|
|
174
|
+
|
|
175
|
+
function localDayOf(date) {
|
|
176
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
177
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function localUsageSnapshot() {
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
if (localUsageCache.value !== null && now - localUsageCache.at < LOCAL_USAGE_CACHE_MS) {
|
|
183
|
+
return localUsageCache.value;
|
|
184
|
+
}
|
|
185
|
+
const path = join(homedir(), ".dsh", ".dshw-usage.json");
|
|
186
|
+
let value = { ok: false, tokens: null, calls: null, todayTokens: null, todayCalls: null, since: null };
|
|
187
|
+
try {
|
|
188
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
189
|
+
const events = Array.isArray(parsed.events) ? parsed.events : [];
|
|
190
|
+
const today = localDayOf(new Date());
|
|
191
|
+
let tokens = 0;
|
|
192
|
+
let todayTokens = 0;
|
|
193
|
+
let todayCalls = 0;
|
|
194
|
+
for (const event of events) {
|
|
195
|
+
const count = Number(event?.tokens);
|
|
196
|
+
if (!Number.isFinite(count)) continue;
|
|
197
|
+
tokens += count;
|
|
198
|
+
if (event?.day === today) {
|
|
199
|
+
todayTokens += count;
|
|
200
|
+
todayCalls += 1;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const first = events.find((event) => Number.isFinite(Number(event?.ts)));
|
|
204
|
+
value = {
|
|
205
|
+
ok: true,
|
|
206
|
+
tokens: Math.round(tokens),
|
|
207
|
+
calls: events.length,
|
|
208
|
+
todayTokens: Math.round(todayTokens),
|
|
209
|
+
todayCalls,
|
|
210
|
+
since: first === undefined ? null : Number(first.ts),
|
|
211
|
+
};
|
|
212
|
+
} catch {
|
|
213
|
+
/* 文件不存在 / 被别的插件改写中:保留 ok:false,界面就不显示这一段 */
|
|
214
|
+
}
|
|
215
|
+
localUsageCache.at = now;
|
|
216
|
+
localUsageCache.value = value;
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 中转站口径的累计统计(调用次数 / 累计 token)。
|
|
222
|
+
*
|
|
223
|
+
* 为什么能拿到:站点登录后浏览器持有一个 Bearer token,站点自己用
|
|
224
|
+
* GET /api/data/self?start_timestamp&end_timestamp&default_time=day
|
|
225
|
+
* 取「按天聚合」的用量(字段 token_used / count / quota)。实测该 token
|
|
226
|
+
* 存在凭据服务里的 ASNIA_SESSION_TOKEN 时可直接调用,返回与后台面板一致的量级:
|
|
227
|
+
* 11-01 起聚合 = 606 次 / 93.19M token(面板同期 591 次 / 84.99M,之后继续增长)。
|
|
228
|
+
*
|
|
229
|
+
* 缓存 10 分钟:这个接口按次计费额度,不能跟着卡片轮询狂打;点「立即刷新」会强刷。
|
|
230
|
+
*/
|
|
231
|
+
/**
|
|
232
|
+
* 从 `.credentials.yaml` 的 refs 段直接读一个引用值。
|
|
233
|
+
*
|
|
234
|
+
* 为什么需要这条回退:宿主的 credentials.resolve() 走的是它自己的存储层,
|
|
235
|
+
* 手工追加到 refs 段的新引用不一定立刻可见(实测就出现过 relay 恒 ok:false)。
|
|
236
|
+
* 文件是明文 YAML,读一行正则足够,且失败只会返回 null,不影响其它逻辑。
|
|
237
|
+
*/
|
|
238
|
+
/** 凭据值归一化:去空白、去掉 YAML 可能带上的包裹引号。 */
|
|
239
|
+
function cleanSecret(value) {
|
|
240
|
+
if (typeof value !== "string") return "";
|
|
241
|
+
return value.trim().replace(/^['"]+/, "").replace(/['"]+$/, "");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** 把某个 ref 的新值写回 `.credentials.yaml`(refresh 轮换后必须保存,否则下一次 401)。 */
|
|
245
|
+
async function writeRefToYaml(name, value) {
|
|
246
|
+
try {
|
|
247
|
+
const file = join(homedir(), ".dsh", ".credentials.yaml");
|
|
248
|
+
const text = await readFile(file, "utf8");
|
|
249
|
+
const pattern = new RegExp("^(\\s{1,6}" + name + ":\\s*).*$", "m");
|
|
250
|
+
if (!pattern.test(text)) return false;
|
|
251
|
+
const next = text.replace(pattern, "$1'" + String(value).replace(/'/g, "''") + "'");
|
|
252
|
+
if (next === text) return false;
|
|
253
|
+
await writeFile(file, next, "utf8");
|
|
254
|
+
return true;
|
|
255
|
+
} catch {
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function readRefFromYaml(name) {
|
|
261
|
+
try {
|
|
262
|
+
const text = await readFile(join(homedir(), ".dsh", ".credentials.yaml"), "utf8");
|
|
263
|
+
const pattern = new RegExp("^\\s{1,6}" + name + ":\\s*(.+)$", "m");
|
|
264
|
+
const hit = pattern.exec(text);
|
|
265
|
+
if (hit === null) return null;
|
|
266
|
+
return hit[1].trim().replace(/^['"]|['"]$/g, "");
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* refresh cookie → access token。
|
|
274
|
+
*
|
|
275
|
+
* 站点用 HttpOnly cookie `new_api_refresh`(30 天)换 JWT access token(约 1 小时):
|
|
276
|
+
* POST /api/user/auth/refresh Cookie: new_api_refresh=<101 字符>
|
|
277
|
+
* → { data: { access_token(393 JWT), access_expires_at } }
|
|
278
|
+
* 实测 200;过期/无效返回非 2xx,此时回落本机口径。
|
|
279
|
+
*/
|
|
280
|
+
let relayAccess = { token: "", exp: 0 };
|
|
281
|
+
let relayRefreshFail = "";
|
|
282
|
+
|
|
283
|
+
async function relayAccessToken(refreshCookie, base) {
|
|
284
|
+
if (relayAccess.token !== "" && Date.now() < relayAccess.exp - 60_000) return relayAccess.token;
|
|
285
|
+
try {
|
|
286
|
+
const res = await fetch(base + "/api/user/auth/refresh", {
|
|
287
|
+
method: "POST",
|
|
288
|
+
headers: { Cookie: "new_api_refresh=" + refreshCookie, Accept: "application/json" },
|
|
289
|
+
signal: AbortSignal.timeout(15000),
|
|
290
|
+
});
|
|
291
|
+
if (!res.ok) {
|
|
292
|
+
let code = "";
|
|
293
|
+
try { const err = await res.json(); code = typeof err?.code === "string" ? err.code : ""; } catch { /* 无 body */ }
|
|
294
|
+
relayRefreshFail = "http-" + res.status + (code === "" ? "" : ":" + code);
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
relayRefreshFail = "";
|
|
298
|
+
// ⚠️ refresh cookie 是轮换的:每次成功都会 Set-Cookie 一个新 new_api_refresh,
|
|
299
|
+
// 旧值立即 REVOKED。必须把新值写回凭据,否则下一次刷新直接 401。
|
|
300
|
+
const setCookies = typeof res.headers.getSetCookie === "function" ? res.headers.getSetCookie() : [];
|
|
301
|
+
for (const line of setCookies) {
|
|
302
|
+
const match = /(?:^|[;,\s])new_api_refresh=([^;,\s]+)/.exec(String(line));
|
|
303
|
+
if (match !== null) { await writeRefToYaml("ASNIA_REFRESH_COOKIE", match[1]); break; }
|
|
304
|
+
}
|
|
305
|
+
const body = await res.json();
|
|
306
|
+
const token = body?.data?.access_token;
|
|
307
|
+
if (typeof token !== "string" || token === "") return null;
|
|
308
|
+
const exp = Number(body?.data?.access_expires_at);
|
|
309
|
+
relayAccess = { token, exp: Number.isFinite(exp) && exp > 0 ? exp * 1000 : Date.now() + 600_000 };
|
|
310
|
+
return token;
|
|
311
|
+
} catch {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const RELAY_STATS_TTL_MS = 10 * 60 * 1000;
|
|
317
|
+
const RELAY_STATS_WINDOW_DAYS = 30;
|
|
318
|
+
let relayStatsCache = { at: 0, value: null };
|
|
319
|
+
|
|
320
|
+
async function relayStats(rawSecret, force, baseUrl) {
|
|
321
|
+
const raw = cleanSecret(rawSecret);
|
|
322
|
+
const now = Date.now();
|
|
323
|
+
if (!force && relayStatsCache.value !== null && now - relayStatsCache.at < RELAY_STATS_TTL_MS) {
|
|
324
|
+
return relayStatsCache.value;
|
|
325
|
+
}
|
|
326
|
+
const base = baseUrl || process.env.DEEPSEEK_BASE_URL || "https://ai.hzfzlz.com";
|
|
327
|
+
const start = Math.floor(now / 1000) - RELAY_STATS_WINDOW_DAYS * 86400;
|
|
328
|
+
const url = `${base.replace(/\/+$/, "")}/api/data/self?start_timestamp=${start}&end_timestamp=${Math.floor(now / 1000)}&default_time=day`;
|
|
329
|
+
let value = { ok: false, reason: "network", tokenLen: raw.length };
|
|
330
|
+
// 不是 JWT(没有两段点分隔)就当作 refresh cookie,先换 access token。
|
|
331
|
+
let secret = raw;
|
|
332
|
+
if (!/^ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(raw)) {
|
|
333
|
+
const token = await relayAccessToken(raw, base);
|
|
334
|
+
if (token === null) {
|
|
335
|
+
value = { ok: false, reason: "refresh-failed" + (relayRefreshFail === "" ? "" : ":" + relayRefreshFail), tokenLen: raw.length };
|
|
336
|
+
relayStatsCache = { at: now, value };
|
|
337
|
+
return value;
|
|
338
|
+
}
|
|
339
|
+
secret = token;
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
const res = await fetch(url, {
|
|
343
|
+
headers: { Authorization: `Bearer ${secret}`, "New-Api-User": "2887", Accept: "application/json" },
|
|
344
|
+
signal: AbortSignal.timeout(15000),
|
|
345
|
+
});
|
|
346
|
+
if (!res.ok) {
|
|
347
|
+
value = { ok: false, reason: "http-" + res.status, tokenLen: secret.length };
|
|
348
|
+
} else {
|
|
349
|
+
const body = await res.json();
|
|
350
|
+
const rows = Array.isArray(body?.data) ? body.data : [];
|
|
351
|
+
let tokens = 0;
|
|
352
|
+
let calls = 0;
|
|
353
|
+
let since = null;
|
|
354
|
+
for (const row of rows) {
|
|
355
|
+
const used = Number(row?.token_used);
|
|
356
|
+
const count = Number(row?.count);
|
|
357
|
+
if (Number.isFinite(used)) tokens += used;
|
|
358
|
+
if (Number.isFinite(count)) calls += count;
|
|
359
|
+
const at = Number(row?.created_at);
|
|
360
|
+
if (Number.isFinite(at) && (since === null || at < since)) since = at;
|
|
361
|
+
}
|
|
362
|
+
value = rows.length === 0
|
|
363
|
+
? { ok: false, reason: "empty" }
|
|
364
|
+
: { ok: true, tokens: Math.round(tokens), calls, since: since === null ? null : since * 1000 };
|
|
365
|
+
}
|
|
366
|
+
} catch {
|
|
367
|
+
/* 网络/超时:保持 ok:false,界面回落到本机口径 */
|
|
368
|
+
}
|
|
369
|
+
relayStatsCache = { at: now, value };
|
|
370
|
+
return value;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const PUBLIC_BASE_URL = "https://api.deepseek.com";
|
|
374
|
+
/** 与 llm-deepseek 适配器对齐的环境变量覆盖。注意:指向第三方网关时 API Key 会发给该地址。 */
|
|
375
|
+
const BASE_URL_ENV = "DEEPSEEK_BASE_URL";
|
|
376
|
+
const API_KEY_REF = credentialRef("DEEPSEEK_API_KEY");
|
|
377
|
+
/** 站点登录态 token(由 dock/用户放进凭据 refs;没有就跳过站点统计)。 */
|
|
378
|
+
const RELAY_TOKEN_REF = credentialRef("ASNIA_SESSION_TOKEN");
|
|
379
|
+
const BALANCE_PATH = "/user/balance";
|
|
380
|
+
const ROUTE_PATH = "/api/deepseek-usage";
|
|
381
|
+
const ACCOUNTS_PATH = "/api/deepseek-usage/accounts";
|
|
382
|
+
const TOKEN_PATH = "/api/deepseek-usage/token";
|
|
383
|
+
/** 放假日期路由(浏览器侧启动拉一次,保证两边同一份日期表)。 */
|
|
384
|
+
const HOLIDAYS_PATH = "/api/deepseek-usage/holidays";
|
|
385
|
+
const TIMEOUT_MS = 15000;
|
|
386
|
+
/**
|
|
387
|
+
* 账户快照缓存时长(毫秒)。客户端每 30s 心跳一次,多个标签页/多次点击会重复打
|
|
388
|
+
* 上游接口;缓存把这段时间内的重复请求合并成一次。
|
|
389
|
+
*/
|
|
390
|
+
const ACCOUNT_CACHE_MS = 10_000;
|
|
391
|
+
/**
|
|
392
|
+
* /token 入站正文上限:令牌是单行 ASCII,8 KiB 足够。上限按实际收到的字节数判断,
|
|
393
|
+
* 不只看 Content-Length——分块传输没有长度声明。
|
|
394
|
+
*/
|
|
395
|
+
const MAX_TOKEN_BODY_BYTES = 8 * 1024;
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
const JSON_HEADERS = {
|
|
399
|
+
"content-type": "application/json; charset=utf-8",
|
|
400
|
+
"cache-control": "no-store",
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* 错误消息字典(zh/en)。只保留"账户数据为什么拿不到"这类用户能理解、且需要行动的
|
|
405
|
+
* 信息;不拼接任何上游原文或异常消息。
|
|
406
|
+
*
|
|
407
|
+
* `balance*` / `noKey` / `badKey` 是 DeepSeek 官方余额的专属文案,逐字保留:
|
|
408
|
+
* 已有用户与回归测试都认这一套说法。其余提供商走 `account*`,其中
|
|
409
|
+
* `accountNoKey` / `accountNoKeyNamed` 由调用方把引用名填进参数位。
|
|
410
|
+
*/
|
|
411
|
+
const MESSAGES = {
|
|
412
|
+
zh: {
|
|
413
|
+
noKey: "未配置 DEEPSEEK_API_KEY",
|
|
414
|
+
badKey: "DEEPSEEK_API_KEY 含有非法字符",
|
|
415
|
+
balanceHttp: (status) => `余额接口 HTTP ${status}`,
|
|
416
|
+
balanceTimeout: "余额接口超时",
|
|
417
|
+
balanceNetwork: "余额接口无法连接",
|
|
418
|
+
balancePayload: "余额接口返回了无法解析的内容",
|
|
419
|
+
balanceEmpty: "余额接口没有返回余额",
|
|
420
|
+
balanceUnavailable: "账户当前不可用",
|
|
421
|
+
forbidden: "仅允许本机访问",
|
|
422
|
+
method: "仅支持 GET",
|
|
423
|
+
internal: "插件内部错误",
|
|
424
|
+
accountHttp: (status) => `账户接口 HTTP ${status}`,
|
|
425
|
+
accountTimeout: "账户接口超时",
|
|
426
|
+
accountNetwork: "账户接口无法连接",
|
|
427
|
+
accountPayload: "账户接口返回了无法解析的内容",
|
|
428
|
+
accountEmpty: "账户接口没有返回可用数值",
|
|
429
|
+
accountUnavailable: "账户当前不可用",
|
|
430
|
+
accountNoKey: "未配置该提供商的 API Key",
|
|
431
|
+
accountNoKeyNamed: (name) => `未配置 ${name}`,
|
|
432
|
+
accountNoToken: "尚未填写该提供商的 OAuth 令牌",
|
|
433
|
+
accountNoGrant: "DeepSeek 账号尚未登录:在设置里登录后即可显示余额",
|
|
434
|
+
accountTokenExpired: "OAuth 令牌已失效,请重新填写",
|
|
435
|
+
accountNoApi: (name) => `当前插件不支持 ${name}`,
|
|
436
|
+
tokenUnknownProvider: "不支持的提供商",
|
|
437
|
+
tokenMethod: "仅支持 POST",
|
|
438
|
+
tokenPayload: "请求内容无法解析",
|
|
439
|
+
tokenWritten: "令牌已保存",
|
|
440
|
+
tokenCleared: "令牌已清除",
|
|
441
|
+
tokenFailed: "令牌保存失败",
|
|
442
|
+
},
|
|
443
|
+
en: {
|
|
444
|
+
noKey: "DEEPSEEK_API_KEY is not configured",
|
|
445
|
+
badKey: "DEEPSEEK_API_KEY contains invalid characters",
|
|
446
|
+
balanceHttp: (status) => `Balance API HTTP ${status}`,
|
|
447
|
+
balanceTimeout: "Balance API timed out",
|
|
448
|
+
balanceNetwork: "Balance API is unreachable",
|
|
449
|
+
balancePayload: "Balance API returned an unreadable response",
|
|
450
|
+
balanceEmpty: "Balance API returned no balance",
|
|
451
|
+
balanceUnavailable: "The account is currently unavailable",
|
|
452
|
+
forbidden: "Local access only",
|
|
453
|
+
method: "GET only",
|
|
454
|
+
internal: "Internal plugin error",
|
|
455
|
+
accountHttp: (status) => `Account API HTTP ${status}`,
|
|
456
|
+
accountTimeout: "Account API timed out",
|
|
457
|
+
accountNetwork: "Account API is unreachable",
|
|
458
|
+
accountPayload: "Account API returned an unreadable response",
|
|
459
|
+
accountEmpty: "Account API returned no usable value",
|
|
460
|
+
accountUnavailable: "The account is currently unavailable",
|
|
461
|
+
accountNoKey: "This provider has no API key configured",
|
|
462
|
+
accountNoKeyNamed: (name) => `${name} is not configured`,
|
|
463
|
+
accountNoToken: "This provider has no OAuth token yet",
|
|
464
|
+
accountNoGrant: "Not signed in to a DeepSeek account: sign in to see the balance",
|
|
465
|
+
accountTokenExpired: "The OAuth token is no longer valid; save it again",
|
|
466
|
+
accountNoApi: (name) => `This plugin does not support ${name}`,
|
|
467
|
+
tokenUnknownProvider: "Unsupported provider",
|
|
468
|
+
tokenMethod: "POST only",
|
|
469
|
+
tokenPayload: "The request body could not be read",
|
|
470
|
+
tokenWritten: "Token saved",
|
|
471
|
+
tokenCleared: "Token cleared",
|
|
472
|
+
tokenFailed: "The token could not be saved",
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* 放假日期表未覆盖当前年份时告警一次(每天一次)。
|
|
478
|
+
*
|
|
479
|
+
* 在请求路径上检查,而不是只在启动时:进程跨年长跑时,下一年的节假日仍按工作日
|
|
480
|
+
* 计价,而这正是用户真正会看到错误价格的时段——只在启动时告警覆盖不到那一刻。
|
|
481
|
+
*/
|
|
482
|
+
let lastHolidayWarningDay = "";
|
|
483
|
+
function warnHolidayCoverage(ctx) {
|
|
484
|
+
if (hasHolidayCoverage()) return;
|
|
485
|
+
const now = Date.now();
|
|
486
|
+
const day = new Date(now + 8 * 60 * 60 * 1000).toISOString().slice(0, 10);
|
|
487
|
+
if (day === lastHolidayWarningDay) return;
|
|
488
|
+
lastHolidayWarningDay = day;
|
|
489
|
+
const year = new Date(now + 8 * 60 * 60 * 1000).getUTCFullYear();
|
|
490
|
+
ctx.logger.warn(
|
|
491
|
+
`dsh-deepseek-usage: 内置放假日期表未覆盖 ${year} 年(仅收录到 ${HOLIDAY_RANGES.at(-1)?.[1] ?? "未知"})`
|
|
492
|
+
+ `,${year} 年法定节假日白天会被当作高峰时段:请按国务院办公厅通知更新 lib/pricing.js 的 HOLIDAY_RANGES`
|
|
493
|
+
+ `(并同步 lib/client.js 的镜像表,并把 HOLIDAY_TABLE_THROUGH_YEAR 推到 ${year})`,
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function sendJson(res, status, body) {
|
|
498
|
+
// 已经发过响应头时再写一次会抛 ERR_HTTP_HEADERS_SENT,直接结束即可。
|
|
499
|
+
if (res.headersSent) {
|
|
500
|
+
res.end();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
res.writeHead(status, JSON_HEADERS);
|
|
504
|
+
res.end(JSON.stringify(body));
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function balanceUrl() {
|
|
508
|
+
const base = process.env[BASE_URL_ENV] ?? PUBLIC_BASE_URL;
|
|
509
|
+
return `${base.replace(/\/+$/, "")}${BALANCE_PATH}`;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* 账号路由(`deepseek-account`)的余额端点,恒为官方源。
|
|
514
|
+
*
|
|
515
|
+
* 宿主只肯把登录 grant 发到它配置的官方推理源(`resolveToken(url)` 校验
|
|
516
|
+
* `destination.origin === inferenceOrigin`,默认 https://api.deepseek.com),
|
|
517
|
+
* 所以这里不能走 `balanceUrl()`:一旦用户把 DEEPSEEK_BASE_URL 指向第三方中转,
|
|
518
|
+
* 账号令牌就会被送到那个地址。自定义基址只对 api-key 路由生效。
|
|
519
|
+
*/
|
|
520
|
+
function accountBalanceUrl() {
|
|
521
|
+
return `${PUBLIC_BASE_URL}${BALANCE_PATH}`;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** 容忍字符串/数字,返回有限数或 NaN。 */
|
|
525
|
+
function toFinite(value) {
|
|
526
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : NaN;
|
|
527
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
528
|
+
const n = Number(value);
|
|
529
|
+
return Number.isFinite(n) ? n : NaN;
|
|
530
|
+
}
|
|
531
|
+
return NaN;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* 请求头里的 Host 是否是"本机"。
|
|
536
|
+
*
|
|
537
|
+
* 接受:回环地址(127/8 任意地址、::1、localhost)、本监听器绑定的地址。
|
|
538
|
+
* 与 DSH 自己的 /api 栅栏同一口径(见 app.asar 的 isTrustedApiRequest):只认回环
|
|
539
|
+
* 会让 `--host <局域网IP>` 与 `--trusted-host` 部署下插件永久 403。
|
|
540
|
+
*/
|
|
541
|
+
function isLocalHost(req, bindHost) {
|
|
542
|
+
const raw = req.headers.host;
|
|
543
|
+
if (typeof raw !== "string" || raw === "") return false;
|
|
544
|
+
const host = hostNameOf(raw);
|
|
545
|
+
if (host === null) return false;
|
|
546
|
+
if (host === "localhost" || host === "::1") return true;
|
|
547
|
+
if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)) return true;
|
|
548
|
+
if (host === "::ffff:127.0.0.1") return true;
|
|
549
|
+
// 监听器绑定的地址(如 --host 10.0.0.7)同样是"自己"。
|
|
550
|
+
if (typeof bindHost === "string" && bindHost !== "") {
|
|
551
|
+
const bind = hostNameOf(bindHost);
|
|
552
|
+
if (bind !== null && bind !== "" && host === bind) return true;
|
|
553
|
+
}
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* 取 authority 里的主机名:小写、去掉端口与 IPv6 方括号。
|
|
559
|
+
* IPv6 不能按冒号切(`::1` 切出空串),所以先剥方括号再处理。
|
|
560
|
+
*/
|
|
561
|
+
function hostNameOf(authority) {
|
|
562
|
+
let host = authority.trim().toLowerCase();
|
|
563
|
+
if (host.startsWith("[")) {
|
|
564
|
+
const end = host.indexOf("]");
|
|
565
|
+
if (end === -1) return null;
|
|
566
|
+
host = host.slice(1, end);
|
|
567
|
+
return host;
|
|
568
|
+
}
|
|
569
|
+
const idx = host.lastIndexOf(":");
|
|
570
|
+
if (idx !== -1 && host.indexOf(":") === idx) host = host.slice(0, idx);
|
|
571
|
+
return host === "" ? null : host;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* 请求是否可以访问本插件的路由。
|
|
576
|
+
*
|
|
577
|
+
* 口径与 DSH 的 /api 栅栏一致:
|
|
578
|
+
* 1. Host 必须是本机(回环或监听器绑定地址);
|
|
579
|
+
* 2. 浏览器标记为跨站的请求一律拒绝;
|
|
580
|
+
* 3. 带 Origin 时,Origin 必须与 Host 同一 authority。
|
|
581
|
+
* 这样任意网页都无法跨站读走余额,DNS rebinding(Host 变成攻击者域名)同样被挡下。
|
|
582
|
+
*/
|
|
583
|
+
function isTrustedRequest(req, bindHost) {
|
|
584
|
+
if (!isLocalHost(req, bindHost)) return false;
|
|
585
|
+
if (req.headers["sec-fetch-site"] === "cross-site") return false;
|
|
586
|
+
const origin = req.headers.origin;
|
|
587
|
+
if (typeof origin === "string" && origin !== "") {
|
|
588
|
+
let originHost;
|
|
589
|
+
try {
|
|
590
|
+
originHost = new URL(origin).host.toLowerCase();
|
|
591
|
+
} catch {
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
const host = String(req.headers.host ?? "").toLowerCase();
|
|
595
|
+
if (originHost !== host) return false;
|
|
596
|
+
}
|
|
597
|
+
return true;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* 语言标签 → 文案语言:中文(zh、zh-CN、zh-Hans…)用中文,其它任何语言一律英文。
|
|
602
|
+
* 与浏览器侧 lib/client.js 的 uiLang 同一规则。
|
|
603
|
+
*/
|
|
604
|
+
function uiLanguageOf(value) {
|
|
605
|
+
return typeof value === "string" && value.trim().toLowerCase().startsWith("zh") ? "zh" : "en";
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** 解析 ?lang= 参数:zh 前缀用中文,其余值或缺省用英文。 */
|
|
609
|
+
/** provider 参数只接受路由 id 形状:字母数字与 . _ : -,最长 128。 */
|
|
610
|
+
// 路由 id 允许空格与中文(用户在设置页自己起的名字);只排除控制字符。
|
|
611
|
+
const PROVIDER_ID = /^[^\u0000-\u001f]{1,128}$/;
|
|
612
|
+
|
|
613
|
+
function resolveQuery(req) {
|
|
614
|
+
const url = req.url ?? "";
|
|
615
|
+
const q = url.indexOf("?");
|
|
616
|
+
const kv = q === -1 ? [] : url.slice(q + 1).split("&");
|
|
617
|
+
let lang = "en";
|
|
618
|
+
let provider = "";
|
|
619
|
+
for (const item of kv) {
|
|
620
|
+
const eq = item.indexOf("=");
|
|
621
|
+
if (eq === -1) continue;
|
|
622
|
+
const key = item.slice(0, eq);
|
|
623
|
+
if (key !== "lang" && key !== "provider") continue;
|
|
624
|
+
let raw = item.slice(eq + 1);
|
|
625
|
+
try {
|
|
626
|
+
raw = decodeURIComponent(raw);
|
|
627
|
+
} catch { /* 非法转义就按原文判断 */ }
|
|
628
|
+
if (key === "lang") lang = uiLanguageOf(raw);
|
|
629
|
+
else provider = raw.trim();
|
|
630
|
+
}
|
|
631
|
+
// provider:侧栏右键选定的路由 id,只接受 id 形状的字符串(空串=跟随默认模型)。
|
|
632
|
+
// nocache=1:卡片上的「立即刷新」用它跳过 10 秒快照缓存,真打一次上游。
|
|
633
|
+
const nocache = kv.some((item) => item === "nocache=1");
|
|
634
|
+
return { lang, provider: PROVIDER_ID.test(provider) ? provider : "", nocache };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* API Key 是否能安全地放进 Authorization 头。
|
|
639
|
+
* 凭据存储允许任意文本(多行值也是合法输入),而非法字符会让 undici 把整个
|
|
640
|
+
* Authorization 值写进异常消息——那道消息会一路流到卡片上。
|
|
641
|
+
*/
|
|
642
|
+
function isUsableKey(value) {
|
|
643
|
+
if (typeof value !== "string") return false;
|
|
644
|
+
const key = value.trim();
|
|
645
|
+
if (key === "") return false;
|
|
646
|
+
// HTTP 头值只允许可见 ASCII(不含空格与控制字符)。
|
|
647
|
+
return /^[\x21-\x7e]+$/.test(key);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** 入站正文超限:与"无法解析"分开,只有它回 413。 */
|
|
651
|
+
class PayloadTooLargeError extends Error {}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* 读取入站请求正文,超过上限立即失败。
|
|
655
|
+
*
|
|
656
|
+
* 宿主注册的 handler 收到的是 Node 的 IncomingMessage(只读流 + 普通对象 headers),
|
|
657
|
+
* 不是 Fetch Response:没有 headers.get / text(),只能逐块读。上限按实际收到的字节
|
|
658
|
+
* 累计,不只看 Content-Length——分块传输不带长度声明,只信头会被绕过。
|
|
659
|
+
*
|
|
660
|
+
* 超限后立刻拒绝、并把剩余正文排空:等到读完再回 413 会让慢速客户端一直占着请求;
|
|
661
|
+
* 直接 destroy 又会让客户端拿到连接重置而不是 413。
|
|
662
|
+
*/
|
|
663
|
+
function readRequestBody(req, limit) {
|
|
664
|
+
return new Promise((resolve, reject) => {
|
|
665
|
+
const declared = Number(req.headers?.["content-length"]);
|
|
666
|
+
if (Number.isFinite(declared) && declared > limit) {
|
|
667
|
+
req.resume();
|
|
668
|
+
reject(new PayloadTooLargeError());
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
const chunks = [];
|
|
672
|
+
let received = 0;
|
|
673
|
+
let done = false;
|
|
674
|
+
const onData = (chunk) => {
|
|
675
|
+
received += chunk.length;
|
|
676
|
+
if (received > limit) {
|
|
677
|
+
done = true;
|
|
678
|
+
chunks.length = 0;
|
|
679
|
+
req.off("data", onData);
|
|
680
|
+
req.resume();
|
|
681
|
+
reject(new PayloadTooLargeError());
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
chunks.push(chunk);
|
|
685
|
+
};
|
|
686
|
+
req.on("data", onData);
|
|
687
|
+
req.on("end", () => {
|
|
688
|
+
if (done) return;
|
|
689
|
+
done = true;
|
|
690
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
691
|
+
});
|
|
692
|
+
req.on("error", (error) => {
|
|
693
|
+
if (done) return;
|
|
694
|
+
done = true;
|
|
695
|
+
reject(error);
|
|
696
|
+
});
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* 把 accounts.js 的取数结果归一成宿主侧的失败分类。
|
|
702
|
+
*
|
|
703
|
+
* 分类键保持 accounts.js 的原始值(empty / shape / unavailable / timeout /
|
|
704
|
+
* network / unauthorized),由调用方按自己的文案表映射:DeepSeek 走
|
|
705
|
+
* DEEPSEEK_CODES(既有 `balance*` 契约),其余提供商走 ACCOUNT_CODES。
|
|
706
|
+
*/
|
|
707
|
+
function normalizeAccountResult(result) {
|
|
708
|
+
if (result.ok) {
|
|
709
|
+
return {
|
|
710
|
+
ok: true,
|
|
711
|
+
balance: result.balance ?? { isAvailable: null, total: null, currency: null },
|
|
712
|
+
usage: result.usage ?? null,
|
|
713
|
+
// 订阅到期时间(毫秒);只有自定义 provider 配了 expiresPath 才有。
|
|
714
|
+
expiresAt: Number.isFinite(result.expiresAt) ? result.expiresAt : null,
|
|
715
|
+
code: null,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
return { ok: false, balance: null, usage: null, code: result.code ?? "empty" };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** 通用提供商的失败分类 → MESSAGES 的 `account*` 键。 */
|
|
722
|
+
const ACCOUNT_CODES = {
|
|
723
|
+
empty: "accountEmpty",
|
|
724
|
+
shape: "accountPayload",
|
|
725
|
+
unavailable: "accountUnavailable",
|
|
726
|
+
timeout: "accountTimeout",
|
|
727
|
+
network: "accountNetwork",
|
|
728
|
+
unauthorized: "accountTokenExpired",
|
|
729
|
+
// 来自 resolveCredential 的三个分类:没配 / 配了但形状非法。
|
|
730
|
+
noKey: "accountNoKey",
|
|
731
|
+
accountNoKey: "accountNoKey",
|
|
732
|
+
accountNoToken: "accountNoToken",
|
|
733
|
+
badKey: "accountPayload",
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
/** 通用提供商的失败分类 → 用户文案。 */
|
|
737
|
+
function accountMessage(msg, code) {
|
|
738
|
+
const key = ACCOUNT_CODES[code];
|
|
739
|
+
if (key === undefined) return msg.accountNetwork;
|
|
740
|
+
const text = msg[key];
|
|
741
|
+
return typeof text === "function" ? text() : text;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* 从凭证服务解析第一个可用的引用值。
|
|
746
|
+
*
|
|
747
|
+
* @returns {{ ok: true, value, ref } | { ok: false, code: 'noKey'|'unusable' }}
|
|
748
|
+
* noKey = 一个都没配;unusable = 配了但形状不能进 HTTP 头。
|
|
749
|
+
*/
|
|
750
|
+
async function resolveCredential(ctx, refs) {
|
|
751
|
+
for (const ref of refs) {
|
|
752
|
+
let hit;
|
|
753
|
+
try {
|
|
754
|
+
hit = await ctx.credentials.resolve(credentialRef(ref));
|
|
755
|
+
} catch {
|
|
756
|
+
// 单个引用解析失败(服务异常)不阻断其余引用。
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
if (hit === undefined) continue;
|
|
760
|
+
const value = typeof hit.value === "string" ? hit.value.trim() : "";
|
|
761
|
+
if (value === "") continue;
|
|
762
|
+
if (!isUsableKey(value)) return { ok: false, code: "unusable" };
|
|
763
|
+
return { ok: true, value, ref };
|
|
764
|
+
}
|
|
765
|
+
return { ok: false, code: "noKey" };
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* DSH 账号登录留下的 grant 记录,键是 `<scope>/<id>`。
|
|
770
|
+
*
|
|
771
|
+
* `deepseek-account` 路由不认 DEEPSEEK_API_KEY:宿主把邮箱/设备登录换来的令牌写进
|
|
772
|
+
* 这条记录,请求头是 `x-dsh-auth-token`(Bearer 会被上游 401 拒掉)。记录形状由
|
|
773
|
+
* dsh-deepseek-account-platform 写入,令牌在 `payload.token`。
|
|
774
|
+
*
|
|
775
|
+
* 键名写字面量而不经 `credentialKey()`:记录 API 是较新的凭证服务能力,插件仍声明
|
|
776
|
+
* 兼容更早的宿主(package.json 的 peerDependencies),这里的字符串与宿主写入的键
|
|
777
|
+
* 逐字相同,因此不需要为它提高版本门槛,也不会在旧宿主上链接失败。
|
|
778
|
+
*/
|
|
779
|
+
const ACCOUNT_GRANT_KEY = "deepseek-account-platform/default";
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* 读 DeepSeek 账号登录的 grant 令牌。
|
|
783
|
+
*
|
|
784
|
+
* @returns {{ ok: true, value: string } | { ok: false, code: 'noKey' | 'unusable' }}
|
|
785
|
+
*/
|
|
786
|
+
async function resolveAccountGrant(ctx) {
|
|
787
|
+
const readRecord = ctx.credentials?.readRecord;
|
|
788
|
+
if (typeof readRecord !== "function") return { ok: false, code: "noKey" };
|
|
789
|
+
let record;
|
|
790
|
+
try {
|
|
791
|
+
record = await readRecord.call(ctx.credentials, ACCOUNT_GRANT_KEY);
|
|
792
|
+
} catch {
|
|
793
|
+
return { ok: false, code: "noKey" };
|
|
794
|
+
}
|
|
795
|
+
const token = typeof record?.payload?.token === "string" ? record.payload.token.trim() : "";
|
|
796
|
+
if (token === "") return { ok: false, code: "noKey" };
|
|
797
|
+
if (!isUsableKey(token)) return { ok: false, code: "unusable" };
|
|
798
|
+
return { ok: true, value: token };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* 账户快照缓存:同一时间窗内多个请求(多标签页、点击、心跳)共用一次上游调用。
|
|
803
|
+
*
|
|
804
|
+
* 只缓存成功结果——失败必须立刻能被下一次请求重试。缓存与在途请求都按
|
|
805
|
+
* `provider + 引用 + Key` 分桶:换 Key 不命中旧缓存,换 provider 也不会。
|
|
806
|
+
*/
|
|
807
|
+
const accountCache = new Map();
|
|
808
|
+
const accountInFlight = new Map();
|
|
809
|
+
|
|
810
|
+
/** 丢掉过期的缓存条目:换 Key 频繁时 Map 会一直长。 */
|
|
811
|
+
function evictStaleCache(now) {
|
|
812
|
+
for (const [key, entry] of accountCache) {
|
|
813
|
+
if (now - entry.at >= ACCOUNT_CACHE_MS) accountCache.delete(key);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/** 让某个 provider 的下一次读取重新打上游(令牌写入后调用)。 */
|
|
818
|
+
function invalidateAccount(providerId) {
|
|
819
|
+
// 自定义 provider 的缓存桶前缀是 `custom:<id>`(见 readAccountCached 的 capabilityId),
|
|
820
|
+
// 只按裸 id 清会漏掉它们——令牌写入后卡片仍显示旧读数就是这里的原因。
|
|
821
|
+
const prefixes = [`${providerId}\u0000`, `custom:${providerId}\u0000`];
|
|
822
|
+
for (const prefix of prefixes) {
|
|
823
|
+
for (const key of accountCache.keys()) {
|
|
824
|
+
if (key.startsWith(prefix)) accountCache.delete(key);
|
|
825
|
+
}
|
|
826
|
+
for (const key of accountInFlight.keys()) {
|
|
827
|
+
if (key.startsWith(prefix)) accountInFlight.delete(key);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** 缓存 + 在途合并的公共路径(只缓存成功结果)。 */
|
|
833
|
+
async function cachedRead(ctx, bucket, run, now) {
|
|
834
|
+
evictStaleCache(now);
|
|
835
|
+
const cached = accountCache.get(bucket);
|
|
836
|
+
if (cached !== undefined && now - cached.at < ACCOUNT_CACHE_MS) return cached.value;
|
|
837
|
+
const pending = accountInFlight.get(bucket);
|
|
838
|
+
if (pending !== undefined) return pending;
|
|
839
|
+
const request = run()
|
|
840
|
+
.then((value) => {
|
|
841
|
+
if (value.ok) accountCache.set(bucket, { at: Date.now(), value });
|
|
842
|
+
return value;
|
|
843
|
+
})
|
|
844
|
+
.finally(() => {
|
|
845
|
+
accountInFlight.delete(bucket);
|
|
846
|
+
});
|
|
847
|
+
accountInFlight.set(bucket, request);
|
|
848
|
+
return request;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* 取一个提供商的账户读数,带缓存与在途合并。
|
|
853
|
+
*
|
|
854
|
+
* `resolution` 是 lib/providers.js 的解析结果(可选):精确 id 与用户映射都走
|
|
855
|
+
* 同一条取数路径,`capabilityId` 决定端点与缓存桶,`entry` 决定解析函数,
|
|
856
|
+
* `refs` 是候选凭据引用。
|
|
857
|
+
*/
|
|
858
|
+
async function readAccountCached(ctx, providerId, resolution = null) {
|
|
859
|
+
const entry = resolution?.entry ?? accountCapabilityOf(providerId);
|
|
860
|
+
const capabilityId = resolution?.capabilityId ?? entry?.id ?? providerId;
|
|
861
|
+
const now = Date.now();
|
|
862
|
+
if (entry === null || entry === undefined || entry.kind === "none") {
|
|
863
|
+
return { kind: "none", reason: entry?.reason ?? "unsupported", ok: false, code: "accountNoApi" };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// DeepSeek 的端点由 DEEPSEEK_BASE_URL 决定,桶 Key 必须带上它,否则改了覆盖
|
|
867
|
+
// 之后还会命中旧地址的缓存。
|
|
868
|
+
const endpointKey = entry.kind === "balance" && capabilityId.startsWith("deepseek")
|
|
869
|
+
? balanceUrl()
|
|
870
|
+
: entry.custom !== undefined
|
|
871
|
+
// 自定义 provider:桶里带上地址与路径,用户改了 URL 立刻绕开旧缓存。
|
|
872
|
+
? `${entry.custom.baseUrl}${entry.custom.path}`
|
|
873
|
+
: "";
|
|
874
|
+
|
|
875
|
+
if (entry.kind === "oauth") {
|
|
876
|
+
const spec = oauthProviderOf(capabilityId);
|
|
877
|
+
const resolved = await resolveCredential(ctx, [spec.tokenRef]);
|
|
878
|
+
if (!resolved.ok) {
|
|
879
|
+
return { kind: "oauth", ok: false, code: resolved.code === "noKey" ? "accountNoToken" : "badKey" };
|
|
880
|
+
}
|
|
881
|
+
// Codex 的账号标识是可选请求头:配了就带上,没配也照常查。
|
|
882
|
+
let accountId = "";
|
|
883
|
+
if (spec.accountRef !== undefined) {
|
|
884
|
+
const account = await resolveCredential(ctx, [spec.accountRef]);
|
|
885
|
+
if (account.ok) accountId = account.value;
|
|
886
|
+
}
|
|
887
|
+
const bucket = `${capabilityId}\u0000${resolved.ref}\u0000${resolved.value}\u0000${accountId}`;
|
|
888
|
+
const reader = makeAccountReader({ deepseekUrl: balanceUrl() });
|
|
889
|
+
return cachedRead(ctx, bucket, async () => normalizeAccountResult(await reader.read(entry, resolved.value, { accountId })), now);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// DeepSeek 的账号路由走宿主登录的 grant,不读环境变量里的 API key。
|
|
893
|
+
if (capabilityId === "deepseek-account") {
|
|
894
|
+
const grant = await resolveAccountGrant(ctx);
|
|
895
|
+
if (!grant.ok) {
|
|
896
|
+
return {
|
|
897
|
+
kind: entry.kind,
|
|
898
|
+
ok: false,
|
|
899
|
+
code: grant.code === "unusable" ? "badKey" : "accountNoGrant",
|
|
900
|
+
// 没登录不是"配错了 Key",ref 留空,文案由 accountNoGrant 给。
|
|
901
|
+
ref: null,
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
const url = accountBalanceUrl();
|
|
905
|
+
const bucket = `${capabilityId}\u0000${url}\u0000${grant.value}`;
|
|
906
|
+
const reader = makeAccountReader({ deepseekUrl: url });
|
|
907
|
+
return cachedRead(ctx, bucket, async () => normalizeAccountResult(await reader.read(entry, grant.value)), now);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const refs = resolution?.refs ?? (entry.custom !== undefined ? (entry.refs ?? []) : candidateRefsOf(capabilityId));
|
|
911
|
+
// 自定义 provider 的 apiKeyRef 允许两种填法:引用名(走凭据服务)或直接从站点复制的明文。
|
|
912
|
+
// ⚠️ 不能靠"形状"区分:`jcpat_9HIE…` 这种令牌完全符合引用名正则,会被误判成 ref
|
|
913
|
+
// (实测就表现为卡片显示「未配置 jcpat_9HIE…」)。所以顺序是:
|
|
914
|
+
// 1) 先按引用名去凭据服务取;
|
|
915
|
+
// 2) 取不到、而 apiKeyRef 本身是可放进 HTTP 头的字符串 → 直接当密钥用。
|
|
916
|
+
let resolved = await resolveCredential(ctx, refs);
|
|
917
|
+
if (!resolved.ok && entry.custom !== undefined && typeof entry.custom.apiKeyRef === "string") {
|
|
918
|
+
const raw = entry.custom.apiKeyRef.trim();
|
|
919
|
+
if (raw !== "" && /^[\x21-\x7e]+$/.test(raw)) resolved = { ok: true, value: raw, ref: null };
|
|
920
|
+
}
|
|
921
|
+
if (!resolved.ok) {
|
|
922
|
+
// DeepSeek 官方 api-key 路由在只登录了账号、没有 API Key 的 profile 里会永久
|
|
923
|
+
// 停在这个分支(默认模型指向 deepseek-official,但宿主只有账号 grant)。
|
|
924
|
+
// 回退用账号 grant 读同一笔余额:端点恒为官方源、认证头是 x-dsh-auth-token,
|
|
925
|
+
// 与 deepseek-account 路由完全相同。用户配了 Key 但形状非法(unusable)时不
|
|
926
|
+
// 回退——那是要修 Key 的错误,不该被账号余额掩盖。
|
|
927
|
+
if (resolved.code === "noKey" && (capabilityId === "deepseek" || capabilityId === "deepseek-official")) {
|
|
928
|
+
const grant = await resolveAccountGrant(ctx);
|
|
929
|
+
if (grant.ok) {
|
|
930
|
+
const url = accountBalanceUrl();
|
|
931
|
+
const bucket = `deepseek-account\u0000${url}\u0000${grant.value}`;
|
|
932
|
+
const accountEntry = accountCapabilityOf("deepseek-account");
|
|
933
|
+
const reader = makeAccountReader({ deepseekUrl: url });
|
|
934
|
+
return cachedRead(ctx, bucket, async () => normalizeAccountResult(await reader.read(accountEntry, grant.value)), now);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
const firstRef = refs[0];
|
|
938
|
+
return {
|
|
939
|
+
kind: entry.kind,
|
|
940
|
+
ok: false,
|
|
941
|
+
code: resolved.code === "noKey" ? "accountNoKey" : "badKey",
|
|
942
|
+
// 长 ref 多半是用户把密钥粘进了引用格:只露前 6 位,别整条印在侧栏上。
|
|
943
|
+
ref: resolved.code === "noKey"
|
|
944
|
+
? (typeof firstRef === "string" && firstRef.length > 24 ? firstRef.slice(0, 6) + "…" : firstRef)
|
|
945
|
+
: null,
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
const bucket = `${capabilityId}\u0000${endpointKey}\u0000${resolved.ref}\u0000${resolved.value}`;
|
|
949
|
+
const reader = makeAccountReader({ deepseekUrl: balanceUrl() });
|
|
950
|
+
return cachedRead(ctx, bucket, async () => normalizeAccountResult(await reader.read(entry, resolved.value)), now);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* DeepSeek 官方余额的失败分类映射。
|
|
955
|
+
*
|
|
956
|
+
* accounts.js 的解析器返回 `empty`/`shape`/`unavailable`,而 DeepSeek 的用户可见
|
|
957
|
+
* 文案(`balanceEmpty`/`balancePayload`/`balanceUnavailable`)是既有契约,逐字保留;
|
|
958
|
+
* 其余分类(timeout / network)与通用文案一致。
|
|
959
|
+
*/
|
|
960
|
+
const DEEPSEEK_CODES = {
|
|
961
|
+
empty: "balanceEmpty",
|
|
962
|
+
shape: "balancePayload",
|
|
963
|
+
unavailable: "balanceUnavailable",
|
|
964
|
+
timeout: "balanceTimeout",
|
|
965
|
+
network: "balanceNetwork",
|
|
966
|
+
unauthorized: "accountTokenExpired",
|
|
967
|
+
};
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* DeepSeek 失败分类 → 用户文案。
|
|
971
|
+
*
|
|
972
|
+
* `noKey` / `accountNoKey` / `badKey` 映射回 DeepSeek 专属说法(指出
|
|
973
|
+
* DEEPSEEK_API_KEY 本身):它们来自 resolveCredential 的通用分类,
|
|
974
|
+
* 而 DeepSeek 的用户可见文案是既有契约,逐字保留。
|
|
975
|
+
*/
|
|
976
|
+
function deepSeekMessage(msg, snapshot) {
|
|
977
|
+
if (snapshot.code === "noKey" || snapshot.code === "accountNoKey") return msg.noKey;
|
|
978
|
+
if (snapshot.code === "accountNoGrant") return msg.accountNoGrant;
|
|
979
|
+
if (snapshot.code === "badKey") return msg.badKey;
|
|
980
|
+
const key = DEEPSEEK_CODES[snapshot.code];
|
|
981
|
+
if (key === undefined) return msg.balanceNetwork;
|
|
982
|
+
const text = msg[key];
|
|
983
|
+
return typeof text === "function" ? text() : text;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function apply(ctx, config = {}) {
|
|
987
|
+
const bindHost = typeof ctx.webServer?.host === "string" ? ctx.webServer.host : "";
|
|
988
|
+
|
|
989
|
+
// 用户映射:把第三方插件注册的 provider id 翻译成受支持提供商的账户口径。
|
|
990
|
+
//
|
|
991
|
+
// 必须在**每次请求**时读取,不能在 apply 时拍快照:`providerAliases` 是
|
|
992
|
+
// volatile 字段,Loader 对「只有 volatile 值变化」的配置更新不会重跑 apply,
|
|
993
|
+
// 而是把新值就地写进这里捕获的引用(cordis-plugin-loader 的 _commitVolatile)。
|
|
994
|
+
// 拍快照会让设置页保存后仍按旧映射查询,直到重启宿主。
|
|
995
|
+
const warned = new Set();
|
|
996
|
+
/** 刷新间隔(秒):配置里是文本;非法或留空按 30,范围 5..3600。 */
|
|
997
|
+
const DEFAULT_REFRESH_SECONDS = 30;
|
|
998
|
+
// 刷新间隔允许小数(0.1 秒起):中转站的账单接口是实时的,想看得更细就调小,
|
|
999
|
+
// 但下限压到 100ms,再短只会把自己打成限流。
|
|
1000
|
+
const MIN_REFRESH_SECONDS = 0.1;
|
|
1001
|
+
const MAX_REFRESH_SECONDS = 3600;
|
|
1002
|
+
function refreshSecondsNow() {
|
|
1003
|
+
const raw = Number.parseFloat(String(config?.refreshSeconds ?? ""));
|
|
1004
|
+
if (!Number.isFinite(raw)) return DEFAULT_REFRESH_SECONDS;
|
|
1005
|
+
const bounded = Math.min(MAX_REFRESH_SECONDS, Math.max(MIN_REFRESH_SECONDS, raw));
|
|
1006
|
+
return Math.round(bounded * 10) / 10;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* 自动识别:模型设置里已经加过的 provider(`llm.listProviders()` 带 baseURL 的那些),
|
|
1011
|
+
* 即使没在本插件里手工登记,也直接生成一条隐式自定义条目。
|
|
1012
|
+
*
|
|
1013
|
+
* 为什么要这样:用户加完模型后,看板右键菜单里还得再手填一遍 provider/地址才对得上,
|
|
1014
|
+
* 纯属重复劳动。这里用它的 baseURL 猜一个最常见的 new-api 端点,猜错也只是显示
|
|
1015
|
+
* "无法解析"——用户点「编辑配置」补 path 即可,不会误报成余额。
|
|
1016
|
+
*/
|
|
1017
|
+
function autoCustomConfigs() {
|
|
1018
|
+
const out = [];
|
|
1019
|
+
try {
|
|
1020
|
+
const llm = ctx.get("llm");
|
|
1021
|
+
if (llm === undefined || llm === null || typeof llm.listProviders !== "function") return out;
|
|
1022
|
+
for (const item of llm.listProviders()) {
|
|
1023
|
+
const id = typeof item?.id === "string" ? item.id.trim() : "";
|
|
1024
|
+
const base = typeof item?.baseURL === "string" ? item.baseURL.trim() : "";
|
|
1025
|
+
if (id === "" || base === "") continue;
|
|
1026
|
+
out.push({
|
|
1027
|
+
provider: id,
|
|
1028
|
+
label: typeof item.name === "string" && item.name !== "" ? item.name : id,
|
|
1029
|
+
// 去掉末尾 /v1:插件的路径自己带 /v1,重复会拼出 /v1/v1/...
|
|
1030
|
+
baseUrl: base.replace(/\/+$/, "").replace(/\/v1$/, ""),
|
|
1031
|
+
preset: "newapi",
|
|
1032
|
+
kind: "balance",
|
|
1033
|
+
currency: "CNY",
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
} catch {
|
|
1037
|
+
/* llm 服务不可用:不自动识别,只返回空 */
|
|
1038
|
+
}
|
|
1039
|
+
return out;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function providersNow() {
|
|
1043
|
+
const { aliases, warnings } = normalizeAliases(config?.providerAliases);
|
|
1044
|
+
const { providers: customs, warnings: customWarnings } = normalizeCustomProviders(config?.customProviders);
|
|
1045
|
+
for (const warning of [...warnings, ...customWarnings]) {
|
|
1046
|
+
if (warned.has(warning)) continue;
|
|
1047
|
+
warned.add(warning);
|
|
1048
|
+
ctx.logger.warn(`dsh-deepseek-usage: ${warning}`);
|
|
1049
|
+
}
|
|
1050
|
+
// 自动识别项先铺底,用户显式配置同 id 时覆盖它(配置永远赢)。
|
|
1051
|
+
const auto = normalizeCustomProviders(autoCustomConfigs());
|
|
1052
|
+
const merged = new Map(auto.providers);
|
|
1053
|
+
for (const [key, entry] of customs) merged.set(key, entry);
|
|
1054
|
+
return createProviderResolver(aliases, merged);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
ctx.effect(
|
|
1058
|
+
() => ctx.webServer.register({
|
|
1059
|
+
kind: "exact",
|
|
1060
|
+
path: HOLIDAYS_PATH,
|
|
1061
|
+
handler: async (req, res) => {
|
|
1062
|
+
const { lang } = resolveQuery(req);
|
|
1063
|
+
const msg = MESSAGES[lang];
|
|
1064
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
1065
|
+
return sendJson(res, 405, { ok: false, error: "method", message: msg.method });
|
|
1066
|
+
}
|
|
1067
|
+
if (!isTrustedRequest(req, bindHost)) {
|
|
1068
|
+
return sendJson(res, 403, { ok: false, error: "forbidden", message: msg.forbidden });
|
|
1069
|
+
}
|
|
1070
|
+
sendJson(res, 200, { ok: true, ranges: HOLIDAY_RANGES });
|
|
1071
|
+
},
|
|
1072
|
+
}),
|
|
1073
|
+
"dsh-deepseek-usage: holidays route",
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
ctx.effect(
|
|
1077
|
+
() => ctx.webServer.register({
|
|
1078
|
+
kind: "exact",
|
|
1079
|
+
path: ROUTE_PATH,
|
|
1080
|
+
handler: async (req, res) => {
|
|
1081
|
+
const { lang, provider: providerOverride, nocache } = resolveQuery(req);
|
|
1082
|
+
const msg = MESSAGES[lang];
|
|
1083
|
+
try {
|
|
1084
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
1085
|
+
return sendJson(res, 405, { ok: false, error: "method", message: msg.method });
|
|
1086
|
+
}
|
|
1087
|
+
// ---- 仅本机访问:拦截 DNS rebinding、跨站读取与局域网直连 ----
|
|
1088
|
+
if (!isTrustedRequest(req, bindHost)) {
|
|
1089
|
+
return sendJson(res, 403, { ok: false, error: "forbidden", message: msg.forbidden });
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// 放假日期表过期时告警(每天一次)。放在请求路径上,跨年长跑也能覆盖到。
|
|
1093
|
+
try {
|
|
1094
|
+
warnHolidayCoverage(ctx);
|
|
1095
|
+
} catch { /* 告警失败不影响卡片 */ }
|
|
1096
|
+
|
|
1097
|
+
// ---- 当前模型当前档单价(展示用)----
|
|
1098
|
+
let model = DEFAULT_MODEL;
|
|
1099
|
+
let provider = "";
|
|
1100
|
+
try {
|
|
1101
|
+
const adm = ctx.get("agentDefaultModel");
|
|
1102
|
+
const selection = adm && typeof adm.currentSelection === "function" ? adm.currentSelection() : void 0;
|
|
1103
|
+
if (selection && typeof selection.model === "string") model = selection.model;
|
|
1104
|
+
if (selection && typeof selection.provider === "string") provider = selection.provider;
|
|
1105
|
+
} catch {}
|
|
1106
|
+
// 立即刷新:清掉这一轮的快照缓存,保证这次真的打到上游(用户要对照调用计数)。
|
|
1107
|
+
if (nocache) accountCache.clear();
|
|
1108
|
+
// 侧栏右键选定的 provider:只是让卡片看别家的读数,不动 agentDefaultModel
|
|
1109
|
+
// (改默认模型会顺带把正在跑的模型换掉,副作用太大)。
|
|
1110
|
+
if (providerOverride !== "") provider = providerOverride;
|
|
1111
|
+
// 时刻在账户请求之后再取:请求耗时会跨过峰谷边界,先取会让 peak / 单价 /
|
|
1112
|
+
// 倒计时三者互相矛盾(显示橙色高峰灯却给着空闲价)。
|
|
1113
|
+
const now = Date.now();
|
|
1114
|
+
// provider 解析:精确 id 优先,其次用户映射;未识别时按「不支持」处理。
|
|
1115
|
+
// 解析器按请求现建,读取的是 volatile 配置的最新值(见 providersNow)。
|
|
1116
|
+
const resolution = providersNow().resolve(provider);
|
|
1117
|
+
const entry = resolution?.entry ?? null;
|
|
1118
|
+
// 计价按解析后的能力 id 查表:映射到厂商账户的路由复用该厂商的价格快照。
|
|
1119
|
+
// 自定义 provider 可以借别家的单价表(custom.pricing),否则用自己的 id 查不到就是 known:false。
|
|
1120
|
+
const pricingId = entry?.custom?.pricing || entry?.id || provider;
|
|
1121
|
+
const unit = unitAt(model, now, pricingId);
|
|
1122
|
+
|
|
1123
|
+
const errors = [];
|
|
1124
|
+
const kind = entry?.kind ?? "none";
|
|
1125
|
+
const providerInfo = {
|
|
1126
|
+
id: provider,
|
|
1127
|
+
displayName: entry?.displayName ?? provider,
|
|
1128
|
+
kind,
|
|
1129
|
+
reason: kind === "none" ? (entry?.reason ?? "unsupported") : null,
|
|
1130
|
+
// 这个 provider 是怎么被认出来的:exact(能力表)/ alias(用户映射)/ none。
|
|
1131
|
+
via: resolution?.via ?? "none",
|
|
1132
|
+
};
|
|
1133
|
+
|
|
1134
|
+
// ---- 当前 provider 的账户数据(余额 / 订阅用量)----
|
|
1135
|
+
let balance = { isAvailable: null, total: null, currency: null };
|
|
1136
|
+
let usage = null;
|
|
1137
|
+
let expiresAt = null;
|
|
1138
|
+
|
|
1139
|
+
if (kind === "none") {
|
|
1140
|
+
// 这个 provider 没有可查的接口:卡片置空并说明原因,不显示任何数字。
|
|
1141
|
+
errors.push(msg.accountNoApi(providerInfo.displayName));
|
|
1142
|
+
} else if (kind === "oauth") {
|
|
1143
|
+
const snapshot = await readAccountCached(ctx, provider, resolution);
|
|
1144
|
+
if (snapshot.ok) {
|
|
1145
|
+
balance = snapshot.balance ?? balance;
|
|
1146
|
+
usage = snapshot.usage ?? null;
|
|
1147
|
+
expiresAt = snapshot.expiresAt ?? null;
|
|
1148
|
+
} else {
|
|
1149
|
+
errors.push(accountMessage(msg, snapshot.code));
|
|
1150
|
+
}
|
|
1151
|
+
} else if (entry.id === "deepseek-official" || entry.id === "deepseek-account" || entry.id === "deepseek") {
|
|
1152
|
+
// DeepSeek 官方路由:与其他提供商同一条取数路径,但失败文案沿用
|
|
1153
|
+
// 既有的 `balance*`(用户可见契约,逐字保留)。
|
|
1154
|
+
const snapshot = await readAccountCached(ctx, provider, resolution);
|
|
1155
|
+
balance = snapshot.balance ?? balance;
|
|
1156
|
+
usage = snapshot.usage ?? null;
|
|
1157
|
+
expiresAt = snapshot.expiresAt ?? null;
|
|
1158
|
+
if (!snapshot.ok) {
|
|
1159
|
+
errors.push(deepSeekMessage(msg, snapshot));
|
|
1160
|
+
}
|
|
1161
|
+
} else {
|
|
1162
|
+
const snapshot = await readAccountCached(ctx, provider, resolution);
|
|
1163
|
+
if (snapshot.ok) {
|
|
1164
|
+
balance = snapshot.balance ?? balance;
|
|
1165
|
+
usage = snapshot.usage ?? null;
|
|
1166
|
+
expiresAt = snapshot.expiresAt ?? null;
|
|
1167
|
+
} else {
|
|
1168
|
+
errors.push(
|
|
1169
|
+
snapshot.code === "accountNoKey" && snapshot.ref
|
|
1170
|
+
? msg.accountNoKeyNamed(snapshot.ref)
|
|
1171
|
+
: accountMessage(msg, snapshot.code),
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// ---- 距下一次计费区间翻转(界面用它在指示灯旁显示倒计时)----
|
|
1177
|
+
// DeepSeek 官方模型走峰谷表;其它 provider 有分时段计费时由各自的表给出;
|
|
1178
|
+
// 不分时段的(window 为 null)不发送倒计时。
|
|
1179
|
+
//
|
|
1180
|
+
// 订阅制路由没有价格快照,但当前模型如果是 DeepSeek 的峰谷型号,仍然把
|
|
1181
|
+
// 时段信息发出去——卡片照旧显示峰谷灯与倒计时(不显示单价)。
|
|
1182
|
+
let displayWindow = unit.window;
|
|
1183
|
+
if (
|
|
1184
|
+
displayWindow === null &&
|
|
1185
|
+
(kind === "usage" || kind === "oauth") &&
|
|
1186
|
+
isDeepSeekScheduleModel(model)
|
|
1187
|
+
) {
|
|
1188
|
+
displayWindow = isPeak(now) ? "peak" : "idle";
|
|
1189
|
+
}
|
|
1190
|
+
const next = displayWindow === null
|
|
1191
|
+
? { peak: false, at: null, ms: 0 }
|
|
1192
|
+
: unit.next ?? nextChange(now);
|
|
1193
|
+
|
|
1194
|
+
sendJson(res, 200, {
|
|
1195
|
+
ok: true,
|
|
1196
|
+
provider: providerInfo,
|
|
1197
|
+
// 卡片按这个间隔轮询(设置页可改,秒)。
|
|
1198
|
+
refreshSeconds: refreshSecondsNow(),
|
|
1199
|
+
// 订阅到期时间(epoch ms):卡片据此显示"剩余 N 天"。
|
|
1200
|
+
expiresAt,
|
|
1201
|
+
// 本机累计用量(调用次数 / token 处理量),与中转站后台口径不同,界面上分开标注。
|
|
1202
|
+
local: await localUsageSnapshot(),
|
|
1203
|
+
// 站点口径(后台面板那两个数):只有拿到登录态 token 时才有,读不到就 ok:false。
|
|
1204
|
+
relay: await (async () => {
|
|
1205
|
+
// 站点口径只在「当前 provider 就是那个中转站」时成立:没有自定义 baseUrl 的
|
|
1206
|
+
// provider(例如映射到 deepseek-official)拿不到站点地址,绝不能借用 asnia 的
|
|
1207
|
+
// cookie 去查别家的数据。这是"跟随当前模型提供商"的第一道闸。
|
|
1208
|
+
const relayBase = entry?.custom?.baseUrl;
|
|
1209
|
+
if (typeof relayBase !== "string" || relayBase === "") {
|
|
1210
|
+
return { ok: false, reason: "not-custom" };
|
|
1211
|
+
}
|
|
1212
|
+
// 顺序反过来了:先直读 `.credentials.yaml`(实测拿到的就是站点 token 原文),
|
|
1213
|
+
// credentials.resolve() 作回退——它返回的标量可能带引号/空白,会被站点判 401。
|
|
1214
|
+
let secret = await readRefFromYaml("ASNIA_REFRESH_COOKIE");
|
|
1215
|
+
if (secret === null || cleanSecret(secret) === "") {
|
|
1216
|
+
secret = await readRefFromYaml("ASNIA_SESSION_TOKEN");
|
|
1217
|
+
}
|
|
1218
|
+
if (secret === null || cleanSecret(secret) === "") {
|
|
1219
|
+
const resolvedToken = await resolveCredential(ctx, [RELAY_TOKEN_REF]);
|
|
1220
|
+
secret = resolvedToken.ok ? resolvedToken.value : null;
|
|
1221
|
+
}
|
|
1222
|
+
if (secret === null || cleanSecret(secret) === "") return { ok: false, reason: "no-token" };
|
|
1223
|
+
return relayStats(secret, nocache, relayBase);
|
|
1224
|
+
})(),
|
|
1225
|
+
balance,
|
|
1226
|
+
usage,
|
|
1227
|
+
// peak = 当前是否处于较贵的一侧(DeepSeek 的峰谷、其它 provider 的高峰
|
|
1228
|
+
// 时段或优惠时段之外都是这个含义);不分时段时为 false。
|
|
1229
|
+
peak: displayWindow === "peak",
|
|
1230
|
+
// peak = 切换后所处的时段,at = 切换时刻,ms = 剩余毫秒
|
|
1231
|
+
next,
|
|
1232
|
+
tier: {
|
|
1233
|
+
input: unit.input,
|
|
1234
|
+
cacheRead: unit.cacheRead,
|
|
1235
|
+
cacheWrite: unit.cacheWrite,
|
|
1236
|
+
output: unit.output,
|
|
1237
|
+
model: unit.model,
|
|
1238
|
+
known: unit.known,
|
|
1239
|
+
// 计费币种:DeepSeek 为 CNY,其它 provider 见各自价格表。
|
|
1240
|
+
currency: unit.currency,
|
|
1241
|
+
// null = 这个模型全天同一价(不画指示灯与倒计时);订阅制路由上的
|
|
1242
|
+
// DeepSeek 模型会给出峰谷时段,但仍然 known=false(不显示单价)。
|
|
1243
|
+
window: displayWindow,
|
|
1244
|
+
},
|
|
1245
|
+
// 【内部诊断】取价路径:界面不再展示(卡片去技术化),保留字段
|
|
1246
|
+
// 供排查问题与回归测试使用。
|
|
1247
|
+
pricing: {
|
|
1248
|
+
via: unit.via, // exact | alias | fallback
|
|
1249
|
+
requested: unit.requested, // 当前启用的模型 id
|
|
1250
|
+
provider: provider, // 当前路由的原始 provider id
|
|
1251
|
+
capability: entry?.id ?? provider, // 解析后用于查价的能力表 id
|
|
1252
|
+
used: unit.model, // 实际取价使用的模型 id
|
|
1253
|
+
known: unit.known, // false = 不计价,界面隐藏单价
|
|
1254
|
+
currency: unit.currency,
|
|
1255
|
+
window: unit.window,
|
|
1256
|
+
},
|
|
1257
|
+
updatedAt: now,
|
|
1258
|
+
errors,
|
|
1259
|
+
});
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
ctx.logger.warn("dsh-deepseek-usage: request failed");
|
|
1262
|
+
ctx.logger.warn(error);
|
|
1263
|
+
sendJson(res, 502, {
|
|
1264
|
+
ok: false,
|
|
1265
|
+
error: "internal",
|
|
1266
|
+
message: msg.internal,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
},
|
|
1270
|
+
}),
|
|
1271
|
+
"dsh-deepseek-usage: route",
|
|
1272
|
+
);
|
|
1273
|
+
|
|
1274
|
+
ctx.effect(
|
|
1275
|
+
() => ctx.webServer.register({
|
|
1276
|
+
kind: "exact",
|
|
1277
|
+
path: ACCOUNTS_PATH,
|
|
1278
|
+
handler: async (req, res) => {
|
|
1279
|
+
const { lang } = resolveQuery(req);
|
|
1280
|
+
const msg = MESSAGES[lang];
|
|
1281
|
+
try {
|
|
1282
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
1283
|
+
return sendJson(res, 405, { ok: false, error: "method", message: msg.method });
|
|
1284
|
+
}
|
|
1285
|
+
if (!isTrustedRequest(req, bindHost)) {
|
|
1286
|
+
return sendJson(res, 403, { ok: false, error: "forbidden", message: msg.forbidden });
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
// 当前 provider 也是"已检测到"的一条:用户可能只在 agentDefaultModel 里
|
|
1290
|
+
// 指向了它,而目录还没列出。
|
|
1291
|
+
let currentProvider = "";
|
|
1292
|
+
try {
|
|
1293
|
+
const adm = ctx.get("agentDefaultModel");
|
|
1294
|
+
const selection = adm && typeof adm.currentSelection === "function" ? adm.currentSelection() : void 0;
|
|
1295
|
+
if (selection && typeof selection.provider === "string") currentProvider = selection.provider;
|
|
1296
|
+
} catch {}
|
|
1297
|
+
|
|
1298
|
+
// 设置页的下拉选项:schema 允许映射到的提供商集合。与 Config 的枚举同源,
|
|
1299
|
+
// 目录读不到时也要给出来,否则设置页没法添加映射。`kind` 让设置页知道
|
|
1300
|
+
// OAuth 目标(Claude Code / Codex)的凭据是订阅令牌,不填凭据引用。
|
|
1301
|
+
const aliasable = aliasableProviderIds().map((id) => {
|
|
1302
|
+
const entry = accountCapabilityOf(id);
|
|
1303
|
+
return { id, displayName: entry.displayName, kind: entry.kind };
|
|
1304
|
+
});
|
|
1305
|
+
|
|
1306
|
+
// 已注册的 provider 路由(directory 可能包含未注册的,只取注册过的)。
|
|
1307
|
+
const registered = new Map();
|
|
1308
|
+
try {
|
|
1309
|
+
const llm = ctx.get("llm");
|
|
1310
|
+
if (llm && typeof llm.listProviders === "function") {
|
|
1311
|
+
for (const item of llm.listProviders()) registered.set(item.id, item.name ?? item.id);
|
|
1312
|
+
}
|
|
1313
|
+
} catch {
|
|
1314
|
+
// 目录读不到时映射选项照常给,未识别候选与令牌区留空。
|
|
1315
|
+
sendJson(res, 200, { ok: true, aliasable, unmapped: [], oauth: [] });
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
// 本次请求的映射解析器:volatile 配置可能在两次请求之间被设置页改写。
|
|
1320
|
+
const providers = providersNow();
|
|
1321
|
+
|
|
1322
|
+
// 检测到、但既不在能力表里、也没有用户映射的路由:设置页用它给出"添加映射"
|
|
1323
|
+
// 的候选。只取已注册与当前 provider,目录里那几十条无关路由不进列表。
|
|
1324
|
+
const detected = new Set([...registered.keys(), ...(currentProvider ? [currentProvider] : [])]);
|
|
1325
|
+
// "未显式配置"= 用户没在设置里登记过(自动识别的条目不算显式),
|
|
1326
|
+
// 这样设置页仍保留一行可点击的入口,把自动项补成显式配置。
|
|
1327
|
+
const explicit = new Set([
|
|
1328
|
+
...normalizeCustomProviders(config?.customProviders).providers.keys(),
|
|
1329
|
+
...normalizeAliases(config?.providerAliases).aliases.keys(),
|
|
1330
|
+
]);
|
|
1331
|
+
const unmapped = [...detected]
|
|
1332
|
+
.filter((id) => !explicit.has(String(id).toLowerCase()))
|
|
1333
|
+
.map((id) => {
|
|
1334
|
+
const hit = providers.resolve(id);
|
|
1335
|
+
const base = hit !== null && hit.entry?.custom?.baseUrl ? hit.entry.custom.baseUrl : "";
|
|
1336
|
+
return {
|
|
1337
|
+
id,
|
|
1338
|
+
displayName: registered.get(id) ?? id,
|
|
1339
|
+
// 自动识别给出的推测地址,设置页点开时直接预填,不用再手输。
|
|
1340
|
+
baseUrl: base,
|
|
1341
|
+
auto: hit !== null && hit.via === "custom",
|
|
1342
|
+
};
|
|
1343
|
+
});
|
|
1344
|
+
|
|
1345
|
+
// OAuth 令牌状态:列出「DSH 里检测到」或「被映射目标引用」的 Claude Code /
|
|
1346
|
+
// Codex——后者让只装了第三方 Codex/Claude 插件的环境也能先填令牌。令牌值
|
|
1347
|
+
// 永不回传;`configured` 只看本地凭据,不查上游。
|
|
1348
|
+
//
|
|
1349
|
+
// 检测到的路由可能用别名 id 注册(如第三方 Codex 插件的 `chatgpt-codex`),
|
|
1350
|
+
// 按规范 id 归一后再判断,令牌框才会出现。
|
|
1351
|
+
const detectedCanonical = new Set([...detected].map((id) => canonicalProviderId(id)));
|
|
1352
|
+
const mappedOauth = new Set(providers.capabilityIds.filter((id) => oauthProviderOf(id) !== null));
|
|
1353
|
+
const oauth = [];
|
|
1354
|
+
for (const id of oauthProviderIds()) {
|
|
1355
|
+
if (!detectedCanonical.has(id) && !mappedOauth.has(id)) continue;
|
|
1356
|
+
const spec = oauthProviderOf(id);
|
|
1357
|
+
const resolved = await resolveCredential(ctx, [spec.tokenRef]);
|
|
1358
|
+
oauth.push({
|
|
1359
|
+
id,
|
|
1360
|
+
displayName: accountCapabilityOf(id).displayName,
|
|
1361
|
+
configured: resolved.ok,
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
// 侧栏右键菜单的候选:能力表里的与自定义的都能直接切换查看。
|
|
1366
|
+
// 用解析器逐条 resolve,拿到的是"这家最终会被怎么读"(displayName / kind / via),
|
|
1367
|
+
// 与卡片实际请求走同一条判断,菜单里列出来的每一条都点得动。
|
|
1368
|
+
const catalog = [];
|
|
1369
|
+
const seenCatalog = new Set();
|
|
1370
|
+
// ⚠️ addedIds 必须一起遍历:它才是"用户在设置里添加过的映射路由 id"。
|
|
1371
|
+
// 只遍历 supportedProviderIds + customIds 的话,映射到 deepseek-official 的路由
|
|
1372
|
+
// (例如自己起名 "DeepSeek ASNIA")不会出现在 catalog 里,右键菜单就只剩自定义项。
|
|
1373
|
+
for (const id of [...supportedProviderIds(), ...providers.customIds, ...providers.addedIds]) {
|
|
1374
|
+
const hit = providers.resolve(id);
|
|
1375
|
+
if (hit === null || hit.entry === null || hit.entry === undefined) continue;
|
|
1376
|
+
const key = id.toLowerCase();
|
|
1377
|
+
if (seenCatalog.has(key)) continue;
|
|
1378
|
+
seenCatalog.add(key);
|
|
1379
|
+
catalog.push({
|
|
1380
|
+
id,
|
|
1381
|
+
// 映射项显示用户自己填的路由名(= id),否则会显示目标提供商的名字,
|
|
1382
|
+
// 菜单里出现两个"DeepSeek"就分不清哪个是映射、哪个是内置。
|
|
1383
|
+
displayName: hit.via === "alias" ? id : (hit.entry.displayName ?? id),
|
|
1384
|
+
kind: hit.entry.kind,
|
|
1385
|
+
via: hit.via,
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
// 当前 provider 排在最前:右键菜单第一屏就能点到手上正在用的那一家。
|
|
1389
|
+
const head = catalog.findIndex((item) => item.id.toLowerCase() === currentProvider.toLowerCase());
|
|
1390
|
+
if (head > 0) catalog.unshift(...catalog.splice(head, 1));
|
|
1391
|
+
sendJson(res, 200, {
|
|
1392
|
+
ok: true,
|
|
1393
|
+
aliasable,
|
|
1394
|
+
unmapped,
|
|
1395
|
+
oauth,
|
|
1396
|
+
custom: providers.customIds,
|
|
1397
|
+
catalog,
|
|
1398
|
+
// 只把"添加过的"给侧栏:右键菜单与卡片按这个集合过滤。
|
|
1399
|
+
added: providers.addedIds,
|
|
1400
|
+
current: currentProvider,
|
|
1401
|
+
});
|
|
1402
|
+
} catch (error) {
|
|
1403
|
+
ctx.logger.warn("dsh-deepseek-usage: plugin page request failed");
|
|
1404
|
+
ctx.logger.warn(error);
|
|
1405
|
+
sendJson(res, 502, { ok: false, error: "internal", message: msg.internal });
|
|
1406
|
+
}
|
|
1407
|
+
},
|
|
1408
|
+
}),
|
|
1409
|
+
"dsh-deepseek-usage: plugin page route",
|
|
1410
|
+
);
|
|
1411
|
+
|
|
1412
|
+
ctx.effect(
|
|
1413
|
+
() => ctx.webServer.register({
|
|
1414
|
+
kind: "exact",
|
|
1415
|
+
path: TOKEN_PATH,
|
|
1416
|
+
handler: async (req, res) => {
|
|
1417
|
+
const { lang } = resolveQuery(req);
|
|
1418
|
+
const msg = MESSAGES[lang];
|
|
1419
|
+
try {
|
|
1420
|
+
if (req.method !== "POST") {
|
|
1421
|
+
return sendJson(res, 405, { ok: false, error: "method", message: msg.tokenMethod });
|
|
1422
|
+
}
|
|
1423
|
+
if (!isTrustedRequest(req, bindHost)) {
|
|
1424
|
+
return sendJson(res, 403, { ok: false, error: "forbidden", message: msg.forbidden });
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// 读有界 body:本机提交也不该无限读。
|
|
1428
|
+
let raw;
|
|
1429
|
+
try {
|
|
1430
|
+
raw = await readRequestBody(req, MAX_TOKEN_BODY_BYTES);
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
if (error instanceof PayloadTooLargeError) {
|
|
1433
|
+
return sendJson(res, 413, { ok: false, error: "payload", message: msg.tokenPayload });
|
|
1434
|
+
}
|
|
1435
|
+
// 客户端中途断开、连接被重置等:请求本身没法读完,不是超限。
|
|
1436
|
+
ctx.logger.warn("dsh-deepseek-usage: token request body read failed");
|
|
1437
|
+
return sendJson(res, 400, { ok: false, error: "payload", message: msg.tokenPayload });
|
|
1438
|
+
}
|
|
1439
|
+
let body;
|
|
1440
|
+
try {
|
|
1441
|
+
body = JSON.parse(raw);
|
|
1442
|
+
} catch {
|
|
1443
|
+
return sendJson(res, 400, { ok: false, error: "payload", message: msg.tokenPayload });
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
const provider = typeof body?.provider === "string" ? body.provider.trim().toLowerCase() : "";
|
|
1447
|
+
const spec = oauthProviderOf(provider);
|
|
1448
|
+
if (spec === null) {
|
|
1449
|
+
return sendJson(res, 400, { ok: false, error: "provider", message: msg.tokenUnknownProvider });
|
|
1450
|
+
}
|
|
1451
|
+
const token = typeof body?.token === "string" ? body.token.trim() : "";
|
|
1452
|
+
if (token !== "" && !isUsableKey(token)) {
|
|
1453
|
+
return sendJson(res, 400, { ok: false, error: "key", message: msg.badKey });
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
const ref = credentialRef(spec.tokenRef);
|
|
1457
|
+
try {
|
|
1458
|
+
if (token === "") {
|
|
1459
|
+
await ctx.credentials.unset(ref);
|
|
1460
|
+
if (spec.accountRef !== undefined) await ctx.credentials.unset(credentialRef(spec.accountRef));
|
|
1461
|
+
invalidateAccount(provider);
|
|
1462
|
+
return sendJson(res, 200, { ok: true, provider, configured: false, message: msg.tokenCleared });
|
|
1463
|
+
}
|
|
1464
|
+
await ctx.credentials.set(ref, token);
|
|
1465
|
+
// Codex 的账号标识与令牌一并保存(缺了它上游可能拒绝请求)。
|
|
1466
|
+
if (spec.accountRef !== undefined) {
|
|
1467
|
+
const accountId = typeof body?.accountId === "string" ? body.accountId.trim() : "";
|
|
1468
|
+
if (accountId !== "") await ctx.credentials.set(credentialRef(spec.accountRef), accountId);
|
|
1469
|
+
}
|
|
1470
|
+
invalidateAccount(provider);
|
|
1471
|
+
return sendJson(res, 200, { ok: true, provider, configured: true, message: msg.tokenWritten });
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
ctx.logger.warn("dsh-deepseek-usage: token write failed");
|
|
1474
|
+
ctx.logger.warn(error);
|
|
1475
|
+
return sendJson(res, 502, { ok: false, error: "internal", message: msg.tokenFailed });
|
|
1476
|
+
}
|
|
1477
|
+
} catch (error) {
|
|
1478
|
+
ctx.logger.warn("dsh-deepseek-usage: token request failed");
|
|
1479
|
+
ctx.logger.warn(error);
|
|
1480
|
+
sendJson(res, 502, { ok: false, error: "internal", message: msg.internal });
|
|
1481
|
+
}
|
|
1482
|
+
},
|
|
1483
|
+
}),
|
|
1484
|
+
"dsh-deepseek-usage: token route",
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
export { name, inject, apply, Config };
|