-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1613 lines (1478 loc) · 60.7 KB
/
Copy pathserver.js
File metadata and controls
1613 lines (1478 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const http = require("http");
const fs = require("fs/promises");
const path = require("path");
const crypto = require("crypto");
const ROOT = __dirname;
const PUBLIC_DIR = path.join(ROOT, "public");
const DATA_DIR = path.join(ROOT, "data");
const STORE_FILE = path.join(DATA_DIR, "store.json");
const SECRET_FILE = path.join(DATA_DIR, "secret.key");
const PORT = Number(process.env.PORT || 4173);
const COOKIE_NAME = "apihub_session";
const SESSION_TTL_MS = 1000 * 60 * 60 * 12;
const DEFAULT_USER = process.env.APIHUB_ADMIN_USER || "admin";
const CONFIGURED_PASSWORD = process.env.APIHUB_ADMIN_PASSWORD || "";
const LEGACY_DEFAULT_PASSWORD = "ChangeMe123!";
const COOKIE_SECURE = process.env.APIHUB_COOKIE_SECURE === "true";
const sessions = new Map();
const refreshAccessCache = new Map();
let cachedSecret;
let bootstrapPasswordNotice = "";
const mimeTypes = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".webmanifest": "application/manifest+json; charset=utf-8"
};
function id(prefix = "id") {
return `${prefix}_${crypto.randomBytes(8).toString("hex")}`;
}
function nowIso() {
return new Date().toISOString();
}
function timingSafeEqualText(a, b) {
const ab = Buffer.from(String(a));
const bb = Buffer.from(String(b));
if (ab.length !== bb.length) return false;
return crypto.timingSafeEqual(ab, bb);
}
function hashPassword(password, salt = crypto.randomBytes(16).toString("hex")) {
const hash = crypto.pbkdf2Sync(String(password), salt, 210000, 32, "sha256").toString("hex");
return { salt, hash };
}
function verifyPassword(password, record) {
const attempt = hashPassword(password, record.salt);
return timingSafeEqualText(attempt.hash, record.hash);
}
function randomPassword() {
return crypto.randomBytes(24).toString("base64url");
}
async function persistInitialPassword(password) {
const file = path.join(DATA_DIR, "initial-admin-password.txt");
await fs.writeFile(
file,
[
"API Hub Mobile initial admin password",
"",
`username: ${DEFAULT_USER}`,
`password: ${password}`,
"",
"Log in once, change this password in Settings, then delete this file."
].join("\n"),
{ mode: 0o600 }
);
bootstrapPasswordNotice = `Initial admin password was written to ${file}`;
}
async function ensureData() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(STORE_FILE);
const store = JSON.parse(await fs.readFile(STORE_FILE, "utf8"));
if (!CONFIGURED_PASSWORD && verifyPassword(LEGACY_DEFAULT_PASSWORD, store.user.password)) {
const password = randomPassword();
store.user.password = hashPassword(password);
await writeStore(store);
await persistInitialPassword(password);
}
} catch {
const initialPassword = CONFIGURED_PASSWORD || randomPassword();
const password = hashPassword(initialPassword);
await writeStore({
version: 1,
user: { username: DEFAULT_USER, password },
sites: [],
audit: []
});
if (!CONFIGURED_PASSWORD) await persistInitialPassword(initialPassword);
}
}
async function masterSecret() {
if (cachedSecret) return cachedSecret;
if (process.env.APIHUB_SECRET) {
cachedSecret = crypto.createHash("sha256").update(process.env.APIHUB_SECRET).digest();
return cachedSecret;
}
try {
const existing = await fs.readFile(SECRET_FILE, "utf8");
cachedSecret = Buffer.from(existing.trim(), "hex");
return cachedSecret;
} catch {
const created = crypto.randomBytes(32);
await fs.writeFile(SECRET_FILE, created.toString("hex"), { mode: 0o600 });
cachedSecret = created;
return cachedSecret;
}
}
async function readStore() {
await ensureData();
const store = JSON.parse(await fs.readFile(STORE_FILE, "utf8"));
if (!Array.isArray(store.sites)) store.sites = [];
if (!Array.isArray(store.credentials)) store.credentials = [];
if (!Array.isArray(store.audit)) store.audit = [];
return store;
}
async function writeStore(store) {
await fs.mkdir(DATA_DIR, { recursive: true });
await fs.writeFile(STORE_FILE, `${JSON.stringify(store, null, 2)}\n`);
}
async function encryptSecret(value) {
if (!value) return null;
const key = await masterSecret();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const encrypted = Buffer.concat([cipher.update(String(value), "utf8"), cipher.final()]);
return {
alg: "aes-256-gcm",
iv: iv.toString("base64"),
tag: cipher.getAuthTag().toString("base64"),
data: encrypted.toString("base64")
};
}
async function decryptSecret(record) {
if (!record) return "";
const key = await masterSecret();
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(record.iv, "base64"));
decipher.setAuthTag(Buffer.from(record.tag, "base64"));
return Buffer.concat([
decipher.update(Buffer.from(record.data, "base64")),
decipher.final()
]).toString("utf8");
}
function mask(value) {
if (!value) return "";
const text = String(value);
if (text.length <= 8) return "••••";
return `${text.slice(0, 4)}••••${text.slice(-4)}`;
}
function sanitizeSite(site) {
return {
id: site.id,
name: site.name,
type: site.type,
baseUrl: site.baseUrl,
authType: site.authType,
enabled: site.enabled,
note: site.note || "",
lastCheckedAt: site.lastCheckedAt || null,
lastStatus: site.lastStatus || "unknown",
lastError: site.lastError || "",
userId: site.userId || "",
maskedCredential: site.maskedCredential || ""
};
}
function sanitizeCredential(credential) {
return {
id: credential.id,
name: credential.name,
baseUrl: credential.baseUrl,
provider: credential.provider || "openai-compatible",
group: credential.group || "default",
enabled: credential.enabled,
note: credential.note || "",
lastCheckedAt: credential.lastCheckedAt || null,
lastStatus: credential.lastStatus || "unknown",
lastError: credential.lastError || "",
maskedKey: credential.maskedKey || ""
};
}
async function readJson(req) {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
if (!chunks.length) return {};
const raw = Buffer.concat(chunks).toString("utf8");
try {
return JSON.parse(raw);
} catch {
throw new HttpError(400, "请求体不是有效 JSON");
}
}
class HttpError extends Error {
constructor(status, message, details) {
super(message);
this.status = status;
this.details = details;
}
}
function send(res, status, data, headers = {}) {
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
...headers
});
res.end(JSON.stringify(data));
}
function setSessionCookie(res, token) {
const secure = COOKIE_SECURE ? "; Secure" : "";
res.setHeader("Set-Cookie", `${COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL_MS / 1000}${secure}`);
}
function clearSessionCookie(res) {
const secure = COOKIE_SECURE ? "; Secure" : "";
res.setHeader("Set-Cookie", `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`);
}
function cookie(req, name) {
const source = req.headers.cookie || "";
for (const part of source.split(";")) {
const [k, ...rest] = part.trim().split("=");
if (k === name) return decodeURIComponent(rest.join("="));
}
return "";
}
async function requireSession(req) {
const token = cookie(req, COOKIE_NAME);
const session = token && sessions.get(token);
if (!session || session.expiresAt < Date.now()) {
if (token) sessions.delete(token);
throw new HttpError(401, "请先登录");
}
session.expiresAt = Date.now() + SESSION_TTL_MS;
return session;
}
function cleanBaseUrl(baseUrl) {
try {
const parsed = new URL(baseUrl);
parsed.pathname = parsed.pathname.replace(/\/+$/, "");
parsed.search = "";
parsed.hash = "";
return parsed.toString().replace(/\/$/, "");
} catch {
throw new HttpError(400, "Base URL 格式不正确");
}
}
async function siteFromInput(input, existing = {}) {
const type = input.type === "auto" ? inferType(input) : input.type;
if (!["newapi", "sub2api"].includes(type)) throw new HttpError(400, "站点类型必须是 New API 或 Sub2API");
const secrets = { ...(existing.secrets || {}) };
let maskedCredential = existing.maskedCredential || "";
for (const field of ["systemToken", "jwt", "apiKey", "adminToken", "sessionCookie", "refreshToken", "password"]) {
if (input[field]) {
secrets[field] = await encryptSecret(input[field]);
if (["systemToken", "jwt", "apiKey", "adminToken", "sessionCookie", "refreshToken"].includes(field)) maskedCredential = mask(input[field]);
}
}
return {
...existing,
id: existing.id || id("site"),
name: String(input.name || existing.name || "").trim(),
type,
baseUrl: cleanBaseUrl(input.baseUrl || existing.baseUrl || ""),
authType: input.authType || existing.authType || (type === "newapi" ? "system-token" : "jwt"),
enabled: Boolean(input.enabled ?? existing.enabled ?? true),
note: String(input.note ?? existing.note ?? "").trim(),
userId: String(input.userId ?? existing.userId ?? "").trim(),
username: String(input.username ?? existing.username ?? "").trim(),
maskedCredential,
secrets,
createdAt: existing.createdAt || nowIso(),
updatedAt: nowIso()
};
}
async function credentialFromInput(input, existing = {}) {
const secrets = { ...(existing.secrets || {}) };
let maskedKey = existing.maskedKey || "";
if (input.apiKey) {
secrets.apiKey = await encryptSecret(input.apiKey);
maskedKey = mask(input.apiKey);
}
return {
...existing,
id: existing.id || id("cred"),
name: String(input.name || existing.name || "").trim(),
provider: String(input.provider || existing.provider || "openai-compatible").trim(),
baseUrl: cleanBaseUrl(input.baseUrl || existing.baseUrl || ""),
group: String(input.group ?? existing.group ?? "default").trim() || "default",
enabled: Boolean(input.enabled ?? existing.enabled ?? true),
note: String(input.note ?? existing.note ?? "").trim(),
maskedKey,
secrets,
createdAt: existing.createdAt || nowIso(),
updatedAt: nowIso()
};
}
function inferType(input) {
if (input.systemToken || input.userId) return "newapi";
return "sub2api";
}
const COMMON_LIST_KEYS = ["items", "rows", "list", "records", "results", "data"];
const NEW_API_QUOTA_PER_USD = 500000;
const NEW_API_USER_ID_HEADERS = [
"New-API-User",
"Veloera-User",
"X-Api-User",
"voapi-user",
"User-id",
"Rix-Api-User",
"neo-api-user"
];
function firstDefined(...values) {
return values.find((value) => value !== undefined && value !== null && value !== "");
}
function asNumber(value, fallback = 0) {
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
}
function isPlainObject(value) {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function looksLikeModel(item) {
if (typeof item === "string") return true;
if (!isPlainObject(item)) return false;
return ["id", "model", "name", "owned_by", "provider", "quota_type", "category", "price", "groups"].some((key) => item[key] !== undefined);
}
function looksLikeKey(item) {
if (!isPlainObject(item)) return false;
return [
"id",
"key_id",
"token_id",
"key",
"token",
"value",
"maskedKey",
"masked_key",
"name",
"key_name",
"token_name",
"description",
"api_key",
"access_token",
"quota",
"used_quota",
"remain_quota",
"usage",
"limit"
].some((key) => item[key] !== undefined);
}
function looksLikeLog(item) {
if (!isPlainObject(item)) return false;
return [
"id",
"created_at",
"createdAt",
"token_name",
"key_name",
"model_name",
"model",
"quota",
"usage",
"prompt_tokens",
"completion_tokens",
"total_tokens",
"content"
].some((key) => item[key] !== undefined);
}
function objectValuesAsList(value, predicate) {
if (!isPlainObject(value)) return [];
const values = Object.entries(value)
.map(([key, item]) => (isPlainObject(item) ? { id: key, ...item } : item))
.filter((item) => isPlainObject(item) || typeof item === "string");
if (!values.length) return [];
return values.some(predicate) ? values : [];
}
function extractList(payload, keys, predicate) {
if (Array.isArray(payload)) return payload;
if (!isPlainObject(payload)) return [];
const listKeys = [...keys, ...COMMON_LIST_KEYS];
const candidates = [payload, payload.data].filter(isPlainObject);
for (const source of candidates) {
for (const key of listKeys) {
const value = source[key];
if (Array.isArray(value)) return value;
const mapped = objectValuesAsList(value, predicate);
if (mapped.length) return mapped;
}
}
for (const source of candidates) {
const mapped = objectValuesAsList(source, predicate);
if (mapped.length) return mapped;
}
return [];
}
function computeModelPricing(site, item) {
const directInput = firstDefined(
item.inputPrice,
item.input_price,
item.prompt_price,
item.price?.input,
item.pricing?.input
);
const directOutput = firstDefined(
item.outputPrice,
item.output_price,
item.completion_price,
item.price?.output,
item.pricing?.output
);
const modelRatio = asNumber(firstDefined(item.model_ratio, item.modelRatio, item.ratio, item.quota_ratio), 0);
const completionRatio = asNumber(firstDefined(item.completion_ratio, item.completionRatio, item.output_ratio), 1);
const groupRatio = asNumber(firstDefined(item.group_ratio, item.groupRatio, item.groups?.[0]?.ratio), 1);
const modelPrice = asNumber(firstDefined(item.model_price, item.modelPrice), 0);
const promptQuotaPer1K = modelPrice > 0 ? modelPrice : modelRatio * groupRatio * 1000;
const completionQuotaPer1K = modelPrice > 0 ? modelPrice : modelRatio * completionRatio * groupRatio * 1000;
const inputUsd = directInput !== undefined ? asNumber(directInput) : site.type === "newapi" ? quotaToUsd(promptQuotaPer1K) : 0;
const outputUsd = directOutput !== undefined ? asNumber(directOutput) : site.type === "newapi" ? quotaToUsd(completionQuotaPer1K) : 0;
return {
inputPer1KUsd: inputUsd,
outputPer1KUsd: outputUsd,
blendedPer1KUsd: inputUsd || outputUsd ? (inputUsd + outputUsd) / 2 : 0,
promptQuotaPer1K,
completionQuotaPer1K,
modelRatio,
completionRatio,
groupRatio,
source: directInput !== undefined || directOutput !== undefined ? "direct" : modelRatio || modelPrice ? "newapi-ratio" : "unknown"
};
}
function normalizeModels(site, payload) {
const list = extractList(payload, ["models"], looksLikeModel);
return list.map((item) => ({
id: String(item.id || item.model || item.name || item || id("model")),
siteId: site.id,
name: String(item.name || item.id || item.model || item || "未知模型"),
provider: String(item.provider || item.owned_by || item.type || site.type),
group: String(item.group || item.groups?.[0] || item.quota_type || item.category || "default"),
inputPrice: Number(item.inputPrice ?? item.input_price ?? item.prompt_price ?? item.price?.input ?? 0),
outputPrice: Number(item.outputPrice ?? item.output_price ?? item.completion_price ?? item.price?.output ?? 0),
pricing: computeModelPricing(site, item),
enabled: item.enabled !== false
}))
.map((model) => ({
...model,
inputPrice: model.inputPrice || model.pricing.inputPer1KUsd,
outputPrice: model.outputPrice || model.pricing.outputPer1KUsd
}))
.filter((item, index, array) => item.name && array.findIndex((candidate) => candidate.name === item.name) === index)
.sort((a, b) => {
const ap = Number(a.pricing?.blendedPer1KUsd || 0) || Number.MAX_SAFE_INTEGER;
const bp = Number(b.pricing?.blendedPer1KUsd || 0) || Number.MAX_SAFE_INTEGER;
return ap - bp || a.name.localeCompare(b.name);
});
}
function normalizeKeys(site, payload) {
const list = extractList(payload, ["tokens", "keys"], looksLikeKey);
return list.map((item) => ({
id: String(item.id || item.key_id || item.token_id || item.name || id("key")),
siteId: site.id,
name: String(item.name || item.key_name || item.token_name || "未命名 Key"),
maskedKey: item.maskedKey || item.masked_key || item.key_preview || mask(item.key || item.token || item.value || item.api_key || item.access_token || ""),
status: item.status || (item.deleted ? "disabled" : "active"),
quota: Number(item.quota ?? item.remain_quota ?? item.unlimited_quota ?? item.limit ?? item.max_usage ?? 0),
used: Number(item.used ?? item.used_quota ?? item.usage ?? item.used_amount ?? 0),
group: String(item.group || item.access_group || item.group_name || "default"),
expiresAt: item.expiresAt || item.expired_time || item.expires_at || item.expire_at || item.expires || null,
createdAt: item.createdAt || item.created_at || null
}));
}
function normalizeUsage(site, payload) {
return normalizeUsageFromRoute(site, payload, "");
}
function quotaToUsd(value) {
const n = Number(value || 0);
return Number.isFinite(n) ? n / NEW_API_QUOTA_PER_USD : 0;
}
function normalizeNewApiUsage(site, values) {
const balanceQuota = Number(values.balance || 0);
const usedTodayQuota = Number(values.usedToday || 0);
const usedTotalQuota = Number(values.usedTotal || 0);
return {
siteId: site.id,
balance: quotaToUsd(balanceQuota),
usedToday: quotaToUsd(usedTodayQuota),
usedTotal: quotaToUsd(usedTotalQuota),
requestCountToday: Number(values.requestCountToday || 0),
promptTokensToday: Number(values.promptTokensToday || 0),
completionTokensToday: Number(values.completionTokensToday || 0),
totalTokensToday: Number(values.totalTokensToday || 0),
unit: "usd",
rawQuota: {
balance: balanceQuota,
usedToday: usedTodayQuota,
usedTotal: usedTotalQuota
}
};
}
function normalizeUsageFromRoute(site, payload, route = "") {
const data = isPlainObject(payload?.data) ? payload.data : {};
if (route.includes("/api/log/self/stat")) {
const statUsage = {
siteId: site.id,
balance: 0,
usedToday: Number(payload?.quota ?? data.quota ?? 0),
usedTotal: 0,
requestCountToday: Number(payload?.count ?? payload?.request_count ?? data.count ?? data.request_count ?? 0)
};
return site.type === "newapi" ? normalizeNewApiUsage(site, statUsage) : statUsage;
}
const usage = {
siteId: site.id,
balance: Number(payload?.balance ?? payload?.quota ?? payload?.remain_quota ?? payload?.remaining ?? payload?.credit ?? data.balance ?? data.quota ?? data.remain_quota ?? data.remaining ?? data.credit ?? 0),
usedToday: Number(payload?.usedToday ?? payload?.today_used ?? payload?.today_usage ?? payload?.today_quota_consumption ?? payload?.total_actual_cost ?? payload?.total_cost ?? data.usedToday ?? data.today_used ?? data.today_usage ?? data.today_quota_consumption ?? data.total_actual_cost ?? data.total_cost ?? 0),
usedTotal: Number(payload?.usedTotal ?? payload?.used_quota ?? payload?.used ?? payload?.total_used ?? payload?.total_usage ?? payload?.total_actual_cost ?? payload?.total_cost ?? data.usedTotal ?? data.used_quota ?? data.used ?? data.total_used ?? data.total_usage ?? data.total_actual_cost ?? data.total_cost ?? 0),
requestCountToday: Number(payload?.requestCountToday ?? payload?.today_requests ?? payload?.today_requests_count ?? payload?.total_requests ?? payload?.request_count ?? data.requestCountToday ?? data.today_requests ?? data.today_requests_count ?? data.total_requests ?? data.request_count ?? 0),
promptTokensToday: Number(payload?.promptTokensToday ?? payload?.prompt_tokens ?? payload?.input_tokens ?? payload?.today_prompt_tokens ?? payload?.today_input_tokens ?? payload?.total_input_tokens ?? data.promptTokensToday ?? data.prompt_tokens ?? data.input_tokens ?? data.today_prompt_tokens ?? data.today_input_tokens ?? data.total_input_tokens ?? 0),
completionTokensToday: Number(payload?.completionTokensToday ?? payload?.completion_tokens ?? payload?.output_tokens ?? payload?.today_completion_tokens ?? payload?.today_output_tokens ?? payload?.total_output_tokens ?? data.completionTokensToday ?? data.completion_tokens ?? data.output_tokens ?? data.today_completion_tokens ?? data.today_output_tokens ?? data.total_output_tokens ?? 0),
totalTokensToday: Number(payload?.totalTokensToday ?? payload?.total_tokens ?? payload?.today_tokens ?? data.totalTokensToday ?? data.total_tokens ?? data.today_tokens ?? 0)
};
return site.type === "newapi" ? normalizeNewApiUsage(site, usage) : usage;
}
function mergeUsage(base, extra) {
const promptTokensToday = Number(extra?.promptTokensToday || base.promptTokensToday || 0);
const completionTokensToday = Number(extra?.completionTokensToday || base.completionTokensToday || 0);
return {
siteId: base.siteId,
balance: Number(base.balance || 0),
usedToday: Number(extra?.usedToday || base.usedToday || 0),
usedTotal: Number(base.usedTotal || extra?.usedTotal || 0),
requestCountToday: Number(extra?.requestCountToday || base.requestCountToday || 0),
promptTokensToday,
completionTokensToday,
totalTokensToday: Number(extra?.totalTokensToday || base.totalTokensToday || (promptTokensToday + completionTokensToday)),
unit: base.unit || extra?.unit,
rawQuota: {
balance: Number(base.rawQuota?.balance || 0),
usedToday: Number(extra?.rawQuota?.usedToday || base.rawQuota?.usedToday || 0),
usedTotal: Number(base.rawQuota?.usedTotal || extra?.rawQuota?.usedTotal || 0)
}
};
}
function todayRangeSeconds() {
const start = new Date();
start.setHours(0, 0, 0, 0);
const end = new Date();
end.setHours(23, 59, 59, 999);
return {
start: Math.floor(start.getTime() / 1000),
end: Math.floor(end.getTime() / 1000)
};
}
function todayLogStatRoute() {
const { start, end } = todayRangeSeconds();
const params = new URLSearchParams({
p: "1",
page_size: "20",
token_name: "",
model_name: "",
start_timestamp: String(start),
end_timestamp: String(end),
type: "2",
group: ""
});
return `/api/log/self/stat?${params.toString()}`;
}
function usageLogRoute(page = 1, pageSize = 50) {
const { start, end } = todayRangeSeconds();
const params = new URLSearchParams({
p: String(page),
page_size: String(pageSize),
token_name: "",
model_name: "",
start_timestamp: String(start),
end_timestamp: String(end),
type: "2",
group: ""
});
return `/api/log/self?${params.toString()}`;
}
function summarizeUsageLogs(site, logsResult) {
const promptTokensToday = logsResult.logs.reduce((sum, log) => sum + Number(log.promptTokens || 0), 0);
const completionTokensToday = logsResult.logs.reduce((sum, log) => sum + Number(log.completionTokens || 0), 0);
const fallbackTotalTokensToday = logsResult.logs.reduce((sum, log) => sum + Number(log.totalTokens || 0), 0);
return {
siteId: site.id,
balance: 0,
usedToday: 0,
usedTotal: 0,
requestCountToday: Number(logsResult.total || logsResult.logs.length || 0),
promptTokensToday,
completionTokensToday,
totalTokensToday: promptTokensToday + completionTokensToday || fallbackTotalTokensToday,
unit: site.type === "newapi" ? "usd" : ""
};
}
function normalizeLogTime(value) {
const n = Number(value || 0);
if (!Number.isFinite(n) || n <= 0) return null;
return new Date(n > 100000000000 ? n : n * 1000).toISOString();
}
function normalizeUsageLogs(site, payload) {
const root = isPlainObject(payload?.data) ? payload.data : payload;
const list = extractList(payload, ["items", "logs"], looksLikeLog);
const total = Number(root?.total ?? payload?.total ?? list.length);
return {
total: Number.isFinite(total) ? total : list.length,
logs: list.map((item) => {
const rawQuota = Number(item.quota ?? item.used_quota ?? 0);
return {
id: String(item.id || id("log")),
siteId: site.id,
createdAt: normalizeLogTime(item.created_at || item.createdAt || item.time || item.timestamp || item.created || item.date),
tokenName: String(item.token_name || item.tokenName || item.key_name || item.keyName || item.name || ""),
modelName: String(item.model_name || item.modelName || item.model || ""),
content: payloadMessage({ message: item.content || item.message || "" }),
promptTokens: Number(item.prompt_tokens ?? item.promptTokens ?? item.input_tokens ?? item.inputTokens ?? 0),
completionTokens: Number(item.completion_tokens ?? item.completionTokens ?? item.output_tokens ?? item.outputTokens ?? 0),
totalTokens: Number(item.total_tokens ?? item.totalTokens ?? 0),
quota: site.type === "newapi" ? quotaToUsd(rawQuota) : Number(item.amount ?? item.cost ?? item.usage ?? rawQuota),
unit: site.type === "newapi" ? "usd" : "",
rawQuota
};
})
};
}
async function fetchUsageLogsForSite(site) {
const routes = site.type === "newapi" ? [usageLogRoute()] : routesFor(site, "logs");
try {
const result = await requestSite(site, "GET", routes);
return {
...normalizeUsageLogs(site, result.payload),
sourceRoute: result.route.split("?")[0]
};
} catch (error) {
if (site.type !== "newapi") return { logs: [], total: 0, sourceRoute: "" };
throw error;
}
}
async function fetchUsageLogSummaryForSite(site) {
if (site.type !== "newapi") {
try {
return summarizeUsageLogs(site, await fetchUsageLogsForSite(site));
} catch {
return summarizeUsageLogs(site, { logs: [], total: 0 });
}
}
const pageSize = 100;
const maxPages = 20;
const first = await requestSite(site, "GET", [usageLogRoute(1, pageSize)]);
const firstPage = normalizeUsageLogs(site, first.payload);
const logs = [...firstPage.logs];
const total = Number(firstPage.total || logs.length);
const totalPages = Math.min(maxPages, Math.max(1, Math.ceil(total / pageSize)));
for (let page = 2; page <= totalPages; page++) {
const result = await requestSite(site, "GET", [usageLogRoute(page, pageSize)]);
logs.push(...normalizeUsageLogs(site, result.payload).logs);
}
return summarizeUsageLogs(site, { logs, total });
}
function buildCreateKeyPayload(site, body) {
const quota = Number(body.quota || 0);
const expiredTime = body.expiresAt ? Math.floor(new Date(body.expiresAt).getTime() / 1000) : -1;
const name = body.name || "mobile-key";
const group = body.group || "default";
if (site.type === "sub2api") {
const payload = {
name,
quota,
expires_in_days: expiredTime > 0 ? Math.max(1, Math.ceil((expiredTime - Math.floor(Date.now() / 1000)) / 86400)) : 0,
ip_whitelist: "",
group
};
if (/^\d+$/.test(String(group))) payload.group_id = Number(group);
return { payload, quota, group, expiresAt: body.expiresAt || null };
}
return {
payload: {
name,
remain_quota: quota > 0 ? quota : 0,
expired_time: expiredTime,
unlimited_quota: quota <= 0,
model_limits_enabled: false,
model_limits: "",
allow_ips: "",
group,
token_name: name,
key_name: name,
quota
},
quota,
group,
expiresAt: body.expiresAt || null
};
}
async function exchangeRefreshToken(site, refreshToken) {
if (!refreshToken) return "";
const cacheKey = site.id || site.baseUrl;
const cached = refreshAccessCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now() + 30000) return cached.accessToken;
if (cached && cached.errorUntil > Date.now()) return "";
for (const route of ["/api/v1/auth/refresh", "/auth/refresh"]) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 7000);
try {
const response = await fetch(`${site.baseUrl}${route}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: refreshToken }),
signal: controller.signal
});
const payload = await response.json().catch(() => ({}));
const data = isPlainObject(payload?.data) ? payload.data : payload;
const accessToken = data.access_token || data.accessToken || data.token || "";
if (response.ok && (payload.code === 0 || payload.success !== false) && accessToken) {
const nextRefreshToken = data.refresh_token || data.refreshToken || "";
if (nextRefreshToken && nextRefreshToken !== refreshToken && site.id) {
try {
const store = await readStore();
const index = store.sites.findIndex((item) => item.id === site.id);
if (index >= 0) {
store.sites[index].secrets = {
...(store.sites[index].secrets || {}),
refreshToken: await encryptSecret(nextRefreshToken)
};
store.sites[index].maskedCredential = mask(nextRefreshToken);
store.sites[index].updatedAt = nowIso();
await writeStore(store);
}
} catch {
// Refresh-token rotation is useful but must not block the current request.
}
}
const expiresIn = Number(data.expires_in || data.expiresIn || 900);
refreshAccessCache.set(cacheKey, {
accessToken,
expiresAt: Date.now() + Math.max(60, expiresIn - 30) * 1000
});
return accessToken;
}
if (response.status === 429) {
refreshAccessCache.set(cacheKey, { accessToken: "", expiresAt: 0, errorUntil: Date.now() + 120000 });
return "";
}
} catch {
// Try the next compatible refresh route.
} finally {
clearTimeout(timer);
}
}
refreshAccessCache.set(cacheKey, { accessToken: "", expiresAt: 0, errorUntil: Date.now() + 45000 });
return "";
}
async function adapterHeaders(site) {
const headers = { "Content-Type": "application/json" };
if (site.type === "newapi") {
const token = await decryptSecret(site.secrets?.systemToken);
if (!token) throw new HttpError(400, "New API 系统 Token 未配置");
if (!site.userId) throw new HttpError(400, "New API 用户 ID 未配置");
if (token) headers.Authorization = `Bearer ${token}`;
for (const header of NEW_API_USER_ID_HEADERS) headers[header] = site.userId;
} else {
const jwt = await decryptSecret(site.secrets?.jwt);
const apiKey = await decryptSecret(site.secrets?.apiKey);
const adminToken = await decryptSecret(site.secrets?.adminToken);
const sessionCookie = await decryptSecret(site.secrets?.sessionCookie);
const refreshToken = await decryptSecret(site.secrets?.refreshToken);
if (!jwt && !apiKey && !adminToken && !sessionCookie && !refreshToken) throw new HttpError(400, "Sub2API JWT、API Key 或 Admin Token 至少需要配置一个");
const refreshedAccessToken = refreshToken ? await exchangeRefreshToken(site, refreshToken) : "";
if (jwt) headers.Authorization = `Bearer ${jwt}`;
else if (refreshedAccessToken) headers.Authorization = `Bearer ${refreshedAccessToken}`;
else if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
else if (refreshToken) headers.Authorization = `Bearer ${refreshToken}`;
if (apiKey) headers["X-API-Key"] = apiKey;
if (sessionCookie) headers.Cookie = sessionCookie;
if (refreshToken) {
headers["X-Refresh-Token"] = refreshToken;
headers["Refresh-Token"] = refreshToken;
headers.refresh_token = refreshToken;
}
if (adminToken) {
headers["X-Admin-Token"] = adminToken;
headers["New-API-Admin"] = adminToken;
headers["Authorization-Admin"] = adminToken;
}
}
return headers;
}
async function requestSite(site, method, paths, body) {
const headers = await adapterHeaders(site);
const errors = [];
for (const route of paths) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 9000);
try {
const response = await fetch(`${site.baseUrl}${route}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
signal: controller.signal
});
const text = await response.text();
let payload = {};
let parsedJson = false;
try {
payload = text ? JSON.parse(text) : {};
parsedJson = true;
} catch {
payload = { message: text };
}
if (response.ok) {
if (text && !parsedJson) {
errors.push(`${route}: HTTP ${response.status} returned non-JSON response`);
continue;
}
if (payload && typeof payload === "object" && payload.success === false) {
const message = payloadMessage(payload);
errors.push(`${route}: ${message || `HTTP ${response.status} returned success=false`}`);
continue;
}
if (method !== "GET" && payload && typeof payload === "object" && payload.success === true) {
return { route, payload, status: response.status };
}
if (!payloadHasUsefulData(payload)) {
const message = payloadMessage(payload);
errors.push(`${route}: HTTP ${response.status} returned no usable data${message ? ` (${message})` : ""}`);
continue;
}
return { route, payload, status: response.status };
}
errors.push(`${route}: HTTP ${response.status}`);
} catch (error) {
errors.push(`${route}: ${error.name === "AbortError" ? "请求超时" : error.message}`);
} finally {
clearTimeout(timer);
}
}
throw new HttpError(502, "远端站点请求失败", errors.slice(0, 3));
}
function transientHeaders(input, type) {
const headers = { "Content-Type": "application/json" };
if (type === "newapi") {
if (input.systemToken) headers.Authorization = `Bearer ${input.systemToken}`;
if (input.userId) {
for (const header of NEW_API_USER_ID_HEADERS) headers[header] = String(input.userId);
}
} else {
if (input.jwt) headers.Authorization = `Bearer ${input.jwt}`;
else if (input.apiKey) headers.Authorization = `Bearer ${input.apiKey}`;
else if (input.refreshToken) headers.Authorization = `Bearer ${input.refreshToken}`;
if (input.apiKey) headers["X-API-Key"] = input.apiKey;
if (input.sessionCookie) headers.Cookie = input.sessionCookie;
if (input.refreshToken) {
headers["X-Refresh-Token"] = input.refreshToken;
headers["Refresh-Token"] = input.refreshToken;
headers.refresh_token = input.refreshToken;
}
if (input.adminToken) {
headers["X-Admin-Token"] = input.adminToken;
headers["New-API-Admin"] = input.adminToken;
headers["Authorization-Admin"] = input.adminToken;
}
}
return headers;
}
async function probeBaseRoute(baseUrl, route, headers = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 7000);
try {
const response = await fetch(`${baseUrl}${route}`, {
method: "GET",
headers,
signal: controller.signal
});
const contentType = response.headers.get("content-type") || "";
const text = await response.text();
let payload = {};
try {
payload = text ? JSON.parse(text) : {};
} catch {
payload = { message: text };
}
return {
route,
ok: response.ok && payload?.success !== false,
status: response.status,
contentType,
body: describePayload(payload),
payload
};
} catch (error) {
return {
route,
ok: false,
status: null,
error: error.name === "AbortError" ? "timeout" : error.message
};
} finally {
clearTimeout(timer);
}
}
function extractUserId(payload) {
const data = isPlainObject(payload?.data) ? payload.data : payload;
return String(firstDefined(data?.id, data?.user_id, data?.userId, data?.user?.id, payload?.id, "") || "");
}
async function detectSite(input) {
const baseUrl = cleanBaseUrl(input.baseUrl || "");
const candidates = [
{
type: "newapi",
authType: "system-token",
routes: ["/api/user/self", "/api/token/?p=0&size=1", "/api/user/models", "/api/status"],
headers: transientHeaders(input, "newapi")
},
{
type: "sub2api",
authType: input.jwt ? "jwt" : input.adminToken ? "admin-token" : input.sessionCookie ? "cookie" : input.refreshToken ? "refresh-token" : "api-key",
routes: ["/api/v1/auth/me", "/api/v1/keys?page=1&size=1", "/api/status", "/v1/models"],
headers: transientHeaders(input, "sub2api")
}
];
const results = [];
for (const candidate of candidates) {
const probes = [];