dsh-sub2api 0.0.0-stage → 0.1.4
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/CHANGELOG.md +48 -0
- package/LICENSE +674 -0
- package/README.md +163 -2
- package/cordis.patch.yml +16 -0
- package/lib/adapter.js +205 -0
- package/lib/client.js +754 -0
- package/lib/config.js +86 -0
- package/lib/constants.js +64 -0
- package/lib/index.js +197 -0
- package/lib/pay.js +243 -0
- package/lib/routes.js +378 -0
- package/lib/schema.js +37 -0
- package/lib/sub2api/api.js +247 -0
- package/lib/sub2api/auth.js +106 -0
- package/lib/sub2api/catalog.js +330 -0
- package/lib/sub2api/provision.js +244 -0
- package/lib/sub2api/session.js +187 -0
- package/lib/tools.js +171 -0
- package/lib/util.js +225 -0
- package/package.json +76 -4
package/lib/routes.js
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-facing API.
|
|
3
|
+
*
|
|
4
|
+
* The panel cannot call sub2api directly: the control plane lives on another
|
|
5
|
+
* origin (CORS), the session token must never reach page scripts, and the pay
|
|
6
|
+
* centre needs a CSRF handshake. Everything therefore goes through these
|
|
7
|
+
* routes on the host.
|
|
8
|
+
*
|
|
9
|
+
* Every route refuses non-loopback callers. That is the only thing standing
|
|
10
|
+
* between a token-bearing local HTTP surface and another process on the same
|
|
11
|
+
* network, so it is applied by {@link defineRoute} rather than per handler.
|
|
12
|
+
* @module dsh-sub2api/routes
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { ROUTE_PREFIX } from "./constants.js";
|
|
16
|
+
import { buildRechargeLink, createRechargeOrder, describeOrderStatus, fetchOrderStatus } from "./pay.js";
|
|
17
|
+
import { loginOrRegister } from "./sub2api/auth.js";
|
|
18
|
+
import { provisionAccount } from "./sub2api/provision.js";
|
|
19
|
+
import { sessionFromAuth } from "./sub2api/session.js";
|
|
20
|
+
import {
|
|
21
|
+
Sub2ApiError,
|
|
22
|
+
isLoopbackRequest,
|
|
23
|
+
maskSecret,
|
|
24
|
+
readJsonBody,
|
|
25
|
+
writeJson,
|
|
26
|
+
} from "./util.js";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} deps
|
|
30
|
+
* @param {import("./sub2api/api.js").Sub2ApiApi} deps.api
|
|
31
|
+
* @param {import("./sub2api/session.js").SessionStore} deps.session
|
|
32
|
+
* @param {import("./sub2api/catalog.js").ModelCatalog} deps.catalog
|
|
33
|
+
* @param {() => any} deps.cfg resolved configuration, re-read per request
|
|
34
|
+
* @param {() => any} deps.hostname
|
|
35
|
+
* @param {(apiKey: string) => Promise<number>} deps.refreshCatalog
|
|
36
|
+
* @param {{info: Function, warn: Function}} deps.logger
|
|
37
|
+
* @returns {Array<{kind: "exact", path: string, handler: Function}>}
|
|
38
|
+
*/
|
|
39
|
+
export function makeRoutes(deps) {
|
|
40
|
+
const { api, session, catalog, cfg, logger } = deps;
|
|
41
|
+
|
|
42
|
+
/** Orders created by this process, keyed by the pay centre's order number. */
|
|
43
|
+
const orders = new Map();
|
|
44
|
+
|
|
45
|
+
/** Assemble the panel's view of the world. */
|
|
46
|
+
async function status() {
|
|
47
|
+
const stored = await session.read();
|
|
48
|
+
const apiKey = await session.apiKey();
|
|
49
|
+
await catalog.load();
|
|
50
|
+
|
|
51
|
+
/** @type {Record<string, unknown>} */
|
|
52
|
+
const view = {
|
|
53
|
+
apiBase: cfg().apiBase,
|
|
54
|
+
payBase: cfg().payBase,
|
|
55
|
+
keyName: cfg().keyName,
|
|
56
|
+
loggedIn: stored !== undefined,
|
|
57
|
+
email: stored?.email ?? stored?.user?.email ?? null,
|
|
58
|
+
user: stored?.user ?? null,
|
|
59
|
+
hasKey: typeof apiKey === "string" && apiKey !== "",
|
|
60
|
+
keyMasked: maskSecret(apiKey),
|
|
61
|
+
models: catalog.snapshot(),
|
|
62
|
+
showSidebarQuota: cfg().showSidebarQuota,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
if (stored !== undefined) {
|
|
66
|
+
const token = await session.accessToken().catch(() => undefined);
|
|
67
|
+
if (token !== undefined) {
|
|
68
|
+
const [profile, subscriptions, usage] = await Promise.all([
|
|
69
|
+
safe(() => api.profile(token)),
|
|
70
|
+
safe(() => api.subscriptionSummary(token)),
|
|
71
|
+
safe(() => api.usageDashboardStats(token)),
|
|
72
|
+
]);
|
|
73
|
+
view.profile = profile ?? null;
|
|
74
|
+
view.subscriptions = subscriptions ?? null;
|
|
75
|
+
view.usage = usage ?? null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return view;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return [
|
|
82
|
+
defineRoute("GET", `${ROUTE_PREFIX}/status`, async () => status()),
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* One form, two outcomes: log in, or register when the address is new.
|
|
86
|
+
* Provisioning runs before the response so the panel can render the final
|
|
87
|
+
* state in a single round trip.
|
|
88
|
+
*/
|
|
89
|
+
defineRoute("POST", `${ROUTE_PREFIX}/auth`, async (body) => {
|
|
90
|
+
const email = String(body?.email ?? "").trim().toLowerCase();
|
|
91
|
+
const password = String(body?.password ?? "");
|
|
92
|
+
const promoCode = String(body?.promoCode ?? "").trim();
|
|
93
|
+
const allowRegister = body?.allowRegister !== false;
|
|
94
|
+
|
|
95
|
+
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
|
96
|
+
throw new Sub2ApiError("请输入有效的邮箱地址", { code: "invalid_email" });
|
|
97
|
+
}
|
|
98
|
+
if (password.length < 6) {
|
|
99
|
+
throw new Sub2ApiError("密码至少 6 位", { code: "invalid_password" });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const { mode, auth } = await loginOrRegister({ api, email, password, promoCode, allowRegister });
|
|
103
|
+
const record = sessionFromAuth(auth, email);
|
|
104
|
+
await session.write(record);
|
|
105
|
+
|
|
106
|
+
const provisioned = await provisionAccount({
|
|
107
|
+
api,
|
|
108
|
+
accessToken: auth.access_token,
|
|
109
|
+
keyName: cfg().keyName,
|
|
110
|
+
groupId: cfg().groupId,
|
|
111
|
+
saveApiKey: (key) => session.setApiKey(key),
|
|
112
|
+
refreshCatalog: (key) => deps.refreshCatalog(key),
|
|
113
|
+
logger,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
logger.info?.(`[sub2api] ${mode === "register" ? "注册" : "登录"}成功:${email}`);
|
|
117
|
+
return { mode, steps: provisioned.steps, ready: provisioned.ready, state: await status() };
|
|
118
|
+
}),
|
|
119
|
+
|
|
120
|
+
defineRoute("POST", `${ROUTE_PREFIX}/logout`, async () => {
|
|
121
|
+
await session.clear();
|
|
122
|
+
orders.clear();
|
|
123
|
+
return { ok: true, state: await status() };
|
|
124
|
+
}),
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Create the key this plugin owns, or hand back the one that already
|
|
128
|
+
* carries its name. `force` skips the reuse and rotates the secret, which
|
|
129
|
+
* is what the panel's 「重建密钥」 button asks for.
|
|
130
|
+
*/
|
|
131
|
+
defineRoute("POST", `${ROUTE_PREFIX}/key`, async (body) => {
|
|
132
|
+
const token = await session.accessToken();
|
|
133
|
+
const groupId = typeof body?.groupId === "number" ? body.groupId : cfg().groupId;
|
|
134
|
+
const groups = await safe(() => api.groups(token));
|
|
135
|
+
|
|
136
|
+
const listed = await safe(() => api.listKeys(token));
|
|
137
|
+
const existing = (listed?.items ?? []).find(
|
|
138
|
+
(entry) => entry?.name === cfg().keyName && entry.status !== "inactive",
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
if (existing && body?.force !== true && typeof existing.key === "string") {
|
|
142
|
+
await session.setApiKey(existing.key);
|
|
143
|
+
const models = await deps.refreshCatalog(existing.key).catch(() => 0);
|
|
144
|
+
return {
|
|
145
|
+
ok: true,
|
|
146
|
+
reused: true,
|
|
147
|
+
keyMasked: maskSecret(existing.key),
|
|
148
|
+
groupId: existing.group_id ?? null,
|
|
149
|
+
groups: Array.isArray(groups) ? groups : [],
|
|
150
|
+
models,
|
|
151
|
+
state: await status(),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const created = await api.createKey(token, { name: cfg().keyName, groupId });
|
|
156
|
+
if (typeof created?.key !== "string" || created.key === "") {
|
|
157
|
+
throw new Sub2ApiError("服务器没有返回密钥值", { code: "key_missing" });
|
|
158
|
+
}
|
|
159
|
+
await session.setApiKey(created.key);
|
|
160
|
+
|
|
161
|
+
// Rotate rather than accumulate: the old key is only removed once the new
|
|
162
|
+
// one is safely stored.
|
|
163
|
+
if (existing && body?.force === true && typeof existing.id === "number") {
|
|
164
|
+
await safe(() => api.deleteKey(token, existing.id));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const models = await deps.refreshCatalog(created.key).catch(() => 0);
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
ok: true,
|
|
171
|
+
reused: false,
|
|
172
|
+
keyMasked: maskSecret(created.key),
|
|
173
|
+
groupId: created.group_id ?? groupId ?? null,
|
|
174
|
+
groups: Array.isArray(groups) ? groups : [],
|
|
175
|
+
models,
|
|
176
|
+
state: await status(),
|
|
177
|
+
};
|
|
178
|
+
}),
|
|
179
|
+
|
|
180
|
+
/** One-shot plaintext reveal for the copy button; loopback only, never cached. */
|
|
181
|
+
defineRoute("POST", `${ROUTE_PREFIX}/key/reveal`, async () => {
|
|
182
|
+
const apiKey = await session.apiKey();
|
|
183
|
+
if (apiKey === undefined) throw new Sub2ApiError("还没有可用的密钥", { code: "no_api_key" });
|
|
184
|
+
return { key: apiKey };
|
|
185
|
+
}),
|
|
186
|
+
|
|
187
|
+
/** Re-read the account snapshot without a full login. */
|
|
188
|
+
defineRoute("GET", `${ROUTE_PREFIX}/profile`, async () => {
|
|
189
|
+
const token = await session.accessToken();
|
|
190
|
+
const [profile, groups, subscriptions, usage] = await Promise.all([
|
|
191
|
+
safe(() => api.profile(token)),
|
|
192
|
+
safe(() => api.groups(token)),
|
|
193
|
+
safe(() => api.subscriptionSummary(token)),
|
|
194
|
+
safe(() => api.usageDashboardStats(token)),
|
|
195
|
+
]);
|
|
196
|
+
return { profile: profile ?? null, groups: groups ?? [], subscriptions: subscriptions ?? null, usage: usage ?? null };
|
|
197
|
+
}),
|
|
198
|
+
|
|
199
|
+
defineRoute("GET", `${ROUTE_PREFIX}/models`, async () => {
|
|
200
|
+
await catalog.load();
|
|
201
|
+
return catalog.snapshot();
|
|
202
|
+
}),
|
|
203
|
+
|
|
204
|
+
defineRoute("POST", `${ROUTE_PREFIX}/models/refresh`, async () => {
|
|
205
|
+
let count = 0;
|
|
206
|
+
let error;
|
|
207
|
+
try {
|
|
208
|
+
count = await catalog.refresh();
|
|
209
|
+
} catch (failure) {
|
|
210
|
+
// A refresh failure is data the panel shows, not an HTTP error: the
|
|
211
|
+
// usual case is a zero-balance account, which is expected, not a fault.
|
|
212
|
+
error = {
|
|
213
|
+
code: failure instanceof Sub2ApiError ? failure.code : undefined,
|
|
214
|
+
message: failure instanceof Error ? failure.message : String(failure),
|
|
215
|
+
status: failure instanceof Sub2ApiError ? failure.status : undefined,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
return { ok: error === undefined, count, error: error ?? null, models: catalog.snapshot() };
|
|
219
|
+
}),
|
|
220
|
+
|
|
221
|
+
/** Recharge level 1: a signed-in URL the browser opens in a new tab. */
|
|
222
|
+
defineRoute("POST", `${ROUTE_PREFIX}/recharge/link`, async (body) => {
|
|
223
|
+
const stored = await session.read();
|
|
224
|
+
const token = await session.accessToken();
|
|
225
|
+
const userId = stored?.user?.id;
|
|
226
|
+
if (userId === undefined || userId === null) {
|
|
227
|
+
throw new Sub2ApiError("登录信息缺少用户 ID,请重新登录", { code: "no_user_id" });
|
|
228
|
+
}
|
|
229
|
+
const url = buildRechargeLink({
|
|
230
|
+
payBase: cfg().payBase,
|
|
231
|
+
userId,
|
|
232
|
+
token,
|
|
233
|
+
theme: body?.theme === "dark" ? "dark" : "light",
|
|
234
|
+
lang: "zh",
|
|
235
|
+
srcHost: "dsh",
|
|
236
|
+
});
|
|
237
|
+
return { url };
|
|
238
|
+
}),
|
|
239
|
+
|
|
240
|
+
/** Recharge level 2: choose the amount here and land straight on checkout. */
|
|
241
|
+
defineRoute("POST", `${ROUTE_PREFIX}/recharge`, async (body) => {
|
|
242
|
+
const stored = await session.read();
|
|
243
|
+
const token = await session.accessToken();
|
|
244
|
+
const userId = stored?.user?.id;
|
|
245
|
+
if (userId === undefined || userId === null) {
|
|
246
|
+
throw new Sub2ApiError("登录信息缺少用户 ID,请重新登录", { code: "no_user_id" });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const order = await createRechargeOrder({
|
|
250
|
+
payBase: cfg().payBase,
|
|
251
|
+
userId,
|
|
252
|
+
token,
|
|
253
|
+
amountYuan: Number(body?.amountYuan),
|
|
254
|
+
theme: body?.theme === "dark" ? "dark" : "light",
|
|
255
|
+
timeoutMs: cfg().requestTimeoutMs,
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
orders.set(order.orderNo, {
|
|
259
|
+
expires: order.expires,
|
|
260
|
+
checkoutToken: order.checkoutToken,
|
|
261
|
+
createdAt: Date.now(),
|
|
262
|
+
});
|
|
263
|
+
// 30 minutes is the pay centre's own order lifetime; anything older is noise.
|
|
264
|
+
for (const [key, value] of orders) {
|
|
265
|
+
if (Date.now() - value.createdAt > 40 * 60 * 1000) orders.delete(key);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { checkoutUrl: order.checkoutUrl, orderNo: order.orderNo };
|
|
269
|
+
}),
|
|
270
|
+
|
|
271
|
+
defineRoute("POST", `${ROUTE_PREFIX}/recharge/status`, async (body) => {
|
|
272
|
+
const orderNo = String(body?.orderNo ?? "");
|
|
273
|
+
const known = orders.get(orderNo);
|
|
274
|
+
if (known === undefined) {
|
|
275
|
+
throw new Sub2ApiError("订单不存在或已过期", { code: "order_gone" });
|
|
276
|
+
}
|
|
277
|
+
const data = await fetchOrderStatus({
|
|
278
|
+
payBase: cfg().payBase,
|
|
279
|
+
orderNo,
|
|
280
|
+
expires: known.expires,
|
|
281
|
+
checkoutToken: known.checkoutToken,
|
|
282
|
+
timeoutMs: cfg().requestTimeoutMs,
|
|
283
|
+
});
|
|
284
|
+
const status = describeOrderStatus(data);
|
|
285
|
+
if (status.tone === "done") {
|
|
286
|
+
// The order is settled; stop tracking it and let the panel refresh.
|
|
287
|
+
orders.delete(orderNo);
|
|
288
|
+
const token = await session.accessToken().catch(() => undefined);
|
|
289
|
+
const profile = token ? await safe(() => api.profile(token)) : undefined;
|
|
290
|
+
// Money just landed, which is what unblocks `/v1/models` on a fresh
|
|
291
|
+
// account, so try the catalog now instead of waiting for the TTL.
|
|
292
|
+
let models;
|
|
293
|
+
try {
|
|
294
|
+
models = { count: await catalog.refresh() };
|
|
295
|
+
} catch (failure) {
|
|
296
|
+
models = {
|
|
297
|
+
count: 0,
|
|
298
|
+
error: failure instanceof Error ? failure.message : String(failure),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
return { ...status, raw: data, profile: profile ?? null, models };
|
|
302
|
+
}
|
|
303
|
+
if (status.tone === "error") orders.delete(orderNo);
|
|
304
|
+
return { ...status, raw: data };
|
|
305
|
+
}),
|
|
306
|
+
|
|
307
|
+
defineRoute("POST", `${ROUTE_PREFIX}/redeem`, async (body) => {
|
|
308
|
+
const code = String(body?.code ?? "").trim();
|
|
309
|
+
if (code === "") throw new Sub2ApiError("请输入兑换码", { code: "invalid_code" });
|
|
310
|
+
const token = await session.accessToken();
|
|
311
|
+
const result = await api.redeem(token, code);
|
|
312
|
+
const profile = await safe(() => api.profile(token));
|
|
313
|
+
return { ok: true, result, profile: profile ?? null };
|
|
314
|
+
}),
|
|
315
|
+
|
|
316
|
+
defineRoute("GET", `${ROUTE_PREFIX}/announcements`, async () => {
|
|
317
|
+
const token = await session.accessToken().catch(() => undefined);
|
|
318
|
+
if (token === undefined) return { items: [] };
|
|
319
|
+
const items = await safe(() => api.announcements(token));
|
|
320
|
+
return { items: Array.isArray(items) ? items : [] };
|
|
321
|
+
}),
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Wrap one route with the method guard, the loopback guard and error
|
|
327
|
+
* translation. Keeping this in one place is what stops a new route from
|
|
328
|
+
* shipping without the check.
|
|
329
|
+
*/
|
|
330
|
+
function defineRoute(method, path, handler) {
|
|
331
|
+
return {
|
|
332
|
+
kind: "exact",
|
|
333
|
+
path,
|
|
334
|
+
handler: async (req, res) => {
|
|
335
|
+
if (!isLoopbackRequest(req)) {
|
|
336
|
+
writeJson(res, 403, { ok: false, error: "forbidden: loopback-only" });
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if ((req.method ?? "GET").toUpperCase() !== method) {
|
|
340
|
+
writeJson(res, 405, { ok: false, error: `method not allowed: ${req.method}` });
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
let body;
|
|
345
|
+
if (method !== "GET") {
|
|
346
|
+
body = await readJsonBody(req);
|
|
347
|
+
if (body === undefined) {
|
|
348
|
+
writeJson(res, 400, { ok: false, error: "invalid JSON body" });
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
try {
|
|
354
|
+
writeJson(res, 200, { ok: true, data: await handler(body ?? {}, req) });
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (error instanceof Sub2ApiError) {
|
|
357
|
+
writeJson(res, error.status && error.status >= 400 ? error.status : 400, {
|
|
358
|
+
ok: false,
|
|
359
|
+
error: error.message,
|
|
360
|
+
code: error.code,
|
|
361
|
+
});
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
365
|
+
writeJson(res, 500, { ok: false, error: message });
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Run one optional read, mapping a failure to `undefined` instead of rejecting. */
|
|
372
|
+
async function safe(run) {
|
|
373
|
+
try {
|
|
374
|
+
return await run();
|
|
375
|
+
} catch {
|
|
376
|
+
return undefined;
|
|
377
|
+
}
|
|
378
|
+
}
|
package/lib/schema.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's configuration schema.
|
|
3
|
+
*
|
|
4
|
+
* Exporting this is not cosmetic: the Models page only lists provider cards
|
|
5
|
+
* whose settings namespace is schema-declared, and the settings page only
|
|
6
|
+
* projects fields that a schema marks. A plugin without it registers a route
|
|
7
|
+
* that no surface can configure.
|
|
8
|
+
*
|
|
9
|
+
* Every field is volatile, so a settings-page write updates the running plugin
|
|
10
|
+
* in place — `resolveConfig` re-reads each field on use, which is what makes a
|
|
11
|
+
* new `apiBase` apply to the next request without a restart.
|
|
12
|
+
* @module dsh-sub2api/schema
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import z from "@deepseek-ai/schemastery";
|
|
16
|
+
import { API_KEY_REF, KEY_NAME } from "./constants.js";
|
|
17
|
+
|
|
18
|
+
const text = (fallback, description) =>
|
|
19
|
+
z.string().default(fallback).description(description).volatile();
|
|
20
|
+
|
|
21
|
+
const count = (description) => z.natural().description(description).volatile();
|
|
22
|
+
|
|
23
|
+
export const Config = z.object({
|
|
24
|
+
apiBase: text("https://sub.pscly.cc", "中转站地址;末尾的 /v1 会被自动去掉"),
|
|
25
|
+
payBase: text("https://pay.pscly.cc", "充值中转站地址(独立服务)"),
|
|
26
|
+
apiKeyEnv: text(API_KEY_REF, "存放 API Key 的凭据引用名"),
|
|
27
|
+
keyName: text(KEY_NAME, "自动创建/复用的密钥名称"),
|
|
28
|
+
groupId: count("强制指定密钥所属分组;留空则跟随账号的默认分组"),
|
|
29
|
+
requestTimeoutMs: count("普通请求超时(毫秒)").default(300000),
|
|
30
|
+
streamIdleTimeoutMs: count("流式请求空闲超时(毫秒)").default(300000),
|
|
31
|
+
modelsCachePath: text("", "模型目录缓存路径;留空使用 $DSH_HOME/sub2api-models.json"),
|
|
32
|
+
visibleModels: z.array(z.string()).description("只在这些模型 id 中显示;留空显示全部").volatile(),
|
|
33
|
+
contextWindow: count("强制覆盖上下文窗口;留空跟随上游"),
|
|
34
|
+
showSidebarQuota: z.boolean().default(false).description("在侧边栏显示余额卡片").volatile(),
|
|
35
|
+
autoProvision: z.boolean().default(true).description("登录后自动创建并保存密钥").volatile(),
|
|
36
|
+
announceToAgent: z.boolean().default(true).description("向 agent 注入插件说明").volatile(),
|
|
37
|
+
});
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sub2api control-plane client.
|
|
3
|
+
*
|
|
4
|
+
* Covers exactly what the panel needs: authentication, the account snapshot,
|
|
5
|
+
* key management, groups, subscriptions, usage and redeem codes. The model
|
|
6
|
+
* gateway (an OpenAI-compatible `/v1`) is a separate concern and lives in
|
|
7
|
+
* `catalog.js` / the transport adapter.
|
|
8
|
+
*
|
|
9
|
+
* Every call resolves the same `{code, message, data}` envelope through
|
|
10
|
+
* `requestJson`, so a caller only ever sees the payload or a `Sub2ApiError`.
|
|
11
|
+
* @module dsh-sub2api/sub2api/api
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { KEY_PAGE_SIZE } from "../constants.js";
|
|
15
|
+
import { Sub2ApiError, requestJson } from "../util.js";
|
|
16
|
+
|
|
17
|
+
export class Sub2ApiApi {
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} deps
|
|
20
|
+
* @param {() => string} deps.apiBase current site origin, read per call so a settings change applies
|
|
21
|
+
* @param {() => number} deps.timeoutMs request deadline
|
|
22
|
+
* @param {typeof fetch} [deps.fetchImpl] replacement transport for tests
|
|
23
|
+
*/
|
|
24
|
+
constructor(deps) {
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param {string} path */
|
|
29
|
+
#url(path) {
|
|
30
|
+
return `${this.deps.apiBase()}${path}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {string} path
|
|
35
|
+
* @param {object} [options]
|
|
36
|
+
* @param {string} [options.method]
|
|
37
|
+
* @param {unknown} [options.body]
|
|
38
|
+
* @param {string} [options.token] bearer access token
|
|
39
|
+
* @param {AbortSignal} [options.signal]
|
|
40
|
+
*/
|
|
41
|
+
async #call(path, options = {}) {
|
|
42
|
+
const headers = {};
|
|
43
|
+
if (options.token) headers.Authorization = `Bearer ${options.token}`;
|
|
44
|
+
try {
|
|
45
|
+
const { payload } = await requestJson(this.#url(path), {
|
|
46
|
+
method: options.method ?? "GET",
|
|
47
|
+
headers,
|
|
48
|
+
body: options.body,
|
|
49
|
+
timeoutMs: this.deps.timeoutMs(),
|
|
50
|
+
signal: options.signal,
|
|
51
|
+
fetchImpl: this.deps.fetchImpl,
|
|
52
|
+
});
|
|
53
|
+
return payload;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
throw annotate(error, path);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------- auth
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Exchange a password for tokens.
|
|
63
|
+
* @returns {Promise<AuthResponse>}
|
|
64
|
+
*/
|
|
65
|
+
login(email, password) {
|
|
66
|
+
return this.#call("/api/v1/auth/login", { method: "POST", body: { email, password } });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Create an account. The site returns the same payload as `login`, because
|
|
71
|
+
* email verification is disabled on this deployment — that is what makes
|
|
72
|
+
* "register and start chatting" a single step.
|
|
73
|
+
* @returns {Promise<AuthResponse>}
|
|
74
|
+
*/
|
|
75
|
+
register({ email, password, username, promoCode }) {
|
|
76
|
+
const body = { email, password };
|
|
77
|
+
if (username) body.username = username;
|
|
78
|
+
if (promoCode) body.promo_code = promoCode;
|
|
79
|
+
return this.#call("/api/v1/auth/register", { method: "POST", body });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** @returns {Promise<AuthResponse>} a fresh token pair */
|
|
83
|
+
refresh(refreshToken) {
|
|
84
|
+
return this.#call("/api/v1/auth/refresh", {
|
|
85
|
+
method: "POST",
|
|
86
|
+
body: { refresh_token: refreshToken },
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
me(token, signal) {
|
|
91
|
+
return this.#call("/api/v1/auth/me", { token, signal });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
logout(token) {
|
|
95
|
+
return this.#call("/api/v1/auth/logout", { method: "POST", token });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
validatePromoCode(code) {
|
|
99
|
+
return this.#call("/api/v1/auth/validate-promo-code", { method: "POST", body: { code } });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// -------------------------------------------------------------- account
|
|
103
|
+
|
|
104
|
+
profile(token, signal) {
|
|
105
|
+
return this.#call("/api/v1/user/profile", { token, signal });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
platformQuotas(token, signal) {
|
|
109
|
+
return this.#call("/api/v1/user/platform-quotas", { token, signal });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Groups this user may bind a key to. */
|
|
113
|
+
groups(token, signal) {
|
|
114
|
+
return this.#call("/api/v1/groups/available", { token, signal });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ------------------------------------------------------------------ keys
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* @param {string} token
|
|
121
|
+
* @param {{page?: number, pageSize?: number, signal?: AbortSignal}} [options]
|
|
122
|
+
* @returns {Promise<{items?: KeyRecord[], total?: number, page?: number, page_size?: number}>}
|
|
123
|
+
*/
|
|
124
|
+
listKeys(token, options = {}) {
|
|
125
|
+
const page = options.page ?? 1;
|
|
126
|
+
const pageSize = options.pageSize ?? KEY_PAGE_SIZE;
|
|
127
|
+
return this.#call(`/api/v1/keys?page=${page}&page_size=${pageSize}`, {
|
|
128
|
+
token,
|
|
129
|
+
signal: options.signal,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Create a key. The response carries the plaintext value in `key`, which is
|
|
135
|
+
* the only moment it can be captured without the user copying it by hand.
|
|
136
|
+
* @param {string} token
|
|
137
|
+
* @param {{name: string, groupId?: number|null, quota?: number, expiresInDays?: number}} input
|
|
138
|
+
*/
|
|
139
|
+
createKey(token, input) {
|
|
140
|
+
const body = { name: input.name };
|
|
141
|
+
if (input.groupId !== undefined && input.groupId !== null) body.group_id = input.groupId;
|
|
142
|
+
if (typeof input.quota === "number" && input.quota > 0) body.quota = input.quota;
|
|
143
|
+
if (typeof input.expiresInDays === "number" && input.expiresInDays > 0) {
|
|
144
|
+
body.expires_in_days = input.expiresInDays;
|
|
145
|
+
}
|
|
146
|
+
return this.#call("/api/v1/keys", { method: "POST", token, body });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
updateKey(token, id, patch) {
|
|
150
|
+
return this.#call(`/api/v1/keys/${id}`, { method: "PUT", token, body: patch });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
deleteKey(token, id) {
|
|
154
|
+
return this.#call(`/api/v1/keys/${id}`, { method: "DELETE", token });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// --------------------------------------------------------- subscriptions
|
|
158
|
+
|
|
159
|
+
activeSubscriptions(token, signal) {
|
|
160
|
+
return this.#call("/api/v1/subscriptions/active", { token, signal });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
subscriptionProgress(token, signal) {
|
|
164
|
+
return this.#call("/api/v1/subscriptions/progress", { token, signal });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
subscriptionSummary(token, signal) {
|
|
168
|
+
return this.#call("/api/v1/subscriptions/summary", { token, signal });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ----------------------------------------------------------------- usage
|
|
172
|
+
|
|
173
|
+
usageStats(token, signal) {
|
|
174
|
+
return this.#call("/api/v1/usage/stats", { token, signal });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
usageDashboardStats(token, signal) {
|
|
178
|
+
return this.#call("/api/v1/usage/dashboard/stats", { token, signal });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---------------------------------------------------------------- redeem
|
|
182
|
+
|
|
183
|
+
redeem(token, code) {
|
|
184
|
+
return this.#call("/api/v1/redeem", { method: "POST", token, body: { code } });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ----------------------------------------------------------- public site
|
|
188
|
+
|
|
189
|
+
publicSettings(signal) {
|
|
190
|
+
return this.#call("/api/v1/settings/public", { signal });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Site announcements; the list is empty when the operator published none. */
|
|
194
|
+
announcements(token, signal) {
|
|
195
|
+
return this.#call("/api/v1/announcements", { token, signal });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// -------------------------------------------------------- model gateway
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The model catalog, authenticated with the user's API key rather than a session.
|
|
202
|
+
* @param {string} apiKey
|
|
203
|
+
* @param {AbortSignal} [signal]
|
|
204
|
+
*/
|
|
205
|
+
gatewayModels(apiKey, signal, baseUrl) {
|
|
206
|
+
return this.#gateway("/v1/models", apiKey, signal, baseUrl);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Per-key billing facts. Unlike the profile endpoint this needs no login, so
|
|
211
|
+
* the sidebar can show a balance before the panel is opened.
|
|
212
|
+
*/
|
|
213
|
+
gatewayBilling(apiKey, signal) {
|
|
214
|
+
return this.#gateway("/v1/sub2api/billing", apiKey, signal);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async #gateway(path, apiKey, signal, baseUrl) {
|
|
218
|
+
const root = baseUrl === undefined || baseUrl === "" ? this.deps.apiBase() : String(baseUrl).replace(/\/+$/, "");
|
|
219
|
+
try {
|
|
220
|
+
const { payload } = await requestJson(`${root}${path}`, {
|
|
221
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
222
|
+
timeoutMs: this.deps.timeoutMs(),
|
|
223
|
+
signal,
|
|
224
|
+
fetchImpl: this.deps.fetchImpl,
|
|
225
|
+
});
|
|
226
|
+
return payload;
|
|
227
|
+
} catch (error) {
|
|
228
|
+
throw annotate(error, path);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Attach the endpoint (never the query string) to an error so a UI message can
|
|
235
|
+
* say which call failed without leaking tokens.
|
|
236
|
+
*/
|
|
237
|
+
function annotate(error, path) {
|
|
238
|
+
if (error instanceof Sub2ApiError && error.status !== undefined) {
|
|
239
|
+
error.endpoint = path;
|
|
240
|
+
return error;
|
|
241
|
+
}
|
|
242
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
243
|
+
return new Sub2ApiError(`${path} 请求失败:${message}`, { code: "transport", cause: error });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** @typedef {{access_token: string, refresh_token?: string, expires_in?: number, user?: any}} AuthResponse */
|
|
247
|
+
/** @typedef {{id: number, key: string, name: string, group_id?: number|null, status: string, quota?: number, quota_used?: number}} KeyRecord */
|