-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1650 lines (1460 loc) · 76.3 KB
/
Copy pathserver.js
File metadata and controls
1650 lines (1460 loc) · 76.3 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 express = require('express');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const session = require('express-session');
const { execSync } = require('child_process');
const app = express();
// Auth config
const ADMIN_USER = process.env.ADMIN_USER || 'admin';
const ADMIN_PASS = process.env.ADMIN_PASS || 'admin';
const LOGIN_REQUIRED = process.env.LOGIN_REQUIRED !== 'false' && process.env.DISABLE_LOGIN !== 'true';
const API_AUTH_REQUIRED = process.env.API_AUTH_REQUIRED !== 'false';
const ALLOW_LOCAL_URL_OVERRIDE = process.env.ALLOW_LOCAL_URL_OVERRIDE !== 'false';
const DEFAULT_A1111_URL = 'http://127.0.0.1:7860';
const DEFAULT_COMFYUI_URL = 'http://127.0.0.1:8188';
const DEFAULT_GPT_IMAGE_URL = 'https://api.openai.com/v1/images/generations';
const DEFAULT_POLLINATIONS_IMAGE_URL = 'https://gen.pollinations.ai/v1/images/generations';
const DEFAULT_NOVELAI_IMAGE_URL = 'https://image.novelai.net/ai/generate-image';
const DEFAULT_GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com';
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '0:0:0:0:0:0:0:1']);
const MODEL_PROXY_ALLOWED_HOSTS = new Set(
String(process.env.MODEL_PROXY_ALLOWED_HOSTS || '')
.split(',')
.map(v => v.trim().toLowerCase())
.filter(Boolean)
);
app.use(express.json({ limit: '100mb' }));
app.use(session({ secret: process.env.SESSION_SECRET || 'sd-proxy-secret', resave: false, saveUninitialized: false }));
if (!process.env.SESSION_SECRET) {
console.warn('SESSION_SECRET is not set. Using default secret is insecure outside local development.');
}
if (!LOGIN_REQUIRED) {
console.warn('LOGIN_REQUIRED=false or DISABLE_LOGIN=true. The web UI and API routes are not login-protected.');
}
if (!API_AUTH_REQUIRED) {
console.warn('API_AUTH_REQUIRED=false. /api/* endpoints are publicly accessible.');
}
if (!ALLOW_LOCAL_URL_OVERRIDE) {
console.warn('ALLOW_LOCAL_URL_OVERRIDE=false. x-local-url headers are ignored.');
}
function resolveLocalUrl(headerValue, fallbackUrl) {
if (!ALLOW_LOCAL_URL_OVERRIDE) return fallbackUrl;
const raw = String(headerValue || '').trim();
if (!raw) return fallbackUrl;
try {
const parsed = new URL(raw);
if (!['http:', 'https:'].includes(parsed.protocol)) return fallbackUrl;
if (!LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return fallbackUrl;
parsed.hash = '';
parsed.search = '';
return parsed.toString().replace(/\/+$/, '');
} catch {
return fallbackUrl;
}
}
function isPrivateHostname(hostname) {
const host = String(hostname || '').toLowerCase();
if (!host) return true;
if (host === 'localhost' || host === '::1' || host === '0:0:0:0:0:0:0:1') return true;
if (host.endsWith('.local')) return true;
if (host.startsWith('127.') || host.startsWith('10.') || host.startsWith('192.168.') || host.startsWith('169.254.')) return true;
const m = host.match(/^172\.(\d{1,3})\./);
if (m) {
const octet = Number(m[1]);
if (octet >= 16 && octet <= 31) return true;
}
if (host.startsWith('fc') || host.startsWith('fd') || host.startsWith('fe80:')) return true;
return false;
}
function getBearerToken(headers) {
const auth = String(headers.authorization || headers.Authorization || '').trim();
const match = auth.match(/^Bearer\s+(.+)$/i);
return (match ? match[1] : auth).trim();
}
function resolveProviderEndpoint(rawUrl, defaultUrl, endpointPath) {
const raw = String(rawUrl || '').trim();
if (!raw) return defaultUrl;
let parsed;
try {
parsed = new URL(raw);
} catch {
throw new Error('Invalid reverse proxy URL');
}
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Reverse proxy URL must use http or https');
}
parsed.hash = '';
const cleanPath = parsed.pathname.replace(/\/+$/, '');
const cleanEndpoint = endpointPath.replace(/\/+$/, '');
if (!cleanPath.endsWith(cleanEndpoint)) {
let suffix = cleanEndpoint.replace(/^\/+/, '');
const firstSegment = suffix.split('/')[0];
if (firstSegment && cleanPath.endsWith(`/${firstSegment}`)) {
suffix = suffix.slice(firstSegment.length).replace(/^\/+/, '');
}
parsed.pathname = `${cleanPath}/${suffix}`.replace(/\/{2,}/g, '/');
}
return parsed.toString();
}
function resolveGeminiEndpoint(rawUrl, model, apiKey) {
const endpointPath = `/v1beta/models/${encodeURIComponent(model)}:generateContent`;
const url = new URL(resolveProviderEndpoint(rawUrl, `${DEFAULT_GEMINI_BASE_URL}${endpointPath}`, endpointPath));
if (apiKey && !url.searchParams.has('key')) url.searchParams.set('key', apiKey);
return url.toString();
}
function normalizeImageData(data) {
const rawImages = data?.data || data?.images || data?.output || [];
const images = Array.isArray(rawImages) ? rawImages : [rawImages];
return images.map(img => {
if (!img) return null;
if (typeof img === 'string') {
if (/^https?:\/\//i.test(img) || img.startsWith('data:')) return { url: img };
return { b64_json: img };
}
return {
url: img.url || img.image_url?.url || img.uri || img.src,
b64_json: img.b64_json || img.base64 || img.data
};
}).filter(img => img && (img.url || img.b64_json));
}
// Auth middleware
function auth(req, res, next) {
if (!LOGIN_REQUIRED) return next();
if (req.session.loggedIn) return next();
if (req.method === 'OPTIONS') return next();
if (req.path === '/login' || req.path === '/logout') return next();
if (req.path.startsWith('/api/')) {
const isPublicApi =
req.path === '/api/session' ||
req.path.startsWith('/api/progress/') ||
req.path.startsWith('/api/logs/');
if (!API_AUTH_REQUIRED || isPublicApi) return next();
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
res.header('Access-Control-Allow-Methods', '*');
return res.status(401).json({ error: 'Authentication required' });
}
res.redirect('/login');
}
// Shared app icon
const FAVICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#0b1410"/><circle cx="32" cy="32" r="20" fill="#4fd18b"/><path d="M22 38c5 4 15 4 20 0M22 27h20" stroke="#0b1410" stroke-width="5" stroke-linecap="round" fill="none"/></svg>';
app.get('/favicon.svg', (req, res) => res.type('image/svg+xml').send(FAVICON_SVG));
app.get('/favicon.ico', (req, res) => res.type('image/svg+xml').send(FAVICON_SVG));
// Login page
app.get('/login', (req, res) => {
if (!LOGIN_REQUIRED) return res.redirect('/');
res.send(`
<!DOCTYPE html><html><head><title>Login - SD Proxy</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<style>
*{box-sizing:border-box}body{--font-ui:"Avenir Next","Segoe UI","Helvetica Neue","Trebuchet MS",sans-serif;--color-bg:#0b1410;--color-surface:#12201a;--color-surface-2:#182a23;--color-border:#2c4b3e;--color-text:#deeee2;--color-text-muted:#8eb6a1;--color-accent:#4fd18b;--color-accent-2:#8ce0b9;--color-danger:#e0626f;--focus-ring:0 0 0 2px rgba(79,209,139,.5);font-family:var(--font-ui);background:radial-gradient(900px 560px at 15% -10%,rgba(79,209,139,.18),transparent 65%),radial-gradient(850px 540px at 100% 0,rgba(239,179,102,.12),transparent 70%),var(--color-bg);color:var(--color-text);display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;padding:20px}.card{background:linear-gradient(180deg,color-mix(in srgb,var(--color-surface) 94%,var(--color-accent)),var(--color-surface));padding:24px;border-radius:10px;width:100%;max-width:360px;border:1px solid var(--color-border);box-shadow:0 1px 2px rgba(0,0,0,.25)}h1{margin:0 0 20px;text-align:center;color:var(--color-accent-2);font-size:20px;letter-spacing:.02em}.login-label{display:block;margin:10px 0 4px;color:var(--color-text-muted);font-size:11px;font-weight:600;letter-spacing:.02em}input{width:100%;padding:10px;background:var(--color-bg);border:1px solid var(--color-border);border-radius:6px;color:var(--color-text);font-size:13px}input::placeholder{color:color-mix(in srgb,var(--color-text-muted) 75%,transparent)}input:focus{outline:none;border-color:var(--color-accent);box-shadow:var(--focus-ring)}button{width:100%;min-height:42px;padding:10px 12px;background:var(--color-accent);border:1px solid var(--color-accent);border-radius:6px;color:var(--color-bg);font-size:13px;font-weight:700;cursor:pointer;margin-top:16px;transition:background-color .15s ease,transform .12s ease}button:hover{background:var(--color-accent-2)}button:active{transform:translateY(1px)}button:focus-visible{outline:none;box-shadow:var(--focus-ring)}.error{color:var(--color-danger);text-align:center;margin:12px 0 0;font-size:12px}@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}</style></head>
<body><div class="card"><h1>🎨 SD Proxy</h1><form method="POST" action="/login">
<label class="login-label" for="login-user">Username</label>
<input id="login-user" name="user" placeholder="Username" autocomplete="username" required>
<label class="login-label" for="login-pass">Password</label>
<input id="login-pass" name="pass" type="password" placeholder="Password" autocomplete="current-password" required>
<button type="submit">Login</button>
${req.query.error ? '<p class="error" role="alert">Invalid credentials</p>' : ''}
</form></div></body></html>`);
});
app.post('/login', express.urlencoded({ extended: true }), (req, res) => {
if (!LOGIN_REQUIRED) return res.redirect('/');
if (req.body.user === ADMIN_USER && req.body.pass === ADMIN_PASS) {
req.session.loggedIn = true;
res.redirect('/');
} else res.redirect('/login?error=1');
});
app.get('/logout', (req, res) => {
if (!LOGIN_REQUIRED) return res.redirect('/');
req.session.destroy();
res.redirect('/login');
});
function requireAuth(req, res, next) {
if (!LOGIN_REQUIRED) return next();
if (req.session.loggedIn) return next();
res.status(401).json({ error: 'Authentication required' });
}
app.use(auth);
app.use(express.static('public'));
// Data storage
const MODELS_DIR = path.join(__dirname, 'models');
[MODELS_DIR].forEach(d => fs.existsSync(d) || fs.mkdirSync(d));
let queue = [], currentGeneration = null;
function safeFilename(name, fallback = 'model.safetensors') {
const raw = String(name || '').trim();
const base = path.basename(raw).replace(/[^a-zA-Z0-9._-]/g, '_');
return base || fallback;
}
// SSE clients
const sseClients = new Map();
// CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
res.header('Access-Control-Allow-Methods', '*');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
// Serve dashboard
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));
// Session endpoint - get unique session ID
app.get('/api/session', (req, res) => {
const sessionId = crypto.randomUUID();
res.json({ sessionId });
});
// SSE endpoints
app.get('/api/progress/:sessionId', (req, res) => {
const { sessionId } = req.params;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
if (!sseClients.has(sessionId)) sseClients.set(sessionId, {});
sseClients.get(sessionId).progress = res;
req.on('close', () => { const c = sseClients.get(sessionId); if (c) { delete c.progress; if (!Object.keys(c).length) sseClients.delete(sessionId); } });
});
app.get('/api/logs/:sessionId', (req, res) => {
const { sessionId } = req.params;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
if (!sseClients.has(sessionId)) sseClients.set(sessionId, {});
sseClients.get(sessionId).logs = res;
req.on('close', () => { const c = sseClients.get(sessionId); if (c) { delete c.logs; if (!Object.keys(c).length) sseClients.delete(sessionId); } });
});
function sendProgress(sessionId, data) {
const client = sseClients.get(sessionId);
if (client?.progress) client.progress.write(`data: ${JSON.stringify(data)}\n\n`);
}
function log(sessionId, message, level = 'info') {
const entry = `[${new Date().toISOString()}] [${level.toUpperCase()}] ${message}`;
console.log(entry);
const client = sseClients.get(sessionId);
if (client?.logs) client.logs.write(`data: ${JSON.stringify({ message, level })}\n\n`);
}
// Prompt matrix expansion: [a|b] [c|d] -> 4 prompts
function expandMatrix(prompt) {
const matches = prompt.match(/\[([^\]]+)\]/g);
if (!matches) return [prompt];
const options = matches.map(m => m.slice(1, -1).split('|'));
const combinations = options.reduce((acc, opts) => acc.flatMap(a => opts.map(o => [...a, o])), [[]]);
return combinations.map(combo => {
let result = prompt;
matches.forEach((m, i) => { result = result.replace(m, combo[i]); });
return result;
});
}
// Wildcard expansion: {a|b|c} -> random pick
function expandWildcards(text) {
return text.replace(/\{([^}]+)\}/g, (m, p) => {
const opts = p.split('|');
return opts[Math.floor(Math.random() * opts.length)];
});
}
// Backend handlers
const A1111_SAMPLERS = { euler_ancestral: 'Euler a', euler: 'Euler', dpmpp_2m: 'DPM++ 2M', dpmpp_2m_sde: 'DPM++ 2M SDE', dpmpp_2s_ancestral: 'DPM++ 2S a', dpmpp_sde: 'DPM++ SDE', dpm_2: 'DPM2', dpm_2_ancestral: 'DPM2 a', heun: 'Heun', lms: 'LMS', ddim: 'DDIM', ddpm: 'DDPM', uni_pc: 'UniPC', lcm: 'LCM' };
const backends = {
async local(body, headers, sessionId) {
const url = resolveLocalUrl(headers['x-local-url'], DEFAULT_A1111_URL);
const sampler = A1111_SAMPLERS[body.sampler] || body.sampler || 'DPM++ 2M';
const samplerName = body.scheduler === 'karras' ? sampler + ' Karras' : body.scheduler === 'exponential' ? sampler + ' Exponential' : sampler;
const payload = {
prompt: expandWildcards(body.prompt), negative_prompt: body.negative_prompt || '',
width: body.width || 512, height: body.height || 768, steps: body.steps || 25,
cfg_scale: body.cfg_scale || 7, sampler_name: samplerName, seed: body.seed ?? -1,
batch_size: body.n || 1, restore_faces: body.face_restore || false, tiling: body.tiling || false
};
// Hires fix
if (body.hires_fix) {
payload.enable_hr = true;
payload.hr_scale = body.hires_scale || 1.5;
payload.hr_upscaler = body.hires_upscaler || 'Latent';
payload.denoising_strength = body.denoising_strength || 0.7;
payload.hr_second_pass_steps = body.hr_second_pass_steps || 0;
}
// ControlNet
if (body.controlnet) {
payload.alwayson_scripts = {
controlnet: {
args: [{
enabled: true,
module: body.controlnet.preprocessor || 'none',
model: body.controlnet.model || 'control_v11p_sd15_canny',
weight: body.controlnet.weight || 1,
image: body.controlnet.image,
guidance_start: body.controlnet.guidance_start || 0,
guidance_end: body.controlnet.guidance_end || 1
}]
}
};
}
// IP-Adapter Face - extract facial features only from reference image
if (body.ip_adapter) {
payload.alwayson_scripts = payload.alwayson_scripts || {};
payload.alwayson_scripts.controlnet = {
args: [{
enabled: true,
module: "ip-adapter_face_id",
model: body.ip_adapter.model || "ip-adapter-faceid-portrait_sd15",
weight: body.ip_adapter.weight || 0.7,
image: body.ip_adapter.image,
resize_mode: "Crop and Resize",
control_mode: "Balanced",
pixel_perfect: true
}]
};
log(sessionId, `IP-Adapter Face: model=${body.ip_adapter.model}, weight=${body.ip_adapter.weight}`);
}
// Regional prompting (via BREAK keyword)
if (body.regional_prompts?.length) {
payload.prompt = body.regional_prompts.map(r => r.prompt).join(' BREAK ');
}
// Img2Img
if (body.init_image && !body.mask) {
payload.init_images = [body.init_image];
payload.denoising_strength = body.strength || 0.75;
payload.resize_mode = body.resize_mode || 0;
const res = await fetch(`${url}/sdapi/v1/img2img`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
return { data: (data.images || []).map(b64 => ({ b64_json: b64 })), info: data.info };
}
// Inpainting
if (body.mask) {
payload.init_images = [body.init_image];
payload.mask = body.mask;
payload.inpainting_fill = body.inpaint_fill ?? 1;
payload.inpaint_full_res = body.inpaint_full_res ?? true;
payload.inpaint_full_res_padding = body.inpaint_padding || 32;
payload.denoising_strength = body.strength || 0.75;
const res = await fetch(`${url}/sdapi/v1/img2img`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
return { data: (data.images || []).map(b64 => ({ b64_json: b64 })), info: data.info };
}
// Outpainting
if (body.outpaint) {
payload.init_images = [body.init_image];
payload.script_name = 'outpainting mk2';
payload.script_args = [body.outpaint.pixels || 128, body.outpaint.direction || 'left,right,up,down'];
const res = await fetch(`${url}/sdapi/v1/img2img`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
return { data: (data.images || []).map(b64 => ({ b64_json: b64 })), info: data.info };
}
// Track progress
currentGeneration = { backend: 'local', startTime: Date.now() };
const progressInterval = setInterval(async () => {
try {
const progRes = await fetch(`${url}/sdapi/v1/progress`);
const prog = await progRes.json();
sendProgress(sessionId, { type: 'generation', progress: prog.progress, eta: prog.eta_relative, preview: prog.current_image });
} catch { /* progress poll — expected to fail between requests */ }
}, 1000);
try {
const res = await fetch(`${url}/sdapi/v1/txt2img`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
return { data: (data.images || []).map(b64 => ({ b64_json: b64 })), info: data.info };
} finally {
clearInterval(progressInterval);
currentGeneration = null;
sendProgress(sessionId, { type: 'generation', progress: 1, done: true });
}
},
async comfyui(body, headers, sessionId) {
const url = resolveLocalUrl(headers['x-local-url'], DEFAULT_COMFYUI_URL);
// Sampler mapping
const comfySamplerMap = {
'euler_ancestral': 'euler_ancestral', 'euler_a': 'euler_ancestral', 'Euler a': 'euler_ancestral',
'euler': 'euler', 'Euler': 'euler',
'dpmpp_2m': 'dpmpp_2m', 'DPM++ 2M': 'dpmpp_2m', 'DPM++ 2M Karras': 'dpmpp_2m',
'dpmpp_sde': 'dpmpp_sde', 'DPM++ SDE': 'dpmpp_sde', 'DPM++ SDE Karras': 'dpmpp_sde',
'ddim': 'ddim', 'DDIM': 'ddim',
'lms': 'lms', 'heun': 'heun', 'uni_pc': 'uni_pc'
};
const comfySchedulerMap = {
'euler_ancestral': 'normal', 'euler_a': 'normal', 'Euler a': 'normal',
'dpmpp_2m': 'karras', 'DPM++ 2M Karras': 'karras',
'dpmpp_sde': 'karras', 'DPM++ SDE Karras': 'karras'
};
const seed = body.seed > 0 ? body.seed : Math.floor(Math.random() * 999999999);
const samplerName = comfySamplerMap[body.sampler] || 'euler_ancestral';
const schedulerName = comfySchedulerMap[body.sampler] || 'normal';
const denoise = body.denoise ?? 1.0;
const clipSkip = body.clip_skip ?? 1;
const model = body.model || 'model.safetensors';
let workflow;
// Check for custom workflow
if (body.workflow) {
workflow = typeof body.workflow === 'string' ? JSON.parse(body.workflow) : body.workflow;
// Replace placeholders in workflow
const replacements = {
'%prompt%': body.prompt || '',
'%negative%': body.negative_prompt || '',
'%seed%': String(seed),
'%width%': String(body.width || 512),
'%height%': String(body.height || 768),
'%steps%': String(body.steps || 25),
'%cfg%': String(body.cfg_scale || 7),
'%denoise%': String(denoise),
'%clip_skip%': String(clipSkip),
'%sampler%': samplerName,
'%scheduler%': schedulerName,
'%model%': model
};
const replaceInObj = (obj) => {
for (const key in obj) {
if (typeof obj[key] === 'string') {
for (const [placeholder, value] of Object.entries(replacements)) {
obj[key] = obj[key].split(placeholder).join(value);
}
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
replaceInObj(obj[key]);
}
}
};
replaceInObj(workflow);
log(sessionId, `ComfyUI: Using custom workflow with ${Object.keys(workflow).length} nodes`);
} else {
// Default workflow
workflow = {
"3": {
class_type: "KSampler",
inputs: {
seed: seed,
steps: body.steps || 25,
cfg: body.cfg_scale || 7,
sampler_name: samplerName,
scheduler: schedulerName,
denoise: denoise,
model: ["4", 0],
positive: ["6", 0],
negative: ["7", 0],
latent_image: ["5", 0]
}
},
"4": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: model } },
"5": { class_type: "EmptyLatentImage", inputs: { width: body.width || 512, height: body.height || 768, batch_size: 1 } },
"6": { class_type: "CLIPTextEncode", inputs: { text: body.prompt || '', clip: clipSkip > 1 ? ["10", 0] : ["4", 1] } },
"7": { class_type: "CLIPTextEncode", inputs: { text: body.negative_prompt || '', clip: clipSkip > 1 ? ["10", 0] : ["4", 1] } },
"8": { class_type: "VAEDecode", inputs: { samples: ["3", 0], vae: ["4", 2] } },
"9": { class_type: "SaveImage", inputs: { filename_prefix: "sdproxy", images: ["8", 0] } }
};
if (clipSkip > 1) {
workflow["10"] = { class_type: "CLIPSetLastLayer", inputs: { stop_at_clip_layer: -clipSkip, clip: ["4", 1] } };
}
log(sessionId, `ComfyUI: Using default workflow - sampler=${samplerName}, scheduler=${schedulerName}, steps=${body.steps || 25}, cfg=${body.cfg_scale || 7}, denoise=${denoise}, clip_skip=${clipSkip}`);
}
const queueRes = await fetch(`${url}/prompt`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt: workflow })
});
const queueData = await queueRes.json();
if (!queueData.prompt_id) throw new Error(queueData.error || 'Failed to queue workflow');
log(sessionId, `ComfyUI: Queued as ${queueData.prompt_id}`);
// Poll for completion
for (let i = 0; i < 300; i++) {
await new Promise(r => setTimeout(r, 1000));
const histRes = await fetch(`${url}/history/${queueData.prompt_id}`);
const hist = await histRes.json();
const result = hist[queueData.prompt_id];
if (result?.outputs) {
// Find any SaveImage/PreviewImage outputs
const images = [];
for (const nodeId in result.outputs) {
const output = result.outputs[nodeId];
if (output.images?.length) {
for (const img of output.images) {
images.push({ url: `${url}/view?filename=${encodeURIComponent(img.filename)}&subfolder=${encodeURIComponent(img.subfolder || '')}&type=${img.type || 'output'}` });
}
}
}
if (images.length) {
log(sessionId, `ComfyUI: Got ${images.length} images`);
return { data: images };
}
}
}
throw new Error('Timeout waiting for ComfyUI');
},
async pollinations(body) {
const seed = body.seed > 0 ? body.seed : Math.floor(Math.random() * 999999);
const params = new URLSearchParams({ width: body.width || 512, height: body.height || 768, seed, nologo: 'true' });
if (body.model) params.set('model', body.model);
const url = `https://image.pollinations.ai/prompt/${encodeURIComponent(body.prompt)}?${params}`;
return { data: [{ url }] };
},
async pollinations_paid(body, headers, sessionId) {
const apiKey = getBearerToken(headers);
if (!apiKey) throw new Error('Pollinations (Paid) requires API key');
const payload = {
prompt: body.prompt,
model: body.model || 'flux',
n: 1,
size: `${body.width || 1024}x${body.height || 1024}`,
response_format: 'b64_json'
};
if (body.seed != null && +body.seed >= 0) payload.seed = +body.seed;
if (body.reference_images?.length) payload.image = body.reference_images;
log(sessionId, `Pollinations paid request: model=${payload.model}, size=${payload.size}`);
const res = await fetch(DEFAULT_POLLINATIONS_IMAGE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify(payload)
});
const data = await res.json();
if (!res.ok) throw new Error(data.error?.message || data.error || `Pollinations error ${res.status}`);
const images = normalizeImageData(data);
if (!images.length) throw new Error(JSON.stringify(data));
return { data: images };
},
async gptimage(body, headers, sessionId) {
const apiKey = getBearerToken(headers);
if (!apiKey) throw new Error('GPT Image requires API key');
const opts = body.gptimage || {};
const endpoint = resolveProviderEndpoint(headers['x-gpt-image-proxy-url'], DEFAULT_GPT_IMAGE_URL, '/v1/images/generations');
const payload = {
model: opts.model || body.model || 'gpt-image-2',
prompt: body.prompt,
n: Math.min(body.n || 1, 4)
};
if (opts.size && opts.size !== 'auto') payload.size = opts.size;
if (opts.quality && opts.quality !== 'auto') payload.quality = opts.quality;
if (opts.background && opts.background !== 'auto') payload.background = opts.background;
log(sessionId, `GPT Image request: model=${payload.model}, endpoint=${endpoint}`);
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify(payload)
});
const data = await res.json();
if (!res.ok) throw new Error(data.error?.message || data.error || `GPT Image error ${res.status}`);
const images = normalizeImageData(data);
if (!images.length) throw new Error(JSON.stringify(data));
return { data: images };
},
async nanogpt(body, headers) {
const apiKey = headers.authorization?.replace('Bearer ', '');
if (!apiKey) throw new Error('NanoGPT requires API key');
const res = await fetch('https://nano-gpt.com/api/v1/images/generations', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({ prompt: body.prompt, model: body.model || 'flux-schnell', n: body.n || 1 })
});
return await res.json();
},
async novelai(body, headers, sessionId) {
const apiKey = getBearerToken(headers);
if (!apiKey) throw new Error('NovelAI requires API key');
const nai = body.nai || {};
const model = nai.model || 'nai-diffusion-4-5-curated';
const endpoint = resolveProviderEndpoint(headers['x-novelai-proxy-url'], DEFAULT_NOVELAI_IMAGE_URL, '/ai/generate-image');
const params = {
width: body.width || 832,
height: body.height || 1216,
n_samples: body.n || 1,
seed: body.seed ?? Math.floor(Math.random() * 2147483647),
sampler: nai.sampler || 'k_euler_ancestral',
steps: nai.steps || 28,
scale: nai.scale || 5,
cfg_rescale: nai.cfg_rescale || 0,
noise_schedule: nai.noise_schedule || 'native',
uc_preset: nai.uc_preset ?? 0,
uncond_scale: nai.uncond_scale || 1,
negative_prompt: body.negative_prompt || '',
sm: nai.smea || false,
sm_dyn: nai.smea_dyn || false,
decrisper: nai.decrisper || false,
quality_toggle: nai.quality_toggle !== false,
variety_plus: nai.variety_plus || false
};
log(sessionId, `NovelAI request: model=${model}, ${params.width}x${params.height}, steps=${params.steps}`);
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
input: body.prompt,
model: model,
action: 'generate',
parameters: params
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(`NovelAI error ${res.status}: ${errText}`);
}
const contentType = res.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
const data = await res.json();
const images = normalizeImageData(data);
if (!images.length) throw new Error(JSON.stringify(data));
log(sessionId, `NovelAI returned ${images.length} image(s)`);
return { data: images };
}
// NovelAI returns a zip file with PNG images
const zipBuffer = await res.arrayBuffer();
const bytes = new Uint8Array(zipBuffer);
// Find PNG signatures in the zip
const images = [];
for (let i = 0; i < bytes.length - 8; i++) {
if (bytes[i] === 0x89 && bytes[i + 1] === 0x50 && bytes[i + 2] === 0x4E && bytes[i + 3] === 0x47) {
// Find PNG end
let end = i + 8;
while (end < bytes.length - 8) {
if (bytes[end] === 0x49 && bytes[end + 1] === 0x45 && bytes[end + 2] === 0x4E && bytes[end + 3] === 0x44) {
end += 8; // Include IEND chunk
break;
}
end++;
}
const pngData = bytes.slice(i, end);
const b64 = Buffer.from(pngData).toString('base64');
images.push({ b64_json: b64 });
i = end - 1;
}
}
log(sessionId, `NovelAI returned ${images.length} image(s)`);
return { data: images };
},
async gemini(body, headers, sessionId) {
const apiKey = getBearerToken(headers);
if (!apiKey) throw new Error('Gemini requires API key');
const opts = body.gemini || {};
const model = opts.model || 'gemini-2.5-flash-image';
const endpoint = resolveGeminiEndpoint(headers['x-gemini-proxy-url'], model, apiKey);
const reqHeaders = { 'Content-Type': 'application/json' };
if (headers['x-gemini-proxy-url']) reqHeaders['Authorization'] = `Bearer ${apiKey}`;
// Build parts array with reference images and prompt
const parts = [];
if (body.reference_images?.length) {
log(sessionId, `Adding ${body.reference_images.length} reference images`);
for (const img of body.reference_images) {
const match = img.match(/^data:([^;]+);base64,(.+)$/);
if (match) {
parts.push({ inlineData: { mimeType: match[1], data: match[2] } });
}
}
}
parts.push({ text: body.prompt });
log(sessionId, `Gemini request: model=${model}, prompt=${(body.prompt || '').substring(0, 50)}...`);
const res = await fetch(endpoint, {
method: 'POST',
headers: reqHeaders,
body: JSON.stringify({
contents: [{ role: 'user', parts }],
generationConfig: {
responseModalities: ['TEXT', 'IMAGE'],
...(opts.aspect_ratio && { aspectRatio: opts.aspect_ratio })
}
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(`Gemini error ${res.status}: ${errText}`);
}
const data = await res.json();
const images = [];
for (const candidate of data.candidates || []) {
for (const part of candidate.content?.parts || []) {
if (part.inlineData?.data) {
images.push({ b64_json: part.inlineData.data });
}
}
}
log(sessionId, `Gemini returned ${images.length} image(s)`);
return { data: images };
},
async naistera(body, headers, sessionId) {
const apiKey = headers.authorization?.replace('Bearer ', '');
if (!apiKey) throw new Error('Naistera requires API token');
const opts = body.naistera || {};
const n = body.n || 1;
const varietyWords = ['', ', detailed', ', beautiful', ', stunning', ', elegant', ', graceful', ', vibrant', ', atmospheric'];
// Limit prompt length to prevent timeouts (Naistera seems to struggle with very long prompts)
const maxPromptLength = 500;
let basePrompt = body.prompt;
if (basePrompt.length > maxPromptLength) {
basePrompt = basePrompt.substring(0, maxPromptLength).trim();
log(sessionId, `Naistera prompt truncated to ${maxPromptLength} chars`);
}
// Generate all requests with staggered timing to avoid 409 errors
const results = [];
for (let i = 0; i < Math.min(n, 4); i++) {
let variedPrompt = basePrompt;
if (n > 1) {
const variety = varietyWords[i % varietyWords.length];
variedPrompt = basePrompt + variety;
}
const params = new URLSearchParams({ token: apiKey });
if (opts.aspect_ratio) params.set('aspect_ratio', opts.aspect_ratio);
if (opts.preset) params.set('preset', opts.preset);
// Add aggressive cache-busting with random component
const timestamp = Date.now();
const random = Math.random().toString(36).substring(2);
params.set('_t', `${timestamp}_${i}_${random}`);
params.set('_nocache', '1');
const url = `https://naistera.org/prompt/${encodeURIComponent(variedPrompt)}?${params}`;
log(sessionId, `Naistera request ${i + 1}: ${url.substring(0, 80)}...`);
// Add delay between requests to avoid rate limiting (409 errors)
if (i > 0) {
await new Promise(resolve => setTimeout(resolve, 2000)); // 2 second delay
log(sessionId, `Naistera: waited 2s before request ${i + 1}`);
}
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
log(sessionId, `Naistera request ${i + 1} timed out after 2 minutes`);
}, 120000); // 2 minutes
try {
const res = await fetch(url, {
signal: controller.signal,
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
'User-Agent': `SDProxy-${timestamp}-${random}`
}
});
clearTimeout(timeoutId);
if (!res.ok) {
if (res.status === 409) {
throw new Error(`Naistera rate limit (409) - try reducing batch size or waiting longer between requests`);
}
throw new Error(`Naistera error: ${res.status}`);
}
const buffer = await res.arrayBuffer();
const b64 = Buffer.from(buffer).toString('base64');
results.push({ b64_json: b64 });
log(sessionId, `Naistera request ${i + 1} completed successfully`);
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error(`Naistera request ${i + 1} was aborted (timeout)`);
}
throw error;
}
}
log(sessionId, `Naistera returned ${results.length} images`);
return { data: results };
},
async civitai(body, headers, sessionId) {
const apiKey = headers.authorization?.replace('Bearer ', '');
if (!apiKey) throw new Error('CivitAI requires API token');
const opts = body.civitai || {};
const input = {
model: opts.model || 'urn:air:sd1:checkpoint:civitai:4201@130072',
params: {
prompt: body.prompt,
negativePrompt: body.negative_prompt,
scheduler: opts.scheduler || 'EulerA',
steps: body.steps || 20,
cfgScale: body.cfg_scale || 7,
width: body.width || 512,
height: body.height || 512,
seed: body.seed || -1,
clipSkip: opts.clipSkip || 2
},
batchSize: body.n || 1
};
if (opts.additionalNetworks) {
input.additionalNetworks = opts.additionalNetworks;
}
log(sessionId, `CivitAI request: model=${input.model.split(':').pop()}, ${input.params.width}x${input.params.height}`);
// Use CivitAI's actual generation endpoint
const res = await fetch('https://civitai.com/api/v1/consumer/jobs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
$type: 'textToImage',
input
})
});
if (!res.ok) {
const error = await res.text();
throw new Error(`CivitAI error: ${res.status} - ${error}`);
}
const data = await res.json();
const jobToken = data.token;
if (!jobToken) throw new Error(`No job token returned. Response: ${JSON.stringify(data)}`);
log(sessionId, `CivitAI job started: ${jobToken}`);
// Poll for completion (10 minute timeout)
let lastError = null;
for (let i = 0; i < 120; i++) {
await new Promise(r => setTimeout(r, 5000)); // 5 second intervals
const statusRes = await fetch(`https://civitai.com/api/v1/consumer/jobs?token=${jobToken}`, {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
if (!statusRes.ok) {
lastError = `Status check failed: ${statusRes.status}`;
log(sessionId, `CivitAI poll error: ${statusRes.status}`, 'warn');
continue;
}
const jobs = await statusRes.json();
const job = jobs?.[0];
if (!job) {
lastError = 'No job found in response';
continue;
}
if (job.result?.blobUrl) {
log(sessionId, `CivitAI completed: ${jobToken}`);
return {
data: [{
url: job.result.blobUrl,
b64_json: null
}]
};
}
if (job.scheduled === false && !job.result) {
throw new Error(`CivitAI generation failed: ${job.message || 'Unknown error'}`);
}
}
throw new Error(`CivitAI timeout (10 minutes). Last error: ${lastError || 'Still processing'}`);
},
async pixai(body, headers, sessionId) {
const apiKey = headers.authorization?.replace('Bearer ', '');
if (!apiKey) throw new Error('PixAI requires API key');
const opts = body.pixai || {};
const params = {
prompts: body.prompt,
modelId: opts.modelId || '1648918127446573124',
width: body.width || 768,
height: body.height || 1280,
batchSize: Math.min(body.n || 1, 4)
};
// Core params
if (body.negative_prompt) params.negativePrompts = body.negative_prompt;
if (body.steps) params.samplingSteps = body.steps;
if (body.cfg_scale) params.cfgScale = body.cfg_scale;
if (body.seed) params.seed = body.seed;
if (opts.sampler) params.samplingMethod = opts.sampler;
// LoRAs
if (body.loras?.length) {
params.lora = {};
body.loras.forEach(l => { params.lora[l.id] = l.weight || 0.7; });
}
// Quality boosters
if (opts.enableADetailer) params.enableADetailer = true;
if (opts.upscale > 1) {
params.upscale = opts.upscale;
if (opts.upscaleSampler) params.upscaleSampler = opts.upscaleSampler;
if (opts.upscaleDenoisingStrength) params.upscaleDenoisingStrength = opts.upscaleDenoisingStrength;
if (opts.upscaleDenoisingSteps) params.upscaleDenoisingSteps = opts.upscaleDenoisingSteps;
if (opts.enableTile) params.enableTile = true;
}
// Img2Img
if (opts.mediaUrl) {
params.mediaUrl = opts.mediaUrl;
if (opts.strength) params.strength = opts.strength;
}
// Prompt helper
if (opts.promptHelper) params.promptHelper = { enable: true };
log(sessionId, `PixAI request: model=${params.modelId}, ${params.width}x${params.height}, sampler=${params.samplingMethod || 'default'}`);
const createRes = await fetch('https://api.pixai.art/v1/task', {
method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({ parameters: params })
});
const createData = await createRes.json();
if (!createData.id) throw new Error(createData.message || 'Failed to create task');
log(sessionId, `PixAI task created: ${createData.id}`);
for (let i = 0; i < 120; i++) {
await new Promise(r => setTimeout(r, 2000));
const statusRes = await fetch(`https://api.pixai.art/v1/task/${createData.id}`, { headers: { 'Authorization': `Bearer ${apiKey}` } });