Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2474 lines (2242 loc) · 88 KB
/
Copy pathserver.js
File metadata and controls
2474 lines (2242 loc) · 88 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 http from 'http';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import { createRateLimiter } from './rate-limiter.js';
import { handleOAuthImageRequestBody, testOAuthAccessToken } from './openai-oauth-image.js';
import { getOAuthMaxBodyBytes } from './oauth-request-limits.js';
import { createJobStore } from './background-jobs.js';
import { createImageStore } from './image-storage.js';
import {
getGenerationProgressMessage,
getResponseStreamProgressMessage,
getResponseStreamProgressPhase,
isPolicyViolationText,
normalizeGenerationError,
} from './ui-feedback.js';
import {
generateCodeVerifier as makeOAuthCodeVerifier,
generateCodeChallenge as makeOAuthCodeChallenge,
parseOAuthCallbackInput,
extractOpenAIUserInfo,
formatOAuthTokenError,
} from './oauth-flow.js';
import { enhancePrompt } from './prompt-enhancement.js';
import { createConfigService } from './config-service.js';
import { createPlatformHandler, getSupportedPlatforms } from './handlers/handler-factory.js';
import { resolveAccountStoreCapabilities } from './account-store-capabilities.js';
import { createAccountStore } from './account-store.js';
import {
getProxyAllowedHosts,
isExplicitLocalDevProxyAllowed,
validateApiBaseUrl,
} from './proxy-policy.js';
import { prepareProxyRequest, runProxyUpstream } from './proxy-executor.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 3000;
const DATA_DIR = process.env.IMAGE_GEN_DATA_DIR || path.join(__dirname, 'data');
const STATIC_ROOT = path.resolve(process.env.IMAGE_GEN_STATIC_DIR || path.join(__dirname, 'dist'));
const MAX_REF_IMAGES = 3;
const RESPONSES_PARTIAL_IMAGES = 3;
const IMAGES_API_TIMEOUT_MS = 300_000;
const RESPONSES_API_TIMEOUT_MS = 300_000;
function boundedIntEnv(name, fallback, min, max) {
const raw = Number.parseInt(process.env[name] || '', 10);
if (!Number.isFinite(raw)) return fallback;
return Math.min(max, Math.max(min, raw));
}
const IMAGE_JOB_MAX_CONCURRENCY = boundedIntEnv('IMAGE_JOB_MAX_CONCURRENCY', 3, 1, 10);
const IMAGE_JOB_MAX_QUEUE = boundedIntEnv('IMAGE_JOB_MAX_QUEUE', 12, 1, 100);
const IMAGE_JOB_TTL_MS = boundedIntEnv('IMAGE_JOB_TTL_MS', 30 * 60 * 1000, 60_000, 24 * 60 * 60 * 1000);
const IMAGE_JOB_PENDING_TIMEOUT_MS = boundedIntEnv('IMAGE_JOB_PENDING_TIMEOUT_MS', 15 * 60 * 1000, 10_000, 60 * 60 * 1000);
const IMAGE_JOB_RUNNING_TIMEOUT_MS = boundedIntEnv('IMAGE_JOB_RUNNING_TIMEOUT_MS', 15 * 60 * 1000, 10_000, 60 * 60 * 1000);
const IMAGE_JOB_MAX_COUNT = 4;
const JSON_BODY_LIMIT_BYTES = Math.min(50 * 1024 * 1024, Math.max(1024, Number(process.env.IMAGE_GEN_JSON_BODY_LIMIT_BYTES || 10 * 1024 * 1024)));
const IMAGE_JOB_BODY_LIMIT_BYTES = getOAuthMaxBodyBytes();
const REF_IMAGE_MAX_BYTES = Math.min(30 * 1024 * 1024, Math.max(1024, Number(process.env.IMAGE_GEN_REF_IMAGE_MAX_BYTES || 8 * 1024 * 1024)));
const REF_IMAGES_TOTAL_MAX_BYTES = Math.min(80 * 1024 * 1024, Math.max(1024, Number(process.env.IMAGE_GEN_REF_IMAGES_TOTAL_MAX_BYTES || 24 * 1024 * 1024)));
const ALLOWED_REF_IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
const imageStore = createImageStore({ dataDir: DATA_DIR });
const OAUTH_LOOPBACK_PORT = 1455;
const OAUTH_SESSION_FILE = process.env.IMAGE_GEN_OAUTH_SESSION_FILE || path.join(__dirname, '.oauth-sessions.json');
const MIME = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
};
const OAUTH_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
const OAUTH_AUTH_URL = 'https://auth.openai.com/oauth/authorize';
const OAUTH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
const OAUTH_SCOPES = 'openid email profile offline_access';
const OAUTH_REDIRECT_URI = `http://localhost:${OAUTH_LOOPBACK_PORT}/auth/callback`;
const ADMIN_TOKEN_HEADER = 'x-image-gen-admin-token';
const STATIC_DENY_SEGMENTS = new Set(['config', 'data', 'api', 'handlers', 'node_modules', 'scripts', 'test', 'netlify']);
const STATIC_DENY_FILES = new Set([
'server.js',
'config-service.js',
'openai-oauth-image.js',
'oauth-flow.js',
'package.json',
'package-lock.json',
'.oauth-sessions.json',
]);
const configService = createConfigService({
isServerless: isServerlessRuntime(),
onReload: (nextConfig) => {
console.log(`[config] reloaded ${configService?.envFile || ''} (${nextConfig?.providerDefaults?.imageModel || 'gpt-image-2'})`);
},
});
function parseOriginList(value = '') {
return String(value || '')
.split(',')
.map((item) => item.trim().replace(/\/+$/, ''))
.filter(Boolean);
}
function parseHostHeader(value = '') {
try {
return new URL(`http://${String(value || '').trim()}`).hostname.toLowerCase();
} catch {
return '';
}
}
function isLocalDevHostname(hostname = '') {
const host = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
return host === 'localhost' || host === '127.0.0.1' || host === '::1';
}
function resolveAllowedCorsOrigin(req) {
const origin = String(req.headers.origin || '').trim().replace(/\/+$/, '');
if (!origin) return '';
let parsed;
try {
parsed = new URL(origin);
} catch {
return '';
}
if (!['http:', 'https:'].includes(parsed.protocol)) return '';
const explicitOrigins = new Set(parseOriginList(process.env.IMAGE_GEN_ALLOWED_ORIGINS));
if (explicitOrigins.has(origin)) return origin;
const requestHost = String(req.headers.host || '').toLowerCase();
if (parsed.host.toLowerCase() === requestHost) return origin;
const requestHostname = parseHostHeader(requestHost);
if (isLocalDevHostname(parsed.hostname) && isLocalDevHostname(requestHostname)) return origin;
return '';
}
function applyCorsHeaders(req, res) {
const allowedOrigin = resolveAllowedCorsOrigin(req);
if (allowedOrigin) {
res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
res.setHeader('Vary', 'Origin');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Image-Gen-Admin-Token');
}
if (!isServerlessRuntime()) {
configService.startWatcher();
}
function getRuntimeConfig() {
return configService.getRuntimeConfig();
}
function getResolvedRuntimeConfig() {
return configService.getResolvedConfig();
}
function getPlatformHandler(platform) {
const resolved = getResolvedRuntimeConfig();
return createPlatformHandler(platform || resolved?.deploy?.platform || 'node', {
configService,
runtimeResolver: getResolvedRuntimeConfig,
});
}
// --- OAuth session store (sessionId -> session, state -> sessionId, persisted, 30 min TTL) ---
const oauthSessions = new Map();
const oauthStateIndex = new Map();
const SESSION_TTL = 30 * 60 * 1000;
export function newOAuthSessionId() {
return crypto.randomBytes(16).toString('hex');
}
function oauthSessionEncryptionKey() {
const secret = getOAuthSessionSecret();
if (!secret) throw new Error('IMAGE_GEN_OAUTH_SESSION_SECRET or IMAGE_GEN_ADMIN_TOKEN is required for stateless OAuth sessions');
return crypto.createHash('sha256').update(secret, 'utf8').digest();
}
function getOAuthSessionSecret() {
return String(process.env.IMAGE_GEN_OAUTH_SESSION_SECRET || process.env.IMAGE_GEN_ADMIN_TOKEN || '').trim();
}
export function encryptOAuthSessionPayload(payload, secret) {
const key = secret
? crypto.createHash('sha256').update(String(secret), 'utf8').digest()
: oauthSessionEncryptionKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return {
v: 1,
iv: iv.toString('base64url'),
tag: tag.toString('base64url'),
ct: ciphertext.toString('base64url'),
};
}
export function decryptOAuthSessionEnvelope(envelope, secret) {
if (!envelope || envelope.v !== 1) throw new Error('OAuth session envelope format is invalid');
const key = secret
? crypto.createHash('sha256').update(String(secret), 'utf8').digest()
: oauthSessionEncryptionKey();
const iv = Buffer.from(String(envelope.iv || ''), 'base64url');
const tag = Buffer.from(String(envelope.tag || ''), 'base64url');
const ciphertext = Buffer.from(String(envelope.ct || ''), 'base64url');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
return JSON.parse(plaintext.toString('utf8'));
}
function safeEqualString(a = '', b = '') {
const left = Buffer.from(String(a));
const right = Buffer.from(String(b));
if (left.length !== right.length) return false;
return crypto.timingSafeEqual(left, right);
}
export function makeStatelessOAuthSessionId(session) {
if (!isServerlessRuntime()) {
return newOAuthSessionId();
}
const secret = getOAuthSessionSecret();
if (!secret) {
throw new Error('IMAGE_GEN_OAUTH_SESSION_SECRET or IMAGE_GEN_ADMIN_TOKEN is required in serverless environments for stateless OAuth sessions');
}
const payload = {
state: session?.state || '',
codeVerifier: session?.codeVerifier || '',
redirectUri: session?.redirectUri || OAUTH_REDIRECT_URI,
createdAt: Number(session?.createdAt || Date.now()),
};
const envelope = encryptOAuthSessionPayload(payload, secret);
return `pkce_${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;
}
export function getOAuthSessionFromStatelessId(sessionId) {
if (!sessionId || !String(sessionId).startsWith('pkce_')) return null;
try {
const secret = getOAuthSessionSecret();
if (!secret) return null;
const envelopeJson = Buffer.from(String(sessionId).slice(5), 'base64url').toString('utf8');
const envelope = JSON.parse(envelopeJson);
const payload = decryptOAuthSessionEnvelope(envelope, secret);
const createdAt = Number(payload.createdAt || 0);
if (!payload.state || !payload.codeVerifier || !createdAt) return null;
if (Date.now() - createdAt > SESSION_TTL) return null;
return {
state: String(payload.state),
codeVerifier: String(payload.codeVerifier),
redirectUri: String(payload.redirectUri || OAUTH_REDIRECT_URI),
status: 'pending',
result: null,
error: null,
createdAt,
};
} catch {
return null;
}
}
function indexOAuthSession(sessionId, session) {
if (session?.state) oauthStateIndex.set(session.state, sessionId);
}
export function setOAuthSession(sessionId, session) {
oauthSessions.set(sessionId, session);
indexOAuthSession(sessionId, session);
saveOAuthSessions();
}
export function getOAuthSessionById(sessionId) {
return sessionId ? oauthSessions.get(sessionId) || null : null;
}
export function getOAuthSessionByState(state) {
if (!state) return { sessionId: '', session: null };
const sessionId = oauthStateIndex.get(state) || '';
return { sessionId, session: sessionId ? getOAuthSessionById(sessionId) : null };
}
export function deleteOAuthSession(sessionId) {
const session = getOAuthSessionById(sessionId);
if (session?.state) oauthStateIndex.delete(session.state);
if (sessionId) oauthSessions.delete(sessionId);
saveOAuthSessions();
}
function isTokenLikeOAuthKey(key = '') {
return /^(accessToken|refreshToken|access_token|refresh_token|id_token|token)$/i.test(String(key || ''))
|| /token$/i.test(String(key || ''));
}
function sanitizeOAuthPersistedValue(value) {
if (Array.isArray(value)) return value.map(sanitizeOAuthPersistedValue);
if (!value || typeof value !== 'object') return value;
const out = {};
for (const [key, child] of Object.entries(value)) {
if (key === 'result' || isTokenLikeOAuthKey(key)) continue;
out[key] = sanitizeOAuthPersistedValue(child);
}
return out;
}
function sanitizeOAuthSessionForDisk(session = {}) {
if (!session || typeof session !== 'object') return null;
if (session.status === 'success') return null;
return sanitizeOAuthPersistedValue(session);
}
function writeOAuthSessionsAtomic(data) {
const tmp = `${OAUTH_SESSION_FILE}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
let fd = null;
try {
fd = fs.openSync(tmp, 'w', 0o600);
fs.writeFileSync(fd, JSON.stringify(data));
fs.fsyncSync(fd);
fs.closeSync(fd);
fd = null;
fs.renameSync(tmp, OAUTH_SESSION_FILE);
} finally {
if (fd !== null) {
try { fs.closeSync(fd); } catch {}
}
try { fs.rmSync(tmp, { force: true }); } catch {}
}
}
function saveOAuthSessions() {
try {
const data = [];
for (const [sessionId, session] of oauthSessions.entries()) {
const persistedSession = sanitizeOAuthSessionForDisk(session);
if (persistedSession) data.push([sessionId, persistedSession]);
}
writeOAuthSessionsAtomic(data);
} catch (e) {
console.warn('Failed to save OAuth sessions:', e.message);
}
}
function backupCorruptOAuthSessionFile() {
try {
if (!fs.existsSync(OAUTH_SESSION_FILE)) return;
const backup = `${OAUTH_SESSION_FILE}.corrupt.${Date.now()}`;
fs.renameSync(OAUTH_SESSION_FILE, backup);
writeOAuthSessionsAtomic([]);
} catch (error) {
console.warn('Failed to backup corrupt OAuth sessions:', error.message);
}
}
function loadOAuthSessions() {
try {
if (!fs.existsSync(OAUTH_SESSION_FILE)) return;
const parsed = JSON.parse(fs.readFileSync(OAUTH_SESSION_FILE, 'utf8'));
if (!Array.isArray(parsed)) return;
const now = Date.now();
for (const item of parsed) {
if (!Array.isArray(item) || item.length !== 2) continue;
const [sessionId, session] = item;
if (!sessionId || !session || now - Number(session.createdAt || 0) > SESSION_TTL) continue;
const persistedSession = sanitizeOAuthSessionForDisk(session);
if (!persistedSession) continue;
oauthSessions.set(sessionId, persistedSession);
indexOAuthSession(sessionId, persistedSession);
}
} catch (e) {
console.warn('Failed to load OAuth sessions:', e.message);
backupCorruptOAuthSessionFile();
}
}
export function cleanSessions() {
const now = Date.now();
let changed = false;
for (const [sessionId, s] of oauthSessions) {
if (now - Number(s.createdAt || 0) > SESSION_TTL) {
if (s?.state) oauthStateIndex.delete(s.state);
oauthSessions.delete(sessionId);
changed = true;
}
}
if (changed) saveOAuthSessions();
}
loadOAuthSessions();
setInterval(cleanSessions, 60_000).unref();
// --- Loopback callback server ---
let loopbackServer = null;
function shouldStartOAuthLoopbackServer() {
return !isServerlessRuntime();
}
export function resolveRuntimeMode(env = process.env) {
const explicit = String(env.IMAGE_GEN_RUNTIME || env.IMAGE_GEN_DEPLOY_RUNTIME || '').trim().toLowerCase();
if (['node', 'docker', 'local', 'server', 'vps'].includes(explicit)) return 'node';
if (['serverless', 'vercel', 'netlify', 'lambda', 'aws'].includes(explicit)) return 'serverless';
return '';
}
function isServerlessRuntime() {
const runtimeMode = resolveRuntimeMode();
if (runtimeMode === 'node') return false;
if (runtimeMode === 'serverless') return true;
return !!(process.env.VERCEL || process.env.NETLIFY || process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.AWS_EXECUTION_ENV);
}
function ensureLoopbackServer() {
if (loopbackServer) return Promise.resolve();
return new Promise((resolve, reject) => {
loopbackServer = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
if (!req.url.startsWith('/auth/callback')) {
res.writeHead(404);
res.end('Not Found');
return;
}
const url = new URL(req.url, `http://localhost:${OAUTH_LOOPBACK_PORT}`);
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
const error = url.searchParams.get('error');
const { sessionId, session } = getOAuthSessionByState(state);
if (error || !code || !session) {
if (session) {
session.status = 'error';
session.error = error || 'Missing code';
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(renderOAuthLoopbackPage('登录失败', '请关闭此窗口重试。'));
return;
}
try {
session.result = await exchangeOAuthCodeForResult(code, session);
session.status = 'success';
saveOAuthSessions();
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(renderOAuthLoopbackPage('登录成功', '可以关闭此窗口了。'));
} catch (e) {
session.status = 'error';
session.error = e.message;
saveOAuthSessions();
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(renderOAuthLoopbackPage('登录失败', e.message || '请关闭此窗口重试。'));
}
});
loopbackServer.listen(OAUTH_LOOPBACK_PORT, '127.0.0.1', () => {
console.log(`OAuth loopback server on http://127.0.0.1:${OAUTH_LOOPBACK_PORT}`);
resolve();
});
loopbackServer.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.log(`Port ${OAUTH_LOOPBACK_PORT} in use, loopback server skipped`);
loopbackServer = null;
resolve();
} else {
reject(e);
}
});
});
}
export function escapeHtml(value = '') {
return String(value).replace(/[&<>"']/g, (ch) => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
}[ch]));
}
export function renderOAuthLoopbackPage(title, message) {
return [
'<!doctype html>',
'<html><head><meta charset="utf-8"><title>',
escapeHtml(title),
'</title></head><body><h2>',
escapeHtml(title),
'</h2><p>',
escapeHtml(message),
'</p><script>window.close()</script></body></html>',
].join('');
}
// --- Static file serving ---
function serveStatic(req, res) {
let pathname = '/';
try {
pathname = decodeURIComponent(new URL(req.url || '/', 'http://localhost').pathname);
} catch {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Bad Request');
return;
}
if (pathname === '/') pathname = '/index.html';
const segments = pathname.split('/').filter(Boolean);
const blocked = segments.some((segment) => (
segment === '.'
|| segment === '..'
|| segment.startsWith('.')
|| STATIC_DENY_SEGMENTS.has(segment)
|| STATIC_DENY_FILES.has(segment)
));
const filePath = path.resolve(STATIC_ROOT, `.${pathname}`);
const insideStaticRoot = filePath === STATIC_ROOT || filePath.startsWith(`${STATIC_ROOT}${path.sep}`);
if (blocked || !insideStaticRoot) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
let stat = null;
try {
stat = fs.statSync(filePath);
} catch {}
if (!stat || stat.isDirectory()) {
res.writeHead(404);
res.end('Not Found');
return;
}
const ext = path.extname(filePath);
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
fs.createReadStream(filePath).pipe(res);
}
// --- Proxy handler ---
async function handleProxy(req, res) {
const body = await readRequestText(req, res, { limitBytes: IMAGE_JOB_BODY_LIMIT_BYTES });
if (body == null) return;
let parsed;
try { parsed = JSON.parse(body); } catch {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
return;
}
let prepared;
try {
prepared = prepareProxyRequest(parsed, {
allowedHosts: getProxyAllowedHosts({ runtimeConfig: configService.getResolvedConfig() }),
allowLocalHttp: isExplicitLocalDevProxyAllowed(),
allowMultipart: true,
buildMultipartBody: buildProxyMultipartFormData,
});
} catch (e) {
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 400;
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message || 'Proxy request is invalid' }));
return;
}
try {
const result = await runProxyUpstream(prepared, {
onStreamStart: ({ status, contentType }) => res.writeHead(status, {
'Content-Type': contentType || 'text/event-stream',
'Cache-Control': 'no-cache',
}),
onStreamChunk: (chunk) => res.write(chunk),
});
if (result.stream) {
res.end();
} else {
res.writeHead(result.status, {
'Content-Type': result.contentType,
});
res.end(result.body);
}
} catch (e) {
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 502;
if (res.headersSent) {
res.end();
return;
}
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message || 'Proxy upstream request failed' }));
}
}
// --- OAuth route handlers ---
function buildOAuthResult(tokenData, fallbackRefreshToken = null) {
const userInfo = tokenData.id_token ? extractOpenAIUserInfo(tokenData.id_token) : {};
return {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token || fallbackRefreshToken,
expiresIn: tokenData.expires_in || 3600,
email: userInfo.email || '',
name: userInfo.name || userInfo.email || '',
sub: userInfo.sub || '',
accountId: userInfo.accountId || '',
planType: userInfo.planType || '',
};
}
async function exchangeOAuthCodeForResult(code, session) {
const tokenResp = await fetch(OAUTH_TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: OAUTH_CLIENT_ID,
code,
code_verifier: session.codeVerifier,
redirect_uri: session.redirectUri || OAUTH_REDIRECT_URI,
}).toString(),
});
const tokenData = await tokenResp.json().catch(() => ({}));
if (!tokenResp.ok || !tokenData.access_token) {
const err = new Error(formatOAuthTokenError(tokenData, 'Token exchange failed'));
err.status = tokenResp.status || 400;
throw err;
}
return buildOAuthResult(tokenData, null);
}
async function handleOAuthStart(req, res) {
try {
const codeVerifier = makeOAuthCodeVerifier();
const codeChallenge = makeOAuthCodeChallenge(codeVerifier);
const state = crypto.randomBytes(24).toString('base64url');
const createdAt = Date.now();
const session = {
state,
codeVerifier,
redirectUri: OAUTH_REDIRECT_URI,
status: 'pending',
result: null,
error: null,
createdAt,
};
const sessionId = makeStatelessOAuthSessionId(session);
setOAuthSession(sessionId, session);
if (shouldStartOAuthLoopbackServer()) await ensureLoopbackServer();
const params = new URLSearchParams({
client_id: OAUTH_CLIENT_ID,
redirect_uri: OAUTH_REDIRECT_URI,
response_type: 'code',
scope: OAUTH_SCOPES,
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
prompt: 'login',
id_token_add_organizations: 'true',
codex_cli_simplified_flow: 'true',
});
const authorizationUrl = `${OAUTH_AUTH_URL}?${params}`;
writeNoStoreJson(res, 200, { authorizationUrl, sessionId, state, redirectUri: OAUTH_REDIRECT_URI });
} catch (e) {
const message = e?.message || 'OAuth start failed';
console.warn('OAuth start failed:', message);
writeNoStoreJson(res, 500, { error: message });
}
}
function writeNoStoreJson(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
});
res.end(JSON.stringify(body));
}
function handleOAuthStatus(req, res, sessionKey) {
let sessionId = sessionKey;
let session = getOAuthSessionById(sessionId);
if (!session) {
session = getOAuthSessionFromStatelessId(sessionKey);
if (session) sessionId = sessionKey;
}
if (!session) {
writeNoStoreJson(res, 404, { error: 'Session not found' });
return;
}
if (session.status === 'success') {
writeNoStoreJson(res, 200, { status: 'success', result: session.result });
deleteOAuthSession(sessionId);
} else if (session.status === 'error') {
writeNoStoreJson(res, 200, { status: 'error', error: session.error });
deleteOAuthSession(sessionId);
} else {
writeNoStoreJson(res, 200, { status: 'pending' });
}
}
async function handleOAuthExchange(req, res) {
const parsed = await readJsonBody(req, res);
if (!parsed) return;
const callbackInput = parsed.callbackUrl || parsed.code || '';
const sessionId = String(parsed.sessionId || '').trim();
const sessionById = getOAuthSessionById(sessionId) || getOAuthSessionFromStatelessId(sessionId);
const parsedCallback = parseOAuthCallbackInput(callbackInput, parsed.state || sessionById?.state || '');
const code = parsedCallback.code;
const state = parsedCallback.state;
if (!code || !state) {
writeNoStoreJson(res, 400, { error: 'Missing authorization code or state' });
return;
}
let resolvedSessionId = sessionId;
let session = sessionById;
if (!session) {
const found = getOAuthSessionByState(state);
resolvedSessionId = found.sessionId;
session = found.session;
}
if (!session) {
writeNoStoreJson(res, 404, { error: 'Session not found or expired' });
return;
}
if (session.state && state && session.state !== state) {
writeNoStoreJson(res, 400, { error: 'Invalid oauth state' });
return;
}
try {
const result = await exchangeOAuthCodeForResult(code, session);
deleteOAuthSession(resolvedSessionId);
writeNoStoreJson(res, 200, { status: 'success', result });
} catch (e) {
session.lastError = e.message || 'Token exchange failed';
saveOAuthSessions();
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 500;
writeNoStoreJson(res, status, { error: session.lastError });
}
}
async function handleOAuthRefresh(req, res) {
const parsed = await readJsonBody(req, res);
if (!parsed) return;
const { refreshToken } = parsed;
if (!refreshToken) {
writeNoStoreJson(res, 400, { error: 'Missing refreshToken' });
return;
}
try {
const resp = await fetch(OAUTH_TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: OAUTH_CLIENT_ID,
refresh_token: refreshToken,
}).toString(),
});
const data = await resp.json();
if (!resp.ok || !data.access_token) {
writeNoStoreJson(res, resp.status, { error: formatOAuthTokenError(data, 'Refresh failed') });
return;
}
const userInfo = data.id_token ? extractOpenAIUserInfo(data.id_token) : {};
writeNoStoreJson(res, 200, {
accessToken: data.access_token,
refreshToken: data.refresh_token || refreshToken,
expiresIn: data.expires_in || 3600,
email: userInfo.email || '',
name: userInfo.name || userInfo.email || '',
accountId: userInfo.accountId || '',
planType: userInfo.planType || '',
});
} catch (e) {
writeNoStoreJson(res, 500, { error: e.message });
}
}
// --- OAuth image generation handler ---
export function formatSseEvent(event, data) {
return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
}
function payloadTooLargeError(message = '请求体过大') {
const error = new Error(message);
error.status = 413;
return error;
}
async function readRequestText(req, res, { limitBytes = JSON_BODY_LIMIT_BYTES } = {}) {
const declaredLength = Number(req.headers?.['content-length'] || 0);
if (declaredLength > limitBytes) {
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: '请求体过大,请减少参考图数量或换用更小图片' }));
return null;
}
const chunks = [];
let receivedBytes = 0;
for await (const chunk of req) {
receivedBytes += Buffer.byteLength(chunk);
if (receivedBytes > limitBytes) {
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: '请求体过大,请减少参考图数量或换用更小图片' }));
return null;
}
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
}
return Buffer.concat(chunks).toString('utf8');
}
async function readJsonBody(req, res, { limitBytes = JSON_BODY_LIMIT_BYTES, allowEmpty = true, emptyValue = {} } = {}) {
const body = await readRequestText(req, res, { limitBytes });
if (body == null) return null;
if (!String(body).trim()) {
if (allowEmpty) return emptyValue;
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
return null;
}
try {
return JSON.parse(body);
} catch {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
return null;
}
}
function decodedBase64Bytes(base64 = '') {
const clean = String(base64 || '').replace(/\s/g, '');
if (!clean) return 0;
const padding = clean.endsWith('==') ? 2 : (clean.endsWith('=') ? 1 : 0);
return Math.max(0, Math.floor((clean.length * 3) / 4) - padding);
}
function imageDataByteLength(data, fallbackMime = 'image/png') {
const parsed = parseImageInputData(data, fallbackMime);
return decodedBase64Bytes(parsed.base64);
}
function normalizeImageMime(mime = 'image/png') {
const value = String(mime || 'image/png').trim().toLowerCase();
if (value === 'image/jpg') return 'image/jpeg';
return value;
}
function assertImageMimeAllowed(mime = 'image/png') {
const normalized = normalizeImageMime(mime);
if (!ALLOWED_REF_IMAGE_MIME_TYPES.has(normalized)) {
const err = new Error('参考图格式不支持,请上传 PNG、JPEG 或 WebP 图片');
err.status = 400;
throw err;
}
return normalized;
}
function assertImageDataSize(data, { maxBytes = REF_IMAGE_MAX_BYTES, message = '参考图过大,请换用更小图片' } = {}) {
const parsed = parseImageInputData(data);
assertImageMimeAllowed(parsed.mime);
const bytes = decodedBase64Bytes(parsed.base64);
if (bytes > maxBytes) throw payloadTooLargeError(message);
return bytes;
}
function assertRefImagesWithinLimits(images = []) {
let totalBytes = 0;
for (const image of images) {
totalBytes += assertImageDataSize(image);
if (totalBytes > REF_IMAGES_TOTAL_MAX_BYTES) throw payloadTooLargeError('参考图总大小过大,请减少数量或换用更小图片');
}
}
function collectDataImageStrings(value, out = [], depth = 0) {
if (depth > 8 || value == null) return out;
if (typeof value === 'string') {
if (/^data:image\/[^;]+;base64,/i.test(value)) out.push(value);
return out;
}
if (Array.isArray(value)) {
value.forEach((item) => collectDataImageStrings(item, out, depth + 1));
return out;
}
if (typeof value === 'object') {
Object.values(value).forEach((item) => collectDataImageStrings(item, out, depth + 1));
}
return out;
}
function assertEmbeddedDataImagesWithinLimits(value) {
const images = collectDataImageStrings(value);
assertRefImagesWithinLimits(images);
}
async function handleOAuthTest(req, res) {
if (!requireConfigAdmin(req, res)) return;
const parsed = await readJsonBody(req, res);
if (!parsed) return;
try {
const data = await testOAuthAccessToken(parsed);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
} catch (e) {
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 500;
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message || 'OAuth test failed' }));
}
}
async function handleOAuthImages(req, res) {
if (!requireConfigAdmin(req, res)) return;
if (oauthImagesRateLimit(req, res)) return;
const cooldown = checkOAuthCooldown(req);
if (cooldown.cooled) {
oauthCooldownResponse(res, cooldown);
return;
}
const parsed = await readJsonBody(req, res, { limitBytes: IMAGE_JOB_BODY_LIMIT_BYTES });
if (!parsed) return;
try {
assertRefImagesWithinLimits(normalizeRefImages(parsed));
const data = await handleOAuthImageRequestBody(parsed);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
} catch (e) {
applyOAuthCooldown(req, e);
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 500;
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message || 'OAuth image generation failed' }));
}
}
async function handlePromptEnhance(req, res) {
const parsed = await readJsonBody(req, res);
if (!parsed) return;
try {
const result = await enhancePrompt({
...parsed,
allowedHosts: getProxyAllowedHosts({ runtimeConfig: configService.getResolvedConfig() }),
allowLocalHttp: isExplicitLocalDevProxyAllowed(),
});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (e) {
const status = e.status && e.status >= 400 && e.status < 600 ? e.status : 400;
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message || 'Prompt enhancement failed' }));
}
}
async function handleOAuthImagesStream(req, res) {
if (!requireConfigAdmin(req, res)) return;
if (oauthImagesRateLimit(req, res)) return;
const cooldown = checkOAuthCooldown(req);
if (cooldown.cooled) {
oauthCooldownResponse(res, cooldown);
return;
}
const parsed = await readJsonBody(req, res, { limitBytes: IMAGE_JOB_BODY_LIMIT_BYTES });
if (!parsed) return;
try {
assertRefImagesWithinLimits(normalizeRefImages(parsed));
} catch (e) {