-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.mjs
More file actions
2382 lines (2135 loc) · 78.9 KB
/
Copy pathproxy.mjs
File metadata and controls
2382 lines (2135 loc) · 78.9 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
import { createServer } from "node:http";
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
import { existsSync } from "node:fs";
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { fileURLToPath } from "node:url";
const rootDir = path.dirname(fileURLToPath(import.meta.url));
const upstreamOrigin = new URL(process.env.UPSTREAM_ORIGIN ?? "https://api.finalval.com");
const listenHost = process.env.HOST ?? "127.0.0.1";
const listenPort = Number(process.env.PORT ?? 8787);
const maxRequestBytes = Number(process.env.MAX_REQUEST_BYTES ?? 20 * 1024 * 1024);
const maxCapturedRequestBytes = Number(process.env.MAX_CAPTURE_REQUEST_BYTES ?? maxRequestBytes);
const maxCapturedResponseBytes = Number(process.env.MAX_CAPTURE_RESPONSE_BYTES ?? 20 * 1024 * 1024);
const redactHeaders = process.env.REDACT_HEADERS !== "0";
const captureOnlyMode = /^(1|true|yes|on)$/i.test(String(process.env.CAPTURE_ONLY ?? ""));
const rulesPath = process.env.RULES_PATH
? path.resolve(process.env.RULES_PATH)
: path.join(rootDir, "rules.json");
const captureRoot = process.env.CAPTURE_DIR
? path.resolve(process.env.CAPTURE_DIR)
: path.join(rootDir, "captures");
const corsOrigin = process.env.CORS_ORIGIN ?? "*";
const chatCompletionsStreamMode = String(
process.env.CHAT_COMPLETIONS_STREAM_MODE
?? (process.env.FORCE_CHAT_COMPLETIONS_STREAM === "1" ? "always" : "auto")
).toLowerCase();
const chatCompletionsStreamThresholdBytes = Number(process.env.CHAT_COMPLETIONS_STREAM_THRESHOLD_BYTES ?? 48 * 1024);
const chatCompletionsStreamThresholdImages = Number(process.env.CHAT_COMPLETIONS_STREAM_THRESHOLD_IMAGES ?? 1);
const chatCompletionsStreamThresholdMessages = Number(process.env.CHAT_COMPLETIONS_STREAM_THRESHOLD_MESSAGES ?? 12);
const captureRetentionDays = Number(process.env.CAPTURE_RETENTION_DAYS ?? 30);
const captureRetentionMaxFiles = Number(process.env.CAPTURE_RETENTION_MAX_FILES ?? 800);
const captureRetentionMaxTotalBytes = Number(process.env.CAPTURE_RETENTION_MAX_TOTAL_MB ?? 2048) * 1024 * 1024;
const panelCssPath = path.join(rootDir, "panel.css");
const panelJsPath = path.join(rootDir, "panel.js");
const cliRelayUsageDbPath = process.env.CLIRELAY_USAGE_DB_PATH ?? "C:\\Users\\nim6\\.CliRelay\\data\\usage.db";
const cliRelayApiKeyLookupEnabled = process.env.CLIRELAY_API_KEY_LOOKUP !== "0" && existsSync(cliRelayUsageDbPath);
const panelPublicPrefix = normalizePublicPrefix(process.env.PANEL_PUBLIC_PREFIX ?? "");
const panelEmbeddedPrefix = normalizePublicPrefix(process.env.PANEL_EMBEDDED_PREFIX ?? "/_proxy-panel");
const panelEmbeddedAuthMode = String(process.env.PANEL_EMBEDDED_AUTH_MODE ?? "sub2api-admin").toLowerCase();
const panelSessionCookieName = process.env.PANEL_SESSION_COOKIE_NAME ?? "__Secure-proxy_panel_session";
const panelSessionSecret = process.env.PANEL_SESSION_SECRET || randomBytes(32).toString("hex");
const panelSessionTtlMs = Number(process.env.PANEL_SESSION_TTL_SECONDS ?? 6 * 60 * 60) * 1000;
const captureAssetsDirName = "_assets";
const captureIndexDbPath = path.join(captureRoot, ".panel-index.sqlite");
const captureDetailCacheLimit = 24;
const captureIndexSyncIntervalMs = Number(process.env.CAPTURE_INDEX_SYNC_INTERVAL_MS ?? 15000);
const captureSummaryState = {
loadPromise: null,
detailCache: new Map(),
activeCaptures: new Map(),
db: null,
prunePromise: Promise.resolve(),
migrationPromise: Promise.resolve(),
indexReady: false,
lastSyncMs: 0
};
const hopByHopHeaders = new Set([
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade"
]);
const sensitiveHeaders = new Set([
"authorization",
"proxy-authorization",
"x-api-key",
"x-goog-api-key",
"cookie",
"set-cookie"
]);
function normalizePublicPrefix(value) {
const raw = String(value ?? "").trim();
if (!raw || raw === "/") return "";
return "/" + raw.replace(/^\/+|\/+$/g, "");
}
function prefixedUrl(prefix, pathnameWithSearch) {
return `${prefix}${String(pathnameWithSearch).startsWith("/") ? "" : "/"}${pathnameWithSearch}`;
}
function requestId() {
return `${new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14)}-${randomUUID().slice(0, 8)}`;
}
function stripHopByHop(headers) {
const result = {};
for (const [name, value] of Object.entries(headers)) {
const lowerName = name.toLowerCase();
if (hopByHopHeaders.has(lowerName)) continue;
result[name] = value;
}
return result;
}
function sanitizeHeaders(headers) {
const result = {};
for (const [name, value] of Object.entries(headers ?? {})) {
if (redactHeaders && sensitiveHeaders.has(name.toLowerCase())) {
result[name] = "[redacted]";
} else {
result[name] = value;
}
}
return result;
}
function headerFirstValue(value) {
if (Array.isArray(value)) return value[0] ?? "";
return value ?? "";
}
function maskSecret(value) {
const secret = String(value ?? "").trim();
if (!secret) return "";
if (secret.length <= 10) return secret.slice(0, 2) + "..." + secret.slice(-2);
return secret.slice(0, 6) + "..." + secret.slice(-4);
}
function lookupCliRelayApiKeyName(secret) {
const apiKey = String(secret ?? "").trim();
if (!apiKey || !cliRelayApiKeyLookupEnabled) return "";
let db;
try {
db = new DatabaseSync(cliRelayUsageDbPath, { open: true, readOnly: true });
const row = db.prepare("select name from api_keys where key = ? and disabled = 0 limit 1").get(apiKey);
return String(row?.name ?? "").trim();
} catch {
return "";
} finally {
try {
db?.close();
} catch {}
}
}
function extractRequestKeyPreview(headers) {
const authorization = String(headerFirstValue(headers?.authorization)).trim();
if (/^Bearer\s+/i.test(authorization)) {
const secret = authorization.replace(/^Bearer\s+/i, "");
const keyName = lookupCliRelayApiKeyName(secret);
return {
source: "authorization",
preview: "Bearer " + maskSecret(secret),
keyName,
display: keyName || ("Bearer " + maskSecret(secret))
};
}
const xApiKey = String(headerFirstValue(headers?.["x-api-key"])).trim();
if (xApiKey) {
const keyName = lookupCliRelayApiKeyName(xApiKey);
return {
source: "x-api-key",
preview: maskSecret(xApiKey),
keyName,
display: keyName || maskSecret(xApiKey)
};
}
const xGoogApiKey = String(headerFirstValue(headers?.["x-goog-api-key"])).trim();
if (xGoogApiKey) {
const keyName = lookupCliRelayApiKeyName(xGoogApiKey);
return {
source: "x-goog-api-key",
preview: maskSecret(xGoogApiKey),
keyName,
display: keyName || maskSecret(xGoogApiKey)
};
}
return null;
}
function isTextLike(headers) {
const contentType = String(headers["content-type"] ?? headers["Content-Type"] ?? "").toLowerCase();
return (
contentType.startsWith("application/json") ||
contentType.startsWith("text/") ||
contentType.includes("javascript") ||
contentType.includes("xml") ||
contentType.includes("x-ndjson") ||
contentType.includes("event-stream")
);
}
function bodyForCapture(buffer, headers, truncated = false) {
const textLike = isTextLike(headers);
return {
encoding: textLike ? "utf8" : "base64",
truncated,
bytes: buffer.length,
data: textLike ? buffer.toString("utf8") : buffer.toString("base64")
};
}
function createCaptureBuffer(maxBytes) {
const chunks = [];
let bytes = 0;
let totalBytes = 0;
let truncated = false;
return {
push(chunk) {
totalBytes += chunk.length;
if (truncated) return;
if (bytes + chunk.length <= maxBytes) {
chunks.push(chunk);
bytes += chunk.length;
return;
}
const remaining = Math.max(0, maxBytes - bytes);
if (remaining > 0) {
chunks.push(chunk.subarray(0, remaining));
bytes += remaining;
}
truncated = true;
},
body(headers) {
const body = bodyForCapture(Buffer.concat(chunks, bytes), headers, truncated);
body.bytes = totalBytes;
return body;
}
};
}
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > maxRequestBytes) {
const err = new Error(`request body exceeds MAX_REQUEST_BYTES=${maxRequestBytes}`);
err.statusCode = 413;
throw err;
}
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function loadRules() {
try {
const raw = await readFile(rulesPath, "utf8");
const parsed = JSON.parse(raw);
return parsed.enabled === false ? [] : Array.isArray(parsed.rules) ? parsed.rules : [];
} catch (error) {
if (error.code === "ENOENT") return [];
throw new Error(`failed to read rules file ${rulesPath}: ${error.message}`);
}
}
function matchesRule(rule, method, pathname) {
if (rule.enabled === false) return false;
if (Array.isArray(rule.methods) && !rule.methods.map(String).map((x) => x.toUpperCase()).includes(method)) {
return false;
}
if (rule.path && rule.path !== pathname) return false;
if (rule.pathPrefix && !pathname.startsWith(rule.pathPrefix)) return false;
return Boolean(rule.path || rule.pathPrefix);
}
function setDeep(target, dottedPath, value) {
const parts = dottedPath.split(".").filter(Boolean);
if (parts.length === 0) return;
let cursor = target;
for (const part of parts.slice(0, -1)) {
if (!cursor[part] || typeof cursor[part] !== "object" || Array.isArray(cursor[part])) {
cursor[part] = {};
}
cursor = cursor[part];
}
cursor[parts.at(-1)] = value;
}
function deleteDeep(target, dottedPath) {
const parts = dottedPath.split(".").filter(Boolean);
if (parts.length === 0) return;
let cursor = target;
for (const part of parts.slice(0, -1)) {
if (!cursor || typeof cursor !== "object") return;
cursor = cursor[part];
}
if (cursor && typeof cursor === "object") {
delete cursor[parts.at(-1)];
}
}
function applyJsonRule(json, rule) {
const changed = [];
if (rule.modelMap && typeof rule.modelMap === "object" && typeof json.model === "string") {
const mappedModel = rule.modelMap[json.model];
if (mappedModel && mappedModel !== json.model) {
changed.push({ op: "modelMap", path: "model", from: json.model, to: mappedModel });
json.model = mappedModel;
}
}
if (rule.jsonSet && typeof rule.jsonSet === "object") {
for (const [key, value] of Object.entries(rule.jsonSet)) {
setDeep(json, key, value);
changed.push({ op: "set", path: key, to: value });
}
}
if (Array.isArray(rule.jsonDelete)) {
for (const key of rule.jsonDelete) {
deleteDeep(json, String(key));
changed.push({ op: "delete", path: String(key) });
}
}
return changed;
}
async function mutateRequestBody(req, requestBody, targetUrl) {
const contentType = String(req.headers["content-type"] ?? "").toLowerCase();
if (!contentType.includes("application/json") || requestBody.length === 0) {
return { body: requestBody, mutations: [], streamEnabled: false, requestedStream: false, bridgeEnabled: false };
}
const rules = await loadRules();
const matchedRules = rules.filter((rule) => matchesRule(rule, req.method, targetUrl.pathname));
const rawText = requestBody.toString("utf8");
let json;
try {
json = JSON.parse(rawText);
} catch {
return { body: requestBody, mutations: [], streamEnabled: false, requestedStream: false, bridgeEnabled: false };
}
const requestedStream = json.stream === true;
const mutations = [];
for (const rule of matchedRules) {
const changes = applyJsonRule(json, rule);
if (changes.length > 0) {
mutations.push({ rule: rule.name ?? "(unnamed)", changes });
}
}
const bridgeEnabled =
req.method === "POST"
&& targetUrl.pathname.startsWith("/v1/chat/completions")
&& !requestedStream
&& shouldBridgeChatCompletions(json, rawText);
if (bridgeEnabled && json.stream !== true) {
json.stream = true;
mutations.push({
rule: "auto-stream",
changes: [{ op: "set", path: "stream", to: true }]
});
}
const streamEnabled = Boolean(json.stream);
if (mutations.length === 0) {
return { body: requestBody, mutations: [], streamEnabled, requestedStream, bridgeEnabled };
}
return {
body: Buffer.from(JSON.stringify(json), "utf8"),
mutations,
streamEnabled,
requestedStream,
bridgeEnabled
};
}
function safePathSegment(value) {
const safe = value.replace(/[^a-zA-Z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
return safe.slice(0, 80) || "root";
}
async function saveCapture(capture) {
const date = capture.startedAt.slice(0, 10);
const dir = path.join(captureRoot, date);
await mkdir(dir, { recursive: true });
const rewritten = await rewriteCaptureInlineAssetsForSave(capture);
const fileName = `${capture.id}_${capture.request.method}_${safePathSegment(capture.request.path)}.json`;
const filePath = path.join(dir, fileName);
const fileText = `${JSON.stringify(rewritten.capture, null, 2)}\n`;
await writeFile(filePath, fileText, "utf8");
rememberDetailCache(
path.relative(captureRoot, filePath).replaceAll(path.sep, "/"),
Buffer.byteLength(fileText),
Date.now(),
rewritten.capture,
rewritten.assets
);
await rememberSavedCapture(filePath, rewritten.capture, Buffer.byteLength(fileText));
await pruneCapturesIfNeeded();
return filePath;
}
function sendText(res, statusCode, contentType, text, extraHeaders = {}) {
const body = Buffer.from(String(text ?? ""), "utf8");
res.writeHead(statusCode, {
"content-type": contentType,
"content-length": body.length,
...extraHeaders
});
res.end(body);
}
function redirect(res, location, extraHeaders = {}) {
res.writeHead(302, {
location,
"cache-control": "no-store",
...extraHeaders
});
res.end();
}
function sendJson(res, statusCode, payload) {
sendText(res, statusCode, "application/json; charset=utf-8", JSON.stringify(payload), corsHeaders());
}
function jsonResponseText(payload) {
return JSON.stringify(payload);
}
function jsonResponseHeaders(requestedHeaders = undefined) {
return {
"content-type": "application/json; charset=utf-8",
...corsHeaders(requestedHeaders)
};
}
function sendHtml(res, html, extraHeaders = {}) {
sendText(res, 200, "text/html; charset=utf-8", html, {
"cache-control": "no-store",
"content-security-policy":
"default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data: blob: http: https:; object-src 'none'; base-uri 'none'; form-action 'none'",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
...extraHeaders
});
}
function sendPanelForbidden(res, prefix) {
sendText(res, 403, "text/plain; charset=utf-8", "Forbidden\n", {
"cache-control": "no-store",
"set-cookie": panelSessionClearCookie(prefix),
"x-content-type-options": "nosniff"
});
}
function sendBuffer(res, statusCode, contentType, buffer, extraHeaders = {}) {
res.writeHead(statusCode, {
"content-type": contentType,
"content-length": buffer.length,
...extraHeaders
});
res.end(buffer);
}
async function sendStaticTextFile(res, filePath, contentType, transform = null, extraHeaders = {}) {
try {
const raw = await readFile(filePath, "utf8");
const text = typeof transform === "function" ? transform(raw) : raw;
sendText(res, 200, contentType, text, {
"cache-control": "no-store",
"x-content-type-options": "nosniff",
...extraHeaders
});
} catch (error) {
const statusCode = error.code === "ENOENT" ? 404 : 500;
sendJson(res, statusCode, {
error: "PANEL_ASSET_READ_FAILED",
message: error.message
});
}
}
function corsHeaders(requestedHeaders = undefined) {
const headers = {
"access-control-allow-origin": corsOrigin,
"access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
"access-control-allow-headers":
requestedHeaders || "authorization,content-type,x-api-key,x-goog-api-key,x-requested-with",
"access-control-expose-headers": "content-type,x-request-id"
};
if (corsOrigin !== "*") {
headers.vary = "Origin";
}
return headers;
}
function parseCookies(header) {
const cookies = new Map();
for (const part of String(header ?? "").split(";")) {
const index = part.indexOf("=");
if (index <= 0) continue;
cookies.set(part.slice(0, index).trim(), decodeURIComponent(part.slice(index + 1).trim()));
}
return cookies;
}
function signPanelSession(value) {
return createHash("sha256").update(`${value}.${panelSessionSecret}`).digest("hex");
}
function makePanelSessionCookie(token) {
const expiresAt = Date.now() + panelSessionTtlMs;
const value = `${expiresAt}.${createHash("sha256").update(String(token)).digest("hex")}`;
const signature = signPanelSession(value);
return `${value}.${signature}`;
}
function validPanelSessionCookie(cookieValue) {
const parts = String(cookieValue ?? "").split(".");
if (parts.length !== 3) return false;
const [expiresAtRaw, tokenHash, signature] = parts;
const expiresAt = Number(expiresAtRaw);
if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || !/^[a-f0-9]{64}$/i.test(tokenHash)) {
return false;
}
const expected = signPanelSession(`${expiresAtRaw}.${tokenHash}`);
const expectedBuffer = Buffer.from(expected);
const actualBuffer = Buffer.from(signature);
return expectedBuffer.length === actualBuffer.length && timingSafeEqual(expectedBuffer, actualBuffer);
}
function panelSessionSetCookie(token, prefix) {
const maxAge = Math.max(1, Math.floor(panelSessionTtlMs / 1000));
const pathValue = prefix ? `${prefix}/` : "/";
return `${panelSessionCookieName}=${encodeURIComponent(makePanelSessionCookie(token))}; Path=${pathValue}; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=Lax`;
}
function panelSessionClearCookie(prefix) {
const pathValue = prefix ? `${prefix}/` : "/";
return `${panelSessionCookieName}=; Path=${pathValue}; Max-Age=0; HttpOnly; Secure; SameSite=Lax`;
}
function extractPanelToken(localUrl, req) {
const queryToken = localUrl.searchParams.get("token");
if (queryToken) return queryToken;
const authHeader = String(req.headers.authorization ?? "");
const match = authHeader.match(/^Bearer\s+(.+)$/i);
return match ? match[1].trim() : "";
}
async function verifySub2ApiAdminToken(token) {
if (!token || token.length > 8192) return false;
const authUrl = new URL("/api/v1/auth/me", upstreamOrigin);
const headers = {
authorization: `Bearer ${token}`,
accept: "application/json"
};
return await new Promise((resolve) => {
const transport = authUrl.protocol === "https:" ? httpsRequest : httpRequest;
const verifyReq = transport(
{
protocol: authUrl.protocol,
hostname: authUrl.hostname,
port: authUrl.port || undefined,
method: "GET",
path: `${authUrl.pathname}${authUrl.search}`,
headers,
timeout: 5000
},
(verifyRes) => {
const chunks = [];
verifyRes.on("data", (chunk) => {
if (chunks.reduce((sum, item) => sum + item.length, 0) < 1024 * 1024) {
chunks.push(chunk);
}
});
verifyRes.on("end", () => {
if ((verifyRes.statusCode ?? 500) >= 400) {
resolve(false);
return;
}
try {
const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
const data = payload?.data ?? payload;
resolve(data?.role === "admin" || data?.user?.role === "admin");
} catch {
resolve(false);
}
});
}
);
verifyReq.on("timeout", () => verifyReq.destroy(new Error("sub2api auth timeout")));
verifyReq.on("error", () => resolve(false));
verifyReq.end();
});
}
async function authorizeEmbeddedPanel(req, res, localUrl, prefix) {
if (panelEmbeddedAuthMode === "off") return true;
const cookies = parseCookies(req.headers.cookie);
if (validPanelSessionCookie(cookies.get(panelSessionCookieName))) {
return true;
}
const token = extractPanelToken(localUrl, req);
if (panelEmbeddedAuthMode === "sub2api-admin" && await verifySub2ApiAdminToken(token)) {
const cleanUrl = new URL(localUrl);
cleanUrl.searchParams.delete("token");
redirect(res, `${cleanUrl.pathname}${cleanUrl.search}`, {
"set-cookie": panelSessionSetCookie(token, prefix)
});
return false;
}
sendPanelForbidden(res, prefix);
return false;
}
async function authorizePanelSurface(req, res, localUrl, prefix) {
if (panelEmbeddedAuthMode === "off") return true;
const cookies = parseCookies(req.headers.cookie);
if (validPanelSessionCookie(cookies.get(panelSessionCookieName))) {
return true;
}
const token = extractPanelToken(localUrl, req);
if (panelEmbeddedAuthMode === "sub2api-admin" && await verifySub2ApiAdminToken(token)) {
return true;
}
sendPanelForbidden(res, prefix);
return false;
}
function captureBodyText(body) {
return body?.encoding === "utf8" ? String(body.data ?? "") : "";
}
function safeJsonParse(raw) {
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}
function collapseWhitespace(value, maxLength = 160) {
const text = String(value ?? "").replace(/\s+/g, " ").trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
}
function collectPreviewStrings(value, pieces = [], depth = 0) {
if (value == null || pieces.length >= 8 || depth > 6) return pieces;
if (typeof value === "string") {
const text = collapseWhitespace(value, 240);
if (text) pieces.push(text);
return pieces;
}
if (Array.isArray(value)) {
for (const item of value) {
collectPreviewStrings(item, pieces, depth + 1);
if (pieces.length >= 8) break;
}
return pieces;
}
if (typeof value !== "object") return pieces;
for (const key of [
"text",
"input_text",
"output_text",
"content",
"parts",
"prompt",
"instructions",
"system",
"system_instruction",
"message",
"messages",
"input",
"delta",
"reasoning_content"
]) {
if (pieces.length >= 8) break;
if (Object.hasOwn(value, key)) {
collectPreviewStrings(value[key], pieces, depth + 1);
}
}
if (pieces.length > 0) return pieces;
for (const [key, nested] of Object.entries(value)) {
if (pieces.length >= 8) break;
if (["id", "object", "role", "type", "model", "name", "usage", "created"].includes(key)) continue;
collectPreviewStrings(nested, pieces, depth + 1);
}
return pieces;
}
function previewFromValue(value, maxLength = 160) {
return collapseWhitespace(collectPreviewStrings(value).join(" "), maxLength);
}
function pickInputLikeValue(payload) {
if (!payload || typeof payload !== "object") return payload;
if (Array.isArray(payload.messages)) return payload.messages.map((message) => message?.content ?? message);
if (Array.isArray(payload.input)) return payload.input;
if (typeof payload.input === "string") return payload.input;
if (Array.isArray(payload.contents)) return payload.contents.map((item) => item?.parts ?? item?.content ?? item);
if (payload.prompt != null) return payload.prompt;
if (payload.instructions != null) return payload.instructions;
if (payload.system != null) return payload.system;
if (payload.system_instruction != null) return payload.system_instruction;
return payload;
}
function pickOutputLikeValue(payload) {
if (!payload || typeof payload !== "object") return payload;
if (typeof payload.output_text === "string") return payload.output_text;
if (Array.isArray(payload.output) && payload.output.length > 0) {
return payload.output.map((item) => item?.content ?? item?.text ?? item);
}
if (Array.isArray(payload.choices) && payload.choices.length > 0) {
return payload.choices.map((choice) => choice?.message?.content ?? choice?.text ?? choice?.delta?.content ?? choice);
}
if (Array.isArray(payload.content) && payload.content.length > 0) return payload.content;
if (Array.isArray(payload.candidates) && payload.candidates.length > 0) {
return payload.candidates.map((candidate) => candidate?.content?.parts ?? candidate?.content ?? candidate);
}
if (payload.message) return payload.message.content ?? payload.message;
if (payload.response) return pickOutputLikeValue(payload.response);
return payload;
}
function detectRequestKind(payload, requestPath) {
const pathText = String(requestPath ?? "").toLowerCase();
if (pathText.includes("/v1/chat/completions")) return "chat";
if (pathText.includes("/v1/responses")) return "responses";
if (Array.isArray(payload?.messages)) return "messages";
if (Array.isArray(payload?.input) || typeof payload?.input === "string") return "input";
if (Array.isArray(payload?.contents)) return "contents";
if (payload?.prompt != null) return "prompt";
return "json";
}
function countConversationItems(payload) {
if (!payload || typeof payload !== "object") return 0;
if (Array.isArray(payload.messages)) return payload.messages.length;
if (Array.isArray(payload.input)) return payload.input.length;
if (typeof payload.input === "string") return 1;
if (Array.isArray(payload.contents)) return payload.contents.length;
if (payload.prompt != null) return 1;
return 0;
}
function countImageLikeParts(value, depth = 0) {
if (value == null || depth > 7) return 0;
if (typeof value === "string") {
return /^data:image\//i.test(value.trim()) ? 1 : 0;
}
if (Array.isArray(value)) {
return value.reduce((sum, item) => sum + countImageLikeParts(item, depth + 1), 0);
}
if (typeof value !== "object") return 0;
let count = 0;
const type = String(value.type ?? "").toLowerCase();
if (type.includes("image")) count += 1;
const imageUrl = value.image_url;
if (typeof imageUrl === "string" && /^data:image\//i.test(imageUrl.trim())) {
count += 1;
} else if (imageUrl && typeof imageUrl === "object") {
if (typeof imageUrl.url === "string" && /^data:image\//i.test(imageUrl.url.trim())) count += 1;
if (typeof imageUrl.data === "string" && /^data:image\//i.test(imageUrl.data.trim())) count += 1;
if (typeof imageUrl.base64 === "string") count += 1;
}
if (typeof value.url === "string" && /^data:image\//i.test(value.url.trim())) count += 1;
if (typeof value.data === "string" && /^data:image\//i.test(value.data.trim())) count += 1;
if (typeof value.base64 === "string") count += 1;
if (value.inline_data && typeof value.inline_data === "object") {
if (typeof value.inline_data.data === "string" || typeof value.inline_data.base64 === "string") count += 1;
}
if (value.source && typeof value.source === "object") {
const sourceType = String(value.source.type ?? "").toLowerCase();
if (sourceType.includes("image")) count += 1;
if (typeof value.source.data === "string" || typeof value.source.base64 === "string") count += 1;
}
for (const [key, nested] of Object.entries(value)) {
if (["image_url", "url", "data", "base64", "inline_data", "source"].includes(key)) continue;
count += countImageLikeParts(nested, depth + 1);
}
return count;
}
function shouldBridgeChatCompletions(payload, rawText) {
if (chatCompletionsStreamMode === "off") return false;
if (chatCompletionsStreamMode === "always") return true;
const bytes = Buffer.byteLength(String(rawText ?? ""), "utf8");
const imageCount = countImageLikeParts(payload);
const messageCount = countConversationItems(payload);
return (
imageCount >= chatCompletionsStreamThresholdImages
|| bytes >= chatCompletionsStreamThresholdBytes
|| messageCount >= chatCompletionsStreamThresholdMessages
);
}
function looksLikeSse(headers, rawText) {
const contentType = String(headers?.["content-type"] ?? headers?.["Content-Type"] ?? "").toLowerCase();
return contentType.includes("event-stream") || /^\s*(event:|data:)/m.test(String(rawText ?? ""));
}
function previewFromSse(raw) {
const pieces = [];
for (const line of String(raw ?? "").replace(/\r\n/g, "\n").split("\n")) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (!data || data === "[DONE]") continue;
const parsed = safeJsonParse(data);
if (parsed) {
const preview = previewFromValue(pickOutputLikeValue(parsed), 200);
if (preview) pieces.push(preview);
} else {
pieces.push(collapseWhitespace(data, 200));
}
if (pieces.length >= 3) break;
}
return collapseWhitespace(pieces.join(" "), 160);
}
function parseSseEvents(raw) {
const events = [];
let eventName = "";
let dataLines = [];
const flush = function () {
if (!eventName && dataLines.length === 0) return;
const data = dataLines.join("\n");
events.push({
event: eventName,
data,
json: data && data !== "[DONE]" ? safeJsonParse(data) : null,
done: data === "[DONE]"
});
eventName = "";
dataLines = [];
};
for (const line of String(raw ?? "").replace(/\r\n/g, "\n").split("\n")) {
if (line === "") {
flush();
} else if (line.startsWith("event:")) {
eventName = line.slice(6).trim();
} else if (line.startsWith("data:")) {
dataLines.push(line.slice(5).replace(/^ /, ""));
}
}
flush();
return events;
}
function appendDeltaText(target, key, value) {
if (typeof value !== "string" || !value) return;
target[key] = typeof target[key] === "string"
? target[key] + value
: value;
}
function mergeToolCallDelta(choice, deltaToolCalls) {
if (!Array.isArray(deltaToolCalls) || deltaToolCalls.length === 0) return;
if (!Array.isArray(choice.message.tool_calls)) {
choice.message.tool_calls = [];
}
for (const deltaToolCall of deltaToolCalls) {
if (!deltaToolCall || typeof deltaToolCall !== "object") continue;
const rawIndex = deltaToolCall.index;
const toolIndex = Number.isInteger(rawIndex) && rawIndex >= 0
? rawIndex
: choice.message.tool_calls.length;
let toolCall = choice.message.tool_calls[toolIndex];
if (!toolCall) {
toolCall = {};
choice.message.tool_calls[toolIndex] = toolCall;
}
if (deltaToolCall.id) toolCall.id = deltaToolCall.id;
if (deltaToolCall.type) toolCall.type = deltaToolCall.type;
if (deltaToolCall.function && typeof deltaToolCall.function === "object") {
toolCall.function ??= {};
if (deltaToolCall.function.name) {
toolCall.function.name = deltaToolCall.function.name;
}
appendDeltaText(toolCall.function, "arguments", deltaToolCall.function.arguments);
}
}
choice.message.tool_calls = choice.message.tool_calls.filter(Boolean);
}
function rebuildChatCompletionFromSse(raw) {
const events = parseSseEvents(raw);
const choices = new Map();
let meta = null;
let usage = null;
let hadAnyChunk = false;
for (const event of events) {
const payload = event.json;
if (!payload || typeof payload !== "object") continue;
if (payload.error) return { error: payload.error };
if (!meta) {
meta = {
id: payload.id,
object: "chat.completion",
created: payload.created,
model: payload.model,
system_fingerprint: payload.system_fingerprint
};
} else {
if (!meta.id && payload.id) meta.id = payload.id;
if (!meta.created && payload.created) meta.created = payload.created;
if (!meta.model && payload.model) meta.model = payload.model;
if (!meta.system_fingerprint && payload.system_fingerprint) meta.system_fingerprint = payload.system_fingerprint;
}
if (payload.usage) usage = payload.usage;
if (!Array.isArray(payload.choices)) continue;
hadAnyChunk = true;
for (const chunkChoice of payload.choices) {
const index = Number.isFinite(chunkChoice?.index) ? chunkChoice.index : 0;
let choice = choices.get(index);
if (!choice) {
choice = {
index,
message: {
role: "assistant",
content: ""
},
finish_reason: null
};
choices.set(index, choice);
}
if (chunkChoice?.message && typeof chunkChoice.message === "object") {
choice.message = {
...choice.message,
...chunkChoice.message
};
}
if (chunkChoice?.delta && typeof chunkChoice.delta === "object") {
if (chunkChoice.delta.role) choice.message.role = chunkChoice.delta.role;
if (typeof chunkChoice.delta.content === "string") {
choice.message.content = (choice.message.content || "") + chunkChoice.delta.content;
}
if (typeof chunkChoice.delta.reasoning_content === "string") {
choice.message.reasoning_content = (choice.message.reasoning_content || "") + chunkChoice.delta.reasoning_content;
}
mergeToolCallDelta(choice, chunkChoice.delta.tool_calls);
}
if (chunkChoice?.finish_reason != null) {
choice.finish_reason = chunkChoice.finish_reason;
}
if (chunkChoice?.logprobs != null) {
choice.logprobs = chunkChoice.logprobs;
}
}
}
if (!hadAnyChunk || choices.size === 0) return null;
const response = {
id: meta?.id || "",
object: "chat.completion",