-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.js
More file actions
2216 lines (1992 loc) · 81.7 KB
/
Copy pathserver.js
File metadata and controls
2216 lines (1992 loc) · 81.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
const http = require("node:http");
const { URL } = require("node:url");
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const path = require("node:path");
const crypto = require("node:crypto");
const { Readable } = require("node:stream");
function isEnvOn(name) {
return /^(1|true|yes|on)$/i.test(String(process.env[name] || ""));
}
const CONFIG = {
port: Number(process.env.PORT || 8787),
host: process.env.HOST || "0.0.0.0",
apiKey: process.env.API_KEY || "change-me",
dataDir: process.env.DATA_DIR || path.join(__dirname, "data"),
accountsFile: process.env.ACCOUNTS_FILE || path.join(__dirname, "data", "accounts.json"),
maxRequestBodyBytes: Number(process.env.MAX_REQUEST_BODY_BYTES || 20 * 1024 * 1024),
maxUploadBytes: Number(process.env.MAX_UPLOAD_BYTES || 25 * 1024 * 1024),
// 图片上传后是否等待 file_processing_queue 入库完成;默认不等待(0),更贴近官方前端的“异步处理 + 轮询状态”体验
// 经过多次测试推荐20s,设为默认
imageProcessingWaitMs: Number(process.env.IMAGE_PROCESSING_WAIT_MS || 20 * 1000),
imageProcessingPollIntervalMs: Number(process.env.IMAGE_PROCESSING_POLL_INTERVAL_MS || 750),
supabaseBase: "https://db.zerotwo.ai",
// 你确认这是“公开 anon key”,可写死;如需替换,可用环境变量覆盖。
supabaseAnonKey:
process.env.SUPABASE_ANON_KEY ||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpkYmNldmpicWFveHJ4eHdxd3V4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgyNDcyMzUsImV4cCI6MjA3MzgyMzIzNX0.UcUJUjMocwijFTtYFKYuTgIODYWc4uxDByu2tI6XGQg",
zerotwoApiBase: process.env.ZEROTWO_API_BASE || "https://api.zerotwo.ai",
zerotwoOrigin: process.env.ZEROTWO_ORIGIN || "https://app.zerotwo.ai",
// 高并发下抖动控制:提前刷新 + 单飞互斥 + 熔断退避
accessRefreshLeewayMs: 20 * 60 * 1000,
csrfRefreshLeewayMs: 60 * 60 * 1000,
// 当触发“authentication rate limit”时,Security 刷新冷却时间(避免 20s 频率加重限流)
auth429SecurityCooldownMs: 10 * 60 * 1000,
auth429SecurityCooldownJitterMinMs: 5 * 1000,
auth429SecurityCooldownJitterMaxMs: 30 * 1000,
backgroundTickMs: 20 * 1000,
// 后台刷新节流:每轮最多处理 4 个账号、并发最多 2
backgroundGroupSize: 4,
backgroundMaxConcurrent: 2,
// 账号级并发上限(可在网页里对单账号覆盖)
defaultMaxInflightPerAccount: 8,
// 请求超时
httpTimeoutMs: 60 * 1000,
// Debug 开关(默认关闭)
debugMode: isEnvOn("DEBUG_MODE") || isEnvOn("DEBUG_RAW_STREAM"),
debugRawStream: isEnvOn("DEBUG_RAW_STREAM") || isEnvOn("DEBUG_MODE"),
debugLogMaxChars: Number(process.env.DEBUG_LOG_MAX_CHARS || 4000)
};
const ANTHROPIC_THINKING_BUDGETS = [1024, 4096, 10000, 16000];
const IMAGE_MODEL_IDS = [
"gpt-image-1.5",
"gpt-image-1",
"gpt-image-1-mini",
"imagen-4.0-generate-preview-06-06",
"nano-banana-pro"
];
const IMAGE_EDIT_MODEL_IDS = IMAGE_MODEL_IDS;
const DEFAULT_IMAGE_MODEL_ON_IMPORT = "nano-banana-pro";
function nowMs() {
return Date.now();
}
function clipForLog(value, maxChars = CONFIG.debugLogMaxChars) {
let s = "";
if (typeof value === "string") s = value;
else {
try {
s = JSON.stringify(value);
} catch (e) {
s = String(value ?? e ?? "");
}
}
if (!s) return "";
const limit = Number(maxChars || 0);
if (!Number.isFinite(limit) || limit <= 0) return s;
if (s.length <= limit) return s;
return `${s.slice(0, limit)}...<truncated ${s.length - limit} chars>`;
}
function debugLog(tag, payload) {
if (!CONFIG.debugMode) return;
const ts = new Date().toISOString();
if (payload === undefined) {
console.log(`[debug][${ts}][${tag}]`);
return;
}
const line = typeof payload === "string" ? payload : JSON.stringify(payload);
console.log(`[debug][${ts}][${tag}] ${clipForLog(line)}`);
}
function sha256Base64Url(input) {
return crypto.createHash("sha256").update(input).digest("base64url");
}
function randIntInclusive(min, max) {
const a = Math.ceil(Number(min));
const b = Math.floor(Number(max));
if (!Number.isFinite(a) || !Number.isFinite(b)) return 0;
if (b <= a) return a;
return a + Math.floor(Math.random() * (b - a + 1));
}
function safeJsonParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (e) {
return { ok: false, error: String(e) };
}
}
function parseJwtPayload(token) {
const t = typeof token === "string" ? token.trim() : "";
if (!t) return null;
const parts = t.split(".");
if (parts.length < 2) return null;
try {
const json = Buffer.from(parts[1], "base64url").toString("utf8");
const parsed = safeJsonParse(json);
return parsed.ok ? parsed.value : null;
} catch {
return null;
}
}
function csrfCookieFromSecurity(security) {
const rawCookie = typeof security?.csrfCookie === "string" ? security.csrfCookie.trim() : "";
if (rawCookie) return rawCookie;
const token = typeof security?.csrfToken === "string" ? security.csrfToken.trim() : "";
return token ? `__csrf=${token}` : "";
}
function extractCsrfCookieFromSetCookie(rawSetCookie) {
const raw = typeof rawSetCookie === "string" ? rawSetCookie : "";
if (!raw) return "";
const m = raw.match(/(?:^|,\s*)__csrf=([^;,\s]+)/);
return m ? `__csrf=${m[1]}` : "";
}
function extractCsrfCookieFromHeaders(headers) {
if (!headers) return "";
if (typeof headers.getSetCookie === "function") {
const setCookies = headers.getSetCookie();
if (Array.isArray(setCookies)) {
for (const item of setCookies) {
const cookie = extractCsrfCookieFromSetCookie(item);
if (cookie) return cookie;
}
}
}
if (typeof headers.get === "function") {
return extractCsrfCookieFromSetCookie(headers.get("set-cookie") || "");
}
return "";
}
function randomId(prefix) {
return `${prefix}_${crypto.randomBytes(12).toString("hex")}`;
}
function normalizeProviderName(provider) {
const p = String(provider || "").trim();
if (!p) return "openai";
const lower = p.toLowerCase();
// 兼容用户口误
if (lower === "authropic") return "anthropic";
return lower;
}
function parseProviderModelFromOpenAIRequest(openaiReq) {
const requestedModelRaw = typeof openaiReq?.model === "string" ? openaiReq.model.trim() : "";
let provider = typeof openaiReq?.provider === "string" ? openaiReq.provider.trim() : "openai";
let model = requestedModelRaw || "gpt-5.2";
if (requestedModelRaw.includes("/")) {
const [p, ...rest] = requestedModelRaw.split("/");
// 只取第一个分段作为 provider,其余原样拼回作为 model
if (p) provider = p;
if (rest.length) model = rest.join("/");
}
provider = normalizeProviderName(provider);
return { provider, model };
}
function extractTextFromMessageContent(content) {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
let text = "";
for (const part of content) {
if (!part || typeof part !== "object") continue;
const type = String(part.type || "").toLowerCase();
if (type === "text" || type === "input_text") {
const t = typeof part.text === "string" ? part.text : typeof part.content === "string" ? part.content : "";
if (t) text += (text ? "\n" : "") + t;
continue;
}
}
return text;
}
function nearestAllowedNumber(value, allowed) {
const v = Number(value);
if (!Number.isFinite(v)) return null;
let best = allowed[0];
let bestDiff = Math.abs(v - best);
for (const a of allowed) {
const diff = Math.abs(v - a);
if (diff < bestDiff) {
best = a;
bestDiff = diff;
}
}
return best;
}
function budgetFromReasoningEffort(effort) {
const e = String(effort ?? "").toLowerCase();
if (e === "none" || e === "off" || e === "disabled") return null;
if (e === "low" || e === "minimal") return 1024;
if (e === "medium") return 4096;
return 16000; // high / 默认
}
function normalizeAnthropicReasoningEffort(value) {
if (value === null || value === undefined) return 16000;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) return "off";
return nearestAllowedNumber(value, ANTHROPIC_THINKING_BUDGETS) || 16000;
}
if (typeof value === "string") {
const s = value.trim();
const lower = s.toLowerCase();
if (!lower) return 16000;
if (lower === "off" || lower === "none" || lower === "disabled") return "off";
// 允许用户用字符串直接写预算数字:例如 "4096"
if (/^\d+$/.test(lower)) {
const n = Number(lower);
if (!Number.isFinite(n) || n <= 0) return "off";
return nearestAllowedNumber(n, ANTHROPIC_THINKING_BUDGETS) || 16000;
}
const mapped = budgetFromReasoningEffort(lower);
if (!mapped) return "off";
return nearestAllowedNumber(mapped, ANTHROPIC_THINKING_BUDGETS) || 16000;
}
return 16000;
}
function normalizeAnthropicThinkingToReasoningEffort(inputThinking, fallbackEffort) {
const raw = inputThinking && typeof inputThinking === "object" ? inputThinking : null;
const rawType = raw?.type;
const type = typeof rawType === "string" ? rawType.toLowerCase() : "";
if (type === "off" || type === "disabled" || type === "none") {
return "off";
}
const requestedBudget = raw?.budget_tokens ?? raw?.budgetTokens;
return normalizeAnthropicReasoningEffort(requestedBudget ?? fallbackEffort);
}
function requireApiKey(req) {
const headerKey = req.headers["x-api-key"];
if (typeof headerKey === "string" && headerKey === CONFIG.apiKey) return true;
const auth = req.headers.authorization;
if (typeof auth === "string" && auth.startsWith("Bearer ")) {
const token = auth.slice("Bearer ".length).trim();
if (token === CONFIG.apiKey) return true;
}
return false;
}
async function supabaseRestJson(account, pathAndQuery, { method, body, headers } = {}) {
const url = `${CONFIG.supabaseBase}${pathAndQuery}`;
const doOnce = async () => {
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), CONFIG.httpTimeoutMs);
try {
const res = await fetch(url, {
method: method || "GET",
headers: {
accept: "application/json",
apikey: CONFIG.supabaseAnonKey,
authorization: `Bearer ${account.accessToken}`,
"content-type": "application/json",
...(headers || {})
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: ac.signal
});
const text = await res.text();
const parsed = safeJsonParse(text);
return { ok: res.ok, status: res.status, json: parsed.ok ? parsed.value : null, text };
} finally {
clearTimeout(t);
}
};
let r = await doOnce();
if (r.status === 401 || r.status === 403) {
await refreshSupabaseSession(account);
r = await doOnce();
}
if (!r.ok) throw new Error(`Supabase REST 失败: ${r.status} ${r.text.slice(0, 200)}`);
return r.json;
}
async function supabasePublicJson(account, pathAndQuery, { method, body, headers } = {}) {
return await supabaseRestJson(account, pathAndQuery, {
method,
body,
headers: {
"content-profile": "public",
"accept-profile": "public",
...(headers || {})
}
});
}
function sendJson(res, statusCode, body) {
const payload = JSON.stringify(body);
res.writeHead(statusCode, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(payload)
});
res.end(payload);
}
function sendText(res, statusCode, text, headers = {}) {
res.writeHead(statusCode, {
"content-type": "text/plain; charset=utf-8",
...headers
});
res.end(text);
}
async function readBody(req, limitBytes = 2 * 1024 * 1024) {
return new Promise((resolve, reject) => {
let total = 0;
const chunks = [];
req.on("data", (c) => {
total += c.length;
if (total > limitBytes) {
reject(new Error("请求体过大"));
req.destroy();
return;
}
chunks.push(c);
});
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
}
function parseDataUrl(dataUrl) {
const raw = typeof dataUrl === "string" ? dataUrl : "";
if (!raw.startsWith("data:")) return null;
const m = raw.match(/^data:([^;,]+)?(;base64)?,([\s\S]*)$/);
if (!m) return null;
const contentType = (m[1] || "application/octet-stream").trim();
const isBase64 = Boolean(m[2]);
const payload = m[3] || "";
try {
const buf = isBase64 ? Buffer.from(payload, "base64") : Buffer.from(decodeURIComponent(payload), "utf8");
return { contentType, buffer: buf };
} catch {
return null;
}
}
function extFromContentType(contentType) {
const ct = String(contentType || "").toLowerCase();
if (ct === "image/png") return ".png";
if (ct === "image/jpeg") return ".jpg";
if (ct === "image/webp") return ".webp";
if (ct === "image/gif") return ".gif";
return "";
}
function sanitizeFilename(name) {
const raw = String(name || "").trim() || "upload";
const safe = raw.replace(/[^\w.\-]+/g, "_").slice(0, 120);
return safe || "upload";
}
function extractImageUrlsFromMessageContent(content) {
if (!Array.isArray(content)) return [];
const out = [];
for (const part of content) {
if (!part || typeof part !== "object") continue;
const type = String(part.type || "").toLowerCase();
if (type !== "image_url" && type !== "input_image" && type !== "image") continue;
const candidate =
(typeof part.image_url === "string" ? part.image_url : "") ||
(typeof part.url === "string" ? part.url : "") ||
(typeof part.image === "string" ? part.image : "") ||
(typeof part.image_url?.url === "string" ? part.image_url.url : "") ||
(typeof part.image_url?.uri === "string" ? part.image_url.uri : "") ||
(typeof part.image?.url === "string" ? part.image.url : "") ||
"";
const url = candidate.trim();
if (url) out.push(url);
}
return out;
}
function extractImageUrlsFromOpenAIRequest(openaiReq) {
const msgs = Array.isArray(openaiReq?.messages) ? openaiReq.messages : [];
const out = [];
for (const m of msgs) {
if (!m || typeof m !== "object") continue;
out.push(...extractImageUrlsFromMessageContent(m.content));
}
return out;
}
function createBadAttachmentsError(message) {
const err = new Error(message);
err.code = "BAD_ATTACHMENTS";
return err;
}
function createBadImageModelError(message) {
const err = new Error(message);
err.code = "BAD_IMAGE_MODEL";
return err;
}
async function fetchBuffer(url, { timeoutMs, maxBytes } = {}) {
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), Number(timeoutMs || CONFIG.httpTimeoutMs));
try {
const res = await fetch(url, { method: "GET", signal: ac.signal });
if (!res.ok) throw new Error(`下载失败: ${res.status}`);
const ab = await res.arrayBuffer();
const buf = Buffer.from(ab);
const limit = Number(maxBytes || 0) || 0;
if (limit > 0 && buf.length > limit) throw new Error("文件过大");
const ct = res.headers.get("content-type") || "";
return { buffer: buf, contentType: ct };
} finally {
clearTimeout(t);
}
}
async function resolveImageToUploadBytes(imageUrl) {
const url = typeof imageUrl === "string" ? imageUrl.trim() : "";
if (!url) throw createBadAttachmentsError("图片 URL 为空");
const parsed = parseDataUrl(url);
if (parsed) {
if (parsed.buffer.length > CONFIG.maxUploadBytes) throw createBadAttachmentsError("图片过大");
return { buffer: parsed.buffer, contentType: parsed.contentType || "application/octet-stream" };
}
// 允许 http(s) 外链:用于 image_url.url = https://...
if (!/^https?:\/\//i.test(url)) {
throw createBadAttachmentsError("仅支持 data: 或 http(s) 图片 URL");
}
try {
const r = await fetchBuffer(url, { timeoutMs: CONFIG.httpTimeoutMs, maxBytes: CONFIG.maxUploadBytes });
return { buffer: r.buffer, contentType: r.contentType || "application/octet-stream" };
} catch (e) {
throw createBadAttachmentsError(`图片下载失败: ${String(e?.message || e)}`);
}
}
async function ensureThreadExists(account, threadId, { provider } = {}) {
const sel = encodeURIComponent("id,vector_store_id,rag_enabled");
const arr = await supabasePublicJson(account, `/rest/v1/threads?id=eq.${threadId}&select=${sel}`, { method: "GET" });
const row = Array.isArray(arr) ? arr[0] : null;
if (row?.id) return row;
const nowIso = new Date().toISOString();
// 对齐官方前端:创建 thread 记录,避免后续 vector store / upload 依赖 thread 不存在。
const created = await supabasePublicJson(account, "/rest/v1/threads?select=*", {
method: "POST",
headers: {
accept: "application/vnd.pgrst.object+json",
prefer: "return=representation"
},
body: {
id: threadId,
title: "New Chat",
user_id: account.userId || account.id,
project_id: null,
metadata: { project_id: null, needs_title_generation: false },
created_at: nowIso,
updated_at: nowIso,
last_activity: nowIso,
provider: normalizeProviderName(provider || "openai"),
is_team: false,
is_shared: false
}
});
return created || { id: threadId, vector_store_id: null, rag_enabled: false };
}
async function ensureThreadVectorStore(account, threadId, { provider } = {}) {
const row = await ensureThreadExists(account, threadId, { provider });
const existing = typeof row?.vector_store_id === "string" ? row.vector_store_id : "";
if (existing) return existing;
const userId = account.userId || account.id;
const rpcRes = await supabasePublicJson(account, "/rest/v1/rpc/create_vector_store", {
method: "POST",
body: {
p_user_id: userId,
p_thread_id: threadId,
p_project_id: null,
p_name: `Thread: ${String(row?.title || "New Chat")}`,
p_description: `Vector store for thread ${threadId}`
}
});
const first = Array.isArray(rpcRes) ? rpcRes[0] : null;
const vectorStoreId = typeof first?.id === "string" ? first.id : "";
if (!vectorStoreId) throw new Error("create_vector_store 未返回 vectorStoreId");
await supabasePublicJson(account, `/rest/v1/threads?id=eq.${threadId}`, {
method: "PATCH",
headers: {
// 不强依赖返回值:与官方行为一致
prefer: "return=minimal"
},
body: { vector_store_id: vectorStoreId, rag_enabled: true }
});
return vectorStoreId;
}
async function getSupabaseAuthUser(account) {
const url = `${CONFIG.supabaseBase}/auth/v1/user`;
const doOnce = async () => {
return await fetchJson(url, {
method: "GET",
headers: {
accept: "*/*",
apikey: CONFIG.supabaseAnonKey,
authorization: `Bearer ${account.accessToken}`
}
});
};
let res = await doOnce();
if (res.status === 401 || res.status === 403) {
await refreshSupabaseSession(account);
res = await doOnce();
}
if (!res.ok) throw createUpstreamHttpError("Supabase user 获取失败", res);
return res.json || null;
}
async function resolveProfileUserId(account, userId) {
const current = String(userId || account.userId || "").trim();
const authUser = await getSupabaseAuthUser(account);
const resolved = String(authUser?.id || current).trim();
if (!resolved) throw new Error("缺少 userId");
if (account.userId !== resolved) {
account.userId = resolved;
await store.save();
}
return resolved;
}
async function getProfileSettings(account, userId, { resolvedUserId } = {}) {
const uid = String(resolvedUserId || "").trim() || (await resolveProfileUserId(account, userId));
return await supabasePublicJson(account, `/rest/v1/profiles?select=settings&id=eq.${uid}`, {
method: "GET",
headers: { accept: "application/vnd.pgrst.object+json" }
});
}
function cloneJsonValue(value) {
if (value === null || value === undefined) return value;
if (typeof structuredClone === "function") return structuredClone(value);
return JSON.parse(JSON.stringify(value));
}
async function patchProfileSettings(account, userId, updateSettings) {
const uid = await resolveProfileUserId(account, userId);
const existing = await getProfileSettings(account, uid, { resolvedUserId: uid });
const settings = existing?.settings && typeof existing.settings === "object" ? existing.settings : {};
const nextSettings = cloneJsonValue(settings) || {};
updateSettings(nextSettings);
return await supabasePublicJson(account, `/rest/v1/profiles?id=eq.${uid}&select=settings`, {
method: "PATCH",
headers: {
accept: "application/vnd.pgrst.object+json",
prefer: "return=representation"
},
body: { settings: nextSettings, updated_at: new Date().toISOString() }
});
}
async function setProfileImageModel(account, userId, imageModel) {
const raw = typeof imageModel === "string" ? imageModel.trim() : "";
if (raw && !IMAGE_MODEL_IDS.includes(raw)) {
throw createBadImageModelError(`不支持的图像模型:${raw}`);
}
return await patchProfileSettings(account, userId, (nextSettings) => {
if (!nextSettings.preferences || typeof nextSettings.preferences !== "object") nextSettings.preferences = {};
if (!raw) {
delete nextSettings.preferences.image_model;
} else {
nextSettings.preferences.image_model = raw;
}
});
}
async function setProfileImageEditModel(account, userId, imageEditModel) {
const raw = typeof imageEditModel === "string" ? imageEditModel.trim() : "";
if (raw && !IMAGE_EDIT_MODEL_IDS.includes(raw)) {
throw createBadImageModelError(`不支持的图像编辑模型:${raw}`);
}
return await patchProfileSettings(account, userId, (nextSettings) => {
if (!nextSettings.preferences || typeof nextSettings.preferences !== "object") nextSettings.preferences = {};
if (!raw) {
delete nextSettings.preferences.image_edit_model;
} else {
nextSettings.preferences.image_edit_model = raw;
}
});
}
async function setProfileMemoryEnabled(account, userId, enabled) {
const nextEnabled = Boolean(enabled);
return await patchProfileSettings(account, userId, (nextSettings) => {
if (!nextSettings.personalization || typeof nextSettings.personalization !== "object") {
nextSettings.personalization = {};
}
nextSettings.personalization.enable_memories = nextEnabled;
});
}
async function setProfileDefaultsOnImport(account, userId) {
return await patchProfileSettings(account, userId, (nextSettings) => {
if (!nextSettings.preferences || typeof nextSettings.preferences !== "object") nextSettings.preferences = {};
nextSettings.preferences.image_model = DEFAULT_IMAGE_MODEL_ON_IMPORT;
nextSettings.preferences.image_edit_model = DEFAULT_IMAGE_MODEL_ON_IMPORT;
if (!nextSettings.personalization || typeof nextSettings.personalization !== "object") {
nextSettings.personalization = {};
}
nextSettings.personalization.enable_memories = false;
});
}
function extractProfileSettingsSnapshot(row) {
const imageModel =
typeof row?.settings?.preferences?.image_model === "string" ? row.settings.preferences.image_model : "";
const imageEditModel =
typeof row?.settings?.preferences?.image_edit_model === "string" ? row.settings.preferences.image_edit_model : "";
const memoryEnabled = row?.settings?.personalization?.enable_memories === true;
return { imageModel, imageEditModel, memoryEnabled };
}
function applyProfileSettingsSnapshotToAccount(account, snapshot) {
const snap = snapshot && typeof snapshot === "object" ? snapshot : {};
account.imageModel = typeof snap.imageModel === "string" ? snap.imageModel : "";
account.imageEditModel = typeof snap.imageEditModel === "string" ? snap.imageEditModel : "";
account.memoryEnabled = snap.memoryEnabled === true;
account.profileSettingsSyncedAtMs = nowMs();
}
async function uploadRagFile(account, { threadId, filename, contentType, buffer, processAsync } = {}) {
if (!buffer || !Buffer.isBuffer(buffer) || buffer.length === 0) throw createBadAttachmentsError("缺少图片文件内容");
if (buffer.length > CONFIG.maxUploadBytes) throw createBadAttachmentsError("图片过大");
const userId = account.userId || account.id;
const safeName = sanitizeFilename(filename || `upload${extFromContentType(contentType) || ".bin"}`);
const ct = String(contentType || "application/octet-stream");
const form = new FormData();
form.append("file", new Blob([buffer], { type: ct }), safeName);
form.append("filename", safeName);
form.append("contentType", ct);
form.append("userId", userId);
form.append("threadId", threadId);
form.append("attributes", "{}");
form.append("chunkingConfig", "{}");
form.append("processAsync", processAsync === false ? "false" : "true");
const url = `${CONFIG.zerotwoApiBase}/api/rag/upload`;
const res = await fetchJson(url, {
method: "POST",
headers: buildZeroTwoAuthHeaders(account, { includeCsrf: true }),
body: form
});
if (!res.ok) throw createUpstreamHttpError("rag/upload 失败", res);
if (!res.json?.success || !res.json?.data) throw new Error("rag/upload 返回不完整");
return res.json;
}
async function getFileProcessingQueue(account, queueId) {
const sel = encodeURIComponent("status,processing_stage,processed_chunks,total_chunks,error_message");
return await supabasePublicJson(
account,
`/rest/v1/file_processing_queue?select=${sel}&id=eq.${encodeURIComponent(queueId)}`,
{
method: "GET",
headers: { accept: "application/vnd.pgrst.object+json" }
}
);
}
async function waitForFileProcessingCompletion(account, queueId, timeoutMs) {
const deadline = nowMs() + Math.max(0, Number(timeoutMs || 0));
let last = null;
while (nowMs() < deadline) {
const row = await getFileProcessingQueue(account, queueId);
last = row;
const status = String(row?.status || "").toLowerCase();
if (status === "completed" || status === "failed") return row;
await new Promise((r) => setTimeout(r, CONFIG.imageProcessingPollIntervalMs));
}
return last;
}
function buildZeroTwoAttachmentFromUploadData(d) {
const fileId = String(d?.fileId || d?.file_id || d?.id || "");
const name = String(d?.name || "");
return {
id: fileId,
fileId,
file_id: fileId,
name,
type: String(d?.type || d?.contentType || ""),
size: Number(d?.size || 0) || 0,
path: String(d?.path || ""),
publicUrl: String(d?.publicUrl || ""),
storage_path: String(d?.storage_path || d?.path || ""),
vector_store_id: String(d?.vector_store_id || d?.vectorStoreId || ""),
vectorStoreId: String(d?.vectorStoreId || d?.vector_store_id || ""),
threadId: String(d?.threadId || ""),
userId: String(d?.userId || "")
};
}
function parseMultipartFormData(body, contentTypeHeader) {
const ct = String(contentTypeHeader || "");
const m = ct.match(/boundary=([^;]+)/i);
const boundary = m ? m[1].trim().replace(/^"|"$/g, "") : "";
if (!boundary) throw new Error("缺少 multipart boundary");
const boundaryBuf = Buffer.from(`--${boundary}`);
const headerSep = Buffer.from("\r\n\r\n");
const crlf = Buffer.from("\r\n");
const fields = {};
const files = {};
let pos = 0;
for (;;) {
const start = body.indexOf(boundaryBuf, pos);
if (start === -1) break;
pos = start + boundaryBuf.length;
// 结束 boundary:--boundary--
if (body.slice(pos, pos + 2).toString() === "--") break;
// 跳过起始 CRLF
if (body.slice(pos, pos + 2).equals(crlf)) pos += 2;
const next = body.indexOf(boundaryBuf, pos);
if (next === -1) break;
const partBuf = body.slice(pos, next);
pos = next;
const headerEnd = partBuf.indexOf(headerSep);
if (headerEnd === -1) continue;
const headerText = partBuf.slice(0, headerEnd).toString("utf8");
let contentBuf = partBuf.slice(headerEnd + headerSep.length);
// 去掉结尾 CRLF
if (contentBuf.length >= 2 && contentBuf.slice(contentBuf.length - 2).equals(crlf)) {
contentBuf = contentBuf.slice(0, contentBuf.length - 2);
}
const headers = {};
for (const line of headerText.split(/\r?\n/)) {
const idx = line.indexOf(":");
if (idx === -1) continue;
const k = line.slice(0, idx).trim().toLowerCase();
const v = line.slice(idx + 1).trim();
headers[k] = v;
}
const cd = headers["content-disposition"] || "";
const nameM = cd.match(/name="([^"]+)"/i);
const filenameM = cd.match(/filename="([^"]*)"/i);
const name = nameM ? nameM[1] : "";
if (!name) continue;
const partCt = headers["content-type"] || "text/plain";
const filename = filenameM ? filenameM[1] : "";
if (filenameM) {
files[name] = { filename, contentType: partCt, buffer: contentBuf };
} else {
fields[name] = contentBuf.toString("utf8");
}
}
return { fields, files };
}
function createMutex() {
let last = Promise.resolve();
return {
async run(fn) {
const prev = last;
let release;
last = new Promise((r) => (release = r));
await prev;
try {
return await fn();
} finally {
release();
}
}
};
}
class TokenStore {
constructor(filePath) {
this.filePath = filePath;
this.accounts = new Map();
this.runtime = new Map();
this._saveMutex = createMutex();
}
async init() {
await fsp.mkdir(path.dirname(this.filePath), { recursive: true });
await this._load();
for (const id of this.accounts.keys()) this._ensureRuntime(id);
}
_ensureRuntime(id) {
if (this.runtime.has(id)) return;
this.runtime.set(id, {
refreshMutex: createMutex(),
securityMutex: createMutex(),
inflight: 0,
circuitUntilMs: 0,
authSecurityCooldownUntilMs: 0,
lastError: null,
consecutiveFailures: 0
});
}
async _load() {
try {
const raw = await fsp.readFile(this.filePath, "utf8");
const parsed = safeJsonParse(raw);
if (!parsed.ok) throw new Error(parsed.error);
const list = Array.isArray(parsed.value?.accounts) ? parsed.value.accounts : [];
for (const a of list) {
if (!a?.id || typeof a?.refreshToken !== "string") continue;
const jwt = !a.email && a.accessToken ? parseJwtPayload(a.accessToken) : null;
const jwtEmail =
(typeof jwt?.email === "string" ? jwt.email : "") ||
(typeof jwt?.user_metadata?.email === "string" ? jwt.user_metadata.email : "") ||
"";
const normalized = {
id: a.id,
email: typeof a.email === "string" ? a.email : jwtEmail,
isPro: Boolean(a.isPro || a.label === "Pro"),
disabled: Boolean(a.disabled),
userId: a.userId || "",
imageModel: typeof a.imageModel === "string" ? a.imageModel : "",
imageEditModel: typeof a.imageEditModel === "string" ? a.imageEditModel : "",
memoryEnabled: a.memoryEnabled === true,
profileSettingsSyncedAtMs: Number(a.profileSettingsSyncedAtMs || 0),
refreshToken: a.refreshToken,
accessToken: a.accessToken || "",
accessExpiresAtMs: Number(a.accessExpiresAtMs || 0),
security: a.security || null,
maxInflight: Number(a.maxInflight || 0)
};
this.accounts.set(a.id, normalized);
}
} catch (e) {
if (String(e).includes("ENOENT")) return;
throw e;
}
}
async save() {
await this._saveMutex.run(async () => {
const accounts = [...this.accounts.values()].map((a) => ({
id: a.id,
email: a.email || "",
isPro: Boolean(a.isPro),
disabled: Boolean(a.disabled),
userId: a.userId || "",
imageModel: typeof a.imageModel === "string" ? a.imageModel : "",
imageEditModel: typeof a.imageEditModel === "string" ? a.imageEditModel : "",
memoryEnabled: a.memoryEnabled === true,
profileSettingsSyncedAtMs: Number(a.profileSettingsSyncedAtMs || 0),
refreshToken: a.refreshToken,
accessToken: a.accessToken || "",
accessExpiresAtMs: Number(a.accessExpiresAtMs || 0),
security: a.security || null,
maxInflight: Number(a.maxInflight || 0)
}));
const payload = JSON.stringify({ accounts }, null, 2);
await fsp.writeFile(this.filePath, payload, "utf8");
});
}
list() {
const out = [];
const now = nowMs();
for (const a of this.accounts.values()) {
const rt = this.runtime.get(a.id) || {};
const jwt = !a.email && a.accessToken ? parseJwtPayload(a.accessToken) : null;
const email =
a.email ||
(typeof jwt?.email === "string" ? jwt.email : "") ||
(typeof jwt?.user_metadata?.email === "string" ? jwt.user_metadata.email : "") ||
"";
const circuitUntilMs = Number(rt.circuitUntilMs || 0);
const inCircuit = circuitUntilMs > now;
const authSecurityCooldownUntilMs = Number(rt.authSecurityCooldownUntilMs || 0);
out.push({
id: a.id,
email,
isPro: Boolean(a.isPro),
disabled: Boolean(a.disabled),
userId: a.userId || "",
imageModel: typeof a.imageModel === "string" ? a.imageModel : "",
imageEditModel: typeof a.imageEditModel === "string" ? a.imageEditModel : "",
memoryEnabled: a.memoryEnabled === true,
profileSettingsSyncedAtMs: Number(a.profileSettingsSyncedAtMs || 0),
accessExpiresAtMs: Number(a.accessExpiresAtMs || 0),
csrfExpiresAtMs: Number(a.security?.csrfExpiresAtMs || 0),
inflight: Number(rt.inflight || 0),
circuitUntilMs,
authSecurityCooldownUntilMs,
lastError: inCircuit ? rt.lastError || null : null,
consecutiveFailures: Number(rt.consecutiveFailures || 0),
maxInflight: Number(a.maxInflight || 0) || CONFIG.defaultMaxInflightPerAccount
});
}
out.sort((x, y) => x.id.localeCompare(y.id));
return out;
}
upsertFromAppSession(appSession) {
const refreshToken = appSession?.refresh_token;
if (typeof refreshToken !== "string" || !refreshToken) {
throw new Error("app-session 缺少 refresh_token");
}
const id = appSession?.user?.id || randomId("acct");
const userId = appSession?.user?.id || "";
const email =
appSession?.user?.email ||
appSession?.user?.user_metadata?.email ||
appSession?.user?.user_metadata?.mail ||
"";
const accessToken = appSession?.access_token || "";
const accessExpiresAtSec = Number(appSession?.expires_at || 0);
const accessExpiresAtMs = accessExpiresAtSec > 0 ? accessExpiresAtSec * 1000 : 0;
const existing = this.accounts.get(id);
const jwt = !email && accessToken ? parseJwtPayload(accessToken) : null;
const jwtEmail =
(typeof jwt?.email === "string" ? jwt.email : "") || (typeof jwt?.user_metadata?.email === "string" ? jwt.user_metadata.email : "");
const account = {
id,
email: email || jwtEmail || existing?.email || "",
isPro: Boolean(existing?.isPro),
disabled: false,
userId,
imageModel: typeof existing?.imageModel === "string" ? existing.imageModel : "",
imageEditModel: typeof existing?.imageEditModel === "string" ? existing.imageEditModel : "",
memoryEnabled: existing?.memoryEnabled === true,
profileSettingsSyncedAtMs: Number(existing?.profileSettingsSyncedAtMs || 0),
refreshToken,
accessToken: accessToken || existing?.accessToken || "",
accessExpiresAtMs: accessExpiresAtMs || existing?.accessExpiresAtMs || 0,
security: existing?.security || null,
maxInflight: existing?.maxInflight || 0
};
this.accounts.set(id, account);
this._ensureRuntime(id);
return account;