Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4634 lines (4264 loc) · 179 KB
/
Copy pathapp.js
File metadata and controls
4634 lines (4264 loc) · 179 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 {
IDLE_GENERATION_HINT,
POLICY_VIOLATION_MESSAGE,
getGenerationProgressMessage,
getGenerationProgressView,
getPreservedGenerationProgressEvent,
getResponseStreamProgressMessage,
getResponseStreamProgressPhase,
getSseProgressMessage,
getWaitingProgressMessage,
isPolicyViolationText,
normalizeGenerationError,
} from './ui-feedback.js';
import { $ } from './frontend/dom.js';
import { backgroundJobBackoffMs, fetchWithTimeout, sleep } from './frontend/http.js';
import {
ACTIVE_JOB_STALE_MS,
BACKGROUND_JOB_CREATE_TIMEOUT_MS,
BACKGROUND_JOB_POLL_INTERVAL_MS,
BACKGROUND_JOB_POLL_RETRY_BASE_MS,
BACKGROUND_JOB_POLL_RETRY_LIMIT,
BACKGROUND_JOB_POLL_TIMEOUT_MS,
clearActiveJob,
formatRelativeTime,
hideActiveJobBanner,
isPollingStopped,
loadActiveJob,
saveActiveJob,
showActiveJobBanner,
stopPollingJob,
} from './frontend/background-jobs.js';
import {
hideGenerationErrorDialog,
showError,
} from './frontend/error-dialog.js';
import { closeDialog, openDialog } from './frontend/dialog-a11y.js';
import { confirmAction, createButton, createIconButton, notifyAction } from './frontend/ui-actions.js';
import { state, cloneDefaultSettings, mergeAppSettings } from './frontend/state.js';
import { adminFetch } from './frontend/admin-api.js';
import {
clearAdminSession,
hasValidAdminSession,
persistAdminSession,
} from './frontend/admin-session.js';
const ACCOUNTS_KEY = 'img-gen-accounts';
const APP_SETTINGS_KEY = 'img-gen-app-settings';
const PROMPT_HISTORY_KEY = 'img-gen-prompt-history';
const LOCAL_IMAGE_HISTORY_DB = 'img-gen-local-image-history';
const LOCAL_IMAGE_HISTORY_STORE = 'images';
const LOCAL_IMAGE_HISTORY_VERSION = 1;
const LOCAL_IMAGE_HISTORY_LIMIT = 120;
const OLD_KEY = 'img-gen-settings';
const DEFAULT_IMAGE_MODEL = 'gpt-image-2';
const DEFAULT_RESPONSES_MODEL = 'gpt-5.4';
const MAX_REF_IMAGES = 3;
const REF_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
const REF_IMAGES_TOTAL_MAX_BYTES = 24 * 1024 * 1024;
const ALLOWED_REF_IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
let historySearchTimer = null;
let promptHistory = [];
let pendingBackupImport = null;
// --- Data Layer ---
function genId() {
return crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2);
}
function loadData() {
try {
const saved = JSON.parse(localStorage.getItem(ACCOUNTS_KEY));
if (saved) { state.data = saved; return; }
} catch {}
migrateOldSettings();
}
function saveData() {
localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(state.data));
}
function getLocalImageDb() {
if (!globalThis.indexedDB) return Promise.resolve(null);
return new Promise((resolve) => {
let request;
try {
request = indexedDB.open(LOCAL_IMAGE_HISTORY_DB, LOCAL_IMAGE_HISTORY_VERSION);
} catch {
resolve(null);
return;
}
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(LOCAL_IMAGE_HISTORY_STORE)) {
const store = db.createObjectStore(LOCAL_IMAGE_HISTORY_STORE, { keyPath: 'id' });
store.createIndex('createdAt', 'createdAt');
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => resolve(null);
});
}
function requestToPromise(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error || new Error('IndexedDB request failed'));
});
}
function txDone(tx) {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error || new Error('IndexedDB transaction aborted'));
tx.onerror = () => reject(tx.error || new Error('IndexedDB transaction failed'));
});
}
function isLocalImageHistoryItem(meta = {}) {
return String(meta?.id || '').startsWith('local_img_') || meta?.localHistory === true;
}
function normalizeLocalImageMeta(meta = {}) {
const snapshot = getHistoryGenerationSnapshot(meta);
return {
prompt: String(meta.prompt || snapshot.prompt || '').slice(0, 300),
createdAt: Number(meta.createdAt || Date.now()),
favorite: meta.favorite === true,
tags: Array.isArray(meta.tags) ? meta.tags.map((tag) => String(tag || '').trim()).filter(Boolean).slice(0, 12) : [],
model: String(meta.model || snapshot.model || '').slice(0, 80),
accountName: String(meta.accountName || '').slice(0, 80),
accountHost: String(meta.accountHost || '').slice(0, 120),
batchId: String(meta.batchId || '').slice(0, 80),
batchIndex: Number(meta.batchIndex || 0) || null,
batchCount: Number(meta.batchCount || 0) || null,
generation: snapshot,
};
}
async function pruneLocalImageHistory(db) {
if (!db) return;
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readwrite');
const store = tx.objectStore(LOCAL_IMAGE_HISTORY_STORE);
const all = await requestToPromise(store.getAll()).catch(() => []);
const overflow = (Array.isArray(all) ? all : [])
.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0))
.slice(LOCAL_IMAGE_HISTORY_LIMIT);
for (const item of overflow) {
if (item?.id) store.delete(item.id);
}
await txDone(tx).catch(() => {});
}
async function saveLocalImageResult(src, format = 'png', meta = {}) {
if (!src) return null;
const db = await getLocalImageDb();
if (!db) return null;
const id = meta.id && isLocalImageHistoryItem(meta) ? meta.id : `local_img_${genId()}`;
const record = {
id,
url: src,
format: format || meta.format || 'png',
localHistory: true,
persisted: true,
...normalizeLocalImageMeta(meta),
};
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readwrite');
tx.objectStore(LOCAL_IMAGE_HISTORY_STORE).put(record);
await txDone(tx);
await pruneLocalImageHistory(db);
return record;
}
async function listLocalImageHistory() {
const db = await getLocalImageDb();
if (!db) return [];
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readonly');
const records = await requestToPromise(tx.objectStore(LOCAL_IMAGE_HISTORY_STORE).getAll()).catch(() => []);
return (Array.isArray(records) ? records : [])
.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0));
}
async function deleteLocalImage(id) {
const db = await getLocalImageDb();
if (!db) return false;
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readwrite');
tx.objectStore(LOCAL_IMAGE_HISTORY_STORE).delete(id);
await txDone(tx);
return true;
}
async function patchLocalImageMeta(id, meta = {}) {
const db = await getLocalImageDb();
if (!db) return null;
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readwrite');
const store = tx.objectStore(LOCAL_IMAGE_HISTORY_STORE);
const record = await requestToPromise(store.get(id)).catch(() => null);
if (!record) return null;
if (Object.prototype.hasOwnProperty.call(meta, 'favorite')) record.favorite = meta.favorite === true;
if (Object.prototype.hasOwnProperty.call(meta, 'tags')) {
record.tags = Array.isArray(meta.tags)
? meta.tags.map((tag) => String(tag || '').trim()).filter(Boolean).slice(0, 12)
: String(meta.tags || '').split(',').map((tag) => tag.trim()).filter(Boolean).slice(0, 12);
}
store.put(record);
await txDone(tx);
return record;
}
async function clearLocalImageHistory() {
const db = await getLocalImageDb();
if (!db) return;
const tx = db.transaction(LOCAL_IMAGE_HISTORY_STORE, 'readwrite');
tx.objectStore(LOCAL_IMAGE_HISTORY_STORE).clear();
await txDone(tx);
}
function filterLocalHistory(history = [], filters = {}) {
const query = String(filters.query || '').trim().toLowerCase();
const favoriteOnly = filters.favorite === true;
const batchId = String(filters.batchId || '').trim();
let items = Array.isArray(history) ? history : [];
if (favoriteOnly) items = items.filter((item) => item.favorite === true);
if (batchId) items = items.filter((item) => String(item.batchId || '') === batchId);
if (query) {
items = items.filter((item) => [
item.prompt,
item.model,
item.accountName,
item.accountHost,
item.batchId,
...(Array.isArray(item.tags) ? item.tags : []),
].map((value) => String(value || '').toLowerCase()).join('\n').includes(query));
}
return items;
}
async function fetchLocalImageHistory(filters = {}) {
const all = filterLocalHistory(await listLocalImageHistory(), filters);
const limit = Math.max(1, Math.min(100, Number(filters.limit || 60)));
const cursor = Math.max(0, Number(filters.cursor || 0));
const history = all.slice(cursor, cursor + limit);
const nextOffset = cursor + history.length;
return {
history,
limit,
cursor,
nextCursor: nextOffset < all.length ? String(nextOffset) : '',
count: history.length,
total: all.length,
};
}
async function loadLocalImageHistory({ replace = false } = {}) {
const data = await fetchLocalImageHistory({ limit: 60 });
if (!replace && $('#results')?.children.length) {
const total = Number(data.total || 0);
setHistoryStatus(total ? `本地已保存 ${total} 张图片` : '暂无本地历史记录');
return data;
}
renderHistoryResults(data.history || [], { replace });
const total = Number(data.total || 0);
setHistoryStatus(total ? `本地已保存 ${total} 张图片` : '暂无本地历史记录');
return data;
}
function shouldPersistClientImageResult(meta = {}) {
return state.appSettings.storage.enabled !== false && (
meta.persistClientHistory === true
|| meta.persisted === false
|| !!meta.storageError
|| !canUseStorageApi()
);
}
async function persistClientResultIfNeeded(src, format, meta = {}, card = null, actions = null) {
if (!shouldPersistClientImageResult(meta)) return null;
if (meta.id || isLocalImageHistoryItem(meta)) return null;
try {
const record = await saveLocalImageResult(src, format, meta);
if (record) {
if (card && actions) appendHistoryActions(actions, record, card);
setHistoryStatus('已保存到浏览器本地历史');
}
return record;
} catch (error) {
console.warn('Failed to save local image history:', error?.message || error);
setHistoryStatus('本地历史保存失败,当前图片仍可下载', true);
return null;
}
}
function sanitizeTemplateText(value = '', max = 2000) {
return String(value || '').trim().slice(0, max);
}
function sanitizePromptHistoryEntry(input = {}) {
const source = sanitizeTemplateText(input.source || input.prompt || input.content || '', 4000);
const final = sanitizeTemplateText(input.final || input.content || input.prompt || input.source || '', 4000);
if (!source && !final) return null;
const now = Date.now();
return {
id: sanitizeTemplateText(input.id, 80) || genId(),
source,
final: final || source,
style: sanitizeTemplateText(input.style, 40),
type: sanitizeTemplateText(input.type, 40),
mode: sanitizeTemplateText(input.mode, 40) || 'history',
createdAt: Number(input.createdAt || input.updatedAt || now),
};
}
function loadPromptHistory() {
try {
const parsed = JSON.parse(localStorage.getItem(PROMPT_HISTORY_KEY) || '[]');
promptHistory = (Array.isArray(parsed) ? parsed : []).map(sanitizePromptHistoryEntry).filter(Boolean).slice(0, 30);
} catch {
promptHistory = [];
}
}
function savePromptHistory() {
localStorage.setItem(PROMPT_HISTORY_KEY, JSON.stringify(promptHistory.map(sanitizePromptHistoryEntry).filter(Boolean).slice(0, 30)));
}
function setPromptHistoryStatus(text = '', isError = false) {
const el = $('#promptHistoryStatus');
if (!el) return;
el.textContent = text;
el.classList.toggle('error', !!isError);
}
function renderPromptHistory() {
const select = $('#promptHistorySelect');
if (!select) return;
const current = select.value;
select.innerHTML = '<option value="">选择历史提示词...</option>';
for (const item of promptHistory) {
const option = document.createElement('option');
option.value = item.id;
const label = new Date(item.createdAt).toLocaleString();
const text = (item.final || item.source || '').replace(/\s+/g, ' ').slice(0, 42);
option.textContent = `${label} · ${text}`;
select.appendChild(option);
}
if (promptHistory.some((item) => item.id === current)) select.value = current;
}
function recordPromptHistory({ source = '', final = '', style = '', type = '', mode = 'generate' } = {}) {
const entry = sanitizePromptHistoryEntry({ source, final: final || source, style, type, mode, createdAt: Date.now() });
if (!entry) return;
const sameIndex = promptHistory.findIndex((item) => (item.final || item.source) === (entry.final || entry.source));
if (sameIndex >= 0) promptHistory.splice(sameIndex, 1);
promptHistory.unshift(entry);
promptHistory = promptHistory.slice(0, 30);
savePromptHistory();
renderPromptHistory();
}
function saveCurrentPromptToHistory() {
const prompt = sanitizeTemplateText($('#prompt')?.value || '', 4000);
if (!prompt) { showError('请输入提示词后再保存历史', { context: 'prompt-history' }); return; }
recordPromptHistory({
source: prompt,
final: prompt,
style: $('#styleSelect')?.value || '',
type: $('#typeSelect')?.value || '',
mode: 'manual-save',
});
const select = $('#promptHistorySelect');
if (select && promptHistory[0]) select.value = promptHistory[0].id;
setPromptHistoryStatus('已保存到提示词历史');
}
function getSelectedPromptHistory() {
const id = $('#promptHistorySelect')?.value || '';
return promptHistory.find((entry) => entry.id === id) || null;
}
function applySelectedPromptHistory() {
const item = getSelectedPromptHistory();
if (!item) {
setPromptHistoryStatus('');
return;
}
const text = item.final || item.source;
if (!text) {
setPromptHistoryStatus('这条历史没有可恢复的提示词', true);
return;
}
$('#prompt').value = text;
if (item.style) setSelectValue('styleSelect', item.style);
if (item.type) setSelectValue('typeSelect', item.type);
setPromptHistoryStatus('已写入输入框');
}
function restorePromptHistoryVersion(kind = 'final') {
const item = getSelectedPromptHistory();
if (!item) { showError('请先选择历史提示词', { context: 'prompt-history' }); return; }
const text = kind === 'source' ? item.source : item.final;
if (!text) { showError(kind === 'source' ? '这条记录没有原始提示词' : '这条记录没有最终提示词', { context: 'prompt-history' }); return; }
$('#prompt').value = text;
if (item.style) setSelectValue('styleSelect', item.style);
if (item.type) setSelectValue('typeSelect', item.type);
setPromptHistoryStatus(kind === 'source' ? '已恢复原始提示词' : '已恢复最终提示词');
}
function clearPromptHistory() {
if (!promptHistory.length) { setPromptHistoryStatus('暂无提示词历史'); return; }
if (!confirmAction('确定清空提示词历史?')) return;
promptHistory = [];
savePromptHistory();
renderPromptHistory();
setPromptHistoryStatus('提示词历史已清空');
}
function toBase64Bytes(bytes) {
const binary = Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => String.fromCharCode(b)).join('');
if (typeof btoa === 'function') return btoa(binary);
return Buffer.from(binary, 'binary').toString('base64');
}
function fromBase64Bytes(value = '') {
const binary = typeof atob === 'function'
? atob(value)
: Buffer.from(String(value || ''), 'base64').toString('binary');
return Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
}
function downloadJsonFile(filename, payload) {
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
function sanitizeAccountForExport(acc = {}, includeSecrets = false) {
const allowed = {
id: sanitizeTemplateText(acc.id, 80) || genId(),
type: acc.type === 'oauth' ? 'oauth' : 'manual',
name: sanitizeTemplateText(acc.name, 120),
apiUrl: sanitizeTemplateText(acc.apiUrl, 500),
model: sanitizeTemplateText(acc.model || DEFAULT_IMAGE_MODEL, 120),
responsesModel: sanitizeTemplateText(acc.responsesModel || DEFAULT_RESPONSES_MODEL, 120),
streamMode: acc.streamMode === true,
imageEditsCompatMode: acc.imageEditsCompatMode === true,
responsesAutoFallback: acc.responsesAutoFallback !== false,
createdAt: Number(acc.createdAt || Date.now()),
};
if (!includeSecrets) return allowed;
for (const key of ['apiKey', 'refreshToken', 'email', 'accountId', 'planType', 'openaiDeviceId', 'openaiSessionId']) {
if (acc[key]) allowed[key] = String(acc[key]);
}
if (acc.tokenExpiresAt) allowed.tokenExpiresAt = Number(acc.tokenExpiresAt);
return allowed;
}
function normalizeImportedAccount(acc = {}) {
const normalized = sanitizeAccountForExport(acc, true);
if (!normalized.id) normalized.id = genId();
return normalized;
}
function buildBackupPayload({ includeSecrets = false } = {}) {
return {
version: 1,
app: 'image-gen',
exportedAt: Date.now(),
containsSecrets: includeSecrets === true,
accounts: (state.data.accounts || []).map((acc) => sanitizeAccountForExport(acc, includeSecrets)),
settings: mergeAppSettings(state.appSettings),
promptHistory: promptHistory.map(sanitizePromptHistoryEntry).filter(Boolean).slice(0, 30),
};
}
async function deriveBackupKey(password, salt) {
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持 Web Crypto,无法加密或解密完整备份');
const material = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(password),
'PBKDF2',
false,
['deriveKey'],
);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: 210_000 },
material,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
}
async function encryptBackupPayload(payload, password) {
if (!String(password || '').trim()) throw new Error('完整导出需要输入加密密码');
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await deriveBackupKey(password, salt);
const plaintext = new TextEncoder().encode(JSON.stringify(payload));
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
return {
version: 1,
app: 'image-gen',
encrypted: true,
exportedAt: Date.now(),
crypto: {
name: 'AES-GCM',
kdf: 'PBKDF2',
hash: 'SHA-256',
iterations: 210_000,
salt: toBase64Bytes(salt),
iv: toBase64Bytes(iv),
},
ciphertext: toBase64Bytes(ciphertext),
};
}
async function decryptBackupEnvelope(envelope, password) {
if (!String(password || '').trim()) throw new Error('此备份已加密,请输入导入密码');
const salt = fromBase64Bytes(envelope?.crypto?.salt || '');
const iv = fromBase64Bytes(envelope?.crypto?.iv || '');
const ciphertext = fromBase64Bytes(envelope?.ciphertext || '');
const key = await deriveBackupKey(password, salt);
const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
return JSON.parse(new TextDecoder().decode(plaintext));
}
function promptHistoryFromBackupPayload(payload = {}) {
if (Array.isArray(payload.promptHistory)) {
return payload.promptHistory.map(sanitizePromptHistoryEntry).filter(Boolean).slice(0, 30);
}
return [];
}
function normalizeBackupPayload(payload = {}) {
if (payload.app !== 'image-gen' || !Array.isArray(payload.accounts)) {
throw new Error('备份文件格式不正确');
}
return {
version: Number(payload.version || 1),
app: 'image-gen',
exportedAt: Number(payload.exportedAt || Date.now()),
containsSecrets: payload.containsSecrets === true,
accounts: payload.accounts.map(normalizeImportedAccount).slice(0, 50),
settings: mergeAppSettings(payload.settings || {}),
promptHistory: promptHistoryFromBackupPayload(payload),
};
}
async function readBackupFile(file, password = '') {
if (!file) return null;
const raw = JSON.parse(await file.text());
const payload = raw?.encrypted ? await decryptBackupEnvelope(raw, password) : raw;
return normalizeBackupPayload(payload);
}
function summarizeBackupPayload(payload = {}) {
const secretless = !payload.containsSecrets;
return [
`<strong>${payload.containsSecrets ? '完整备份' : '安全备份'}</strong>`,
`账号:${payload.accounts?.length || 0} 个${secretless ? '(不含 key/token/session)' : '(含敏感字段,已通过密码解密)'}`,
`设置:${payload.settings ? '1 组' : '0 组'}`,
`提示词历史:${payload.promptHistory?.length || 0} 条`,
`导出时间:${payload.exportedAt ? new Date(payload.exportedAt).toLocaleString() : '未知'}`,
].join('<br>');
}
function setBackupPreview(html = '', isError = false) {
const preview = $('#importBackupPreview');
if (!preview) return;
preview.innerHTML = html;
preview.classList.toggle('hidden', !html);
preview.classList.toggle('error', !!isError);
}
function readBackupImportScopes() {
return {
accounts: $('#importBackupAccounts')?.checked !== false,
settings: $('#importBackupSettings')?.checked !== false,
promptHistory: $('#importBackupPromptHistory')?.checked !== false,
};
}
function applyImportedBackup(payload, scopes = readBackupImportScopes()) {
if (!payload) throw new Error('请先选择并预览备份文件');
if (scopes.accounts) {
const byId = new Map((state.data.accounts || []).map((acc) => [acc.id, acc]));
for (const acc of payload.accounts || []) byId.set(acc.id || genId(), normalizeImportedAccount(acc));
state.data.accounts = Array.from(byId.values()).slice(0, 50);
if (!state.data.activeId && state.data.accounts.length) state.data.activeId = state.data.accounts[0].id;
saveData();
renderSwitcher();
}
if (scopes.settings) {
state.appSettings = mergeAppSettings(payload.settings || {});
saveAppSettings();
fillSettingsForm();
applyGenerationDefaultsToControls();
syncPromptEnhancementUi();
}
if (scopes.promptHistory) {
const byId = new Map(promptHistory.map((item) => [item.id, item]));
for (const item of payload.promptHistory || []) {
const sanitized = sanitizePromptHistoryEntry(item);
if (sanitized) byId.set(sanitized.id, sanitized);
}
promptHistory = Array.from(byId.values())
.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0))
.slice(0, 30);
savePromptHistory();
renderPromptHistory();
}
return {
accounts: scopes.accounts ? (payload.accounts?.length || 0) : 0,
settings: scopes.settings ? 1 : 0,
promptHistory: scopes.promptHistory ? (payload.promptHistory?.length || 0) : 0,
};
}
function exportSafeBackup() {
downloadJsonFile(`image-gen-safe-backup-${Date.now()}.json`, buildBackupPayload({ includeSecrets: false }));
setBackupPreview('安全备份已导出:不包含 API key、OAuth token、session 或平台口令。');
}
async function exportEncryptedBackup() {
const password = $('#backupPassword')?.value || '';
const envelope = await encryptBackupPayload(buildBackupPayload({ includeSecrets: true }), password);
downloadJsonFile(`image-gen-encrypted-backup-${Date.now()}.json`, envelope);
setBackupPreview('完整备份已加密导出;导入时需要同一个密码。');
}
async function previewBackupImportFromFile(file) {
const password = $('#backupPassword')?.value || '';
pendingBackupImport = await readBackupFile(file, password);
setBackupPreview(`${summarizeBackupPayload(pendingBackupImport)}<br><strong>请确认导入范围后再点击确认。</strong>`);
const confirmBtn = $('#confirmImportBackup');
if (confirmBtn) confirmBtn.disabled = false;
}
function confirmImportBackup() {
const result = applyImportedBackup(pendingBackupImport, readBackupImportScopes());
setBackupPreview(`导入完成:账号 ${result.accounts} 个,设置 ${result.settings} 组,提示词历史 ${result.promptHistory} 条。`);
const confirmBtn = $('#confirmImportBackup');
if (confirmBtn) confirmBtn.disabled = true;
pendingBackupImport = null;
}
function setAdminGateStatus(text = '', isError = false) {
const el = $('#adminGateStatus');
if (!el) return;
el.textContent = text;
el.classList.toggle('error', !!isError);
}
function syncAdminGateUi() {
const unlocked = hasValidAdminSession();
const loginShell = $('#adminLoginShell');
const mainShell = $('#mainAppShell');
if (loginShell) loginShell.classList.toggle('hidden', unlocked);
if (mainShell) mainShell.classList.toggle('hidden', !unlocked);
document.documentElement.dataset.adminSession = unlocked ? 'active' : 'locked';
document.body?.classList.toggle('admin-gate-active', !unlocked);
setAdminGateStatus(
unlocked ? '管理员已登录,已拥有全部管理权限。' : '请输入管理员鉴权后进入。',
false,
);
}
async function verifyAdminTokenInput(token) {
const resp = await fetch('/api/admin/session', {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) {
const error = new Error(data.error || '管理员口令不正确或当前部署未启用管理接口。');
error.status = resp.status;
error.code = 'ADMIN_AUTH_FAILED';
error.context = 'admin';
throw error;
}
return data;
}
async function hydrateAdminUnlockedState({ resumeJob = false } = {}) {
try {
await fetchEditableRuntimeConfig();
fillServerConfigForm();
} catch (error) {
console.warn('Failed to refresh editable runtime config:', error?.message || error);
if (error?.code === 'ADMIN_AUTH_EXPIRED' || error?.code === 'ADMIN_AUTH_REQUIRED') {
syncAdminGateUi();
return;
}
}
await fetchAccountStoreCapabilities();
await loadServerAccountsIntoLocal({ silent: true });
renderSwitcher();
renderDropdown();
renderAccountList();
syncAccountMigrationUi();
if (resumeJob) void resumeActiveJobIfAny();
}
async function loginAdminFromGate() {
const token = ($('#adminGateTokenInput')?.value || '').trim();
if (!token) {
setAdminGateStatus('请输入管理员鉴权。', true);
return;
}
const btn = $('#adminGateLoginBtn');
if (btn) btn.disabled = true;
setAdminGateStatus('正在验证管理员鉴权...');
try {
await verifyAdminTokenInput(token);
persistAdminSession(token);
setInputValue('adminGateTokenInput', '');
syncAdminGateUi();
await hydrateAdminUnlockedState({ resumeJob: true });
notifyAction('管理员已登录');
} catch (error) {
clearAdminSession();
syncAdminGateUi();
setAdminGateStatus('管理员鉴权不正确或当前部署未启用管理接口。', true);
showError(error, { context: 'admin' });
} finally {
if (btn) btn.disabled = false;
}
}
function logoutAdminSession() {
clearAdminSession();
syncAdminGateUi();
syncAccountMigrationUi();
notifyAction('已退出管理员登录');
}
function isRuntimeConfigPayload(data = {}) {
return !!(
data
&& typeof data === 'object'
&& data.runtime
&& (data.meta?.capabilities || data.capabilities)
);
}
async function fetchServerRuntimeConfig() {
const resp = await fetch('/api/config/runtime');
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
if (!isRuntimeConfigPayload(data)) throw new Error('Runtime config API unavailable');
state.serverConfig = data.runtime || null;
state.serverCapabilities = data.meta?.capabilities || data.capabilities || null;
state.configSchema = data.schema || null;
return data;
}
async function fetchEditableRuntimeConfig() {
const resp = await adminFetch('/api/config/editable', { method: 'GET' });
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
state.serverConfig = data.runtime || state.serverConfig;
state.serverCapabilities = data.meta?.capabilities || data.capabilities || state.serverCapabilities;
state.configSchema = data.schema || state.configSchema;
return data;
}
function getProviderDefaults() {
return state.serverConfig?.providerDefaults || {
apiUrl: 'https://api.openai.com',
imageModel: DEFAULT_IMAGE_MODEL,
responsesModel: DEFAULT_RESPONSES_MODEL,
streamMode: false,
responsesAutoFallback: true,
imageEditsCompatMode: false,
forceProxy: false,
};
}
function getServerCapabilities() {
return state.serverCapabilities || {};
}
function markRuntimeApisUnavailable() {
state.serverCapabilities = {
...(state.serverCapabilities || {}),
runtime: state.serverCapabilities?.runtime || 'static',
canUseStorageApi: false,
canPersistImages: false,
canUseBackgroundJobs: false,
backgroundJobsInline: false,
canUseConfigApi: false,
canUseConfigSaveApi: false,
};
}
function canUseProxyMultipart() {
return getServerCapabilities().canProxyMultipart !== false;
}
function canPersistImagesOnServer() {
return getServerCapabilities().canPersistImages !== false;
}
function canUseStorageApi() {
return getServerCapabilities().canUseStorageApi !== false;
}
function canUseBackgroundJobs() {
return getServerCapabilities().canUseBackgroundJobs !== false;
}
function canUseConfigSaveApi() {
return getServerCapabilities().canUseConfigSaveApi !== false;
}
function normalizeAccountStoreCapabilities(input = {}) {
const source = input.store || input.accountStore || input;
const type = ['file', 'upstash', 'browser'].includes(source?.type) ? source.type : 'browser';
return {
ok: input.ok !== false,
schemaVersion: Number(input.schemaVersion || 1),
store: {
requested: source?.requested || 'auto',
type,
available: source?.available !== false,
encrypted: source?.encrypted === true,
fallback: source?.fallback || 'browser',
fallbackActive: source?.fallbackActive === true || type === 'browser' || source?.available === false,
scope: source?.scope || (type === 'upstash' ? 'remote' : type === 'file' ? 'server' : 'browser'),
reason: source?.reason || '',
},
};
}
function fallbackAccountStoreCapabilities(reason = 'api-unavailable') {
return normalizeAccountStoreCapabilities({
ok: true,
store: {
requested: 'auto',
type: 'browser',
available: true,
encrypted: false,
fallback: 'browser',
fallbackActive: true,
scope: 'browser',
reason,
},
});
}
async function fetchAccountStoreCapabilities() {
try {
const resp = await fetch('/api/accounts/capabilities');
if (resp.status === 404) {
state.accountStoreCapabilities = fallbackAccountStoreCapabilities('api-not-found');
syncAccountStoreUi();
return state.accountStoreCapabilities;
}
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
state.accountStoreCapabilities = normalizeAccountStoreCapabilities(data);
} catch (error) {
console.warn('Failed to load account store capabilities:', error?.message || error);
state.accountStoreCapabilities = fallbackAccountStoreCapabilities('api-error');
}
syncAccountStoreUi();
return state.accountStoreCapabilities;
}
function describeAccountStore(store = {}) {
const type = store.type || 'browser';
if (type === 'file' && store.available) {
return {
pill: '账号当前保存位置:服务端文件',
type: '服务端文件存储',
detail: '当前 Node / Docker 部署具备服务端账号存储能力;管理员登录后,账号会优先同步到服务端文件,并保留浏览器缓存作为兼容副本。',
encrypted: store.encrypted ? '敏感字段:已启用账号存储加密' : '敏感字段:尚未检测到账号加密 key,后续写入前会继续要求加密或本地密钥。',
};
}
if (type === 'upstash' && store.available) {
return {
pill: '账号当前保存位置:Upstash',
type: 'Upstash 远程存储',
detail: '已检测到 Upstash 账号存储配置,适合云平台多浏览器共享账号;页面不会展示 Upstash URL、Token 或账号密钥。',
encrypted: store.encrypted ? '敏感字段:已启用加密配置' : '敏感字段:缺少加密配置,暂不应写入远程存储。',
};
}
if (type !== 'browser' && store.available === false) {
return {
pill: '账号当前保存位置:浏览器缓存',
type: type === 'upstash' ? 'Upstash 未就绪' : '服务端账号存储未就绪',
detail: '已检测到服务端账号存储配置不完整。为避免影响使用,API Key 与 OAuth 账号会继续保存在当前浏览器。',
encrypted: '敏感字段:未写入服务端或远程存储。',
};
}
return {
pill: '账号当前保存位置:浏览器缓存',
type: '当前浏览器缓存',
detail: '当前部署未检测到可用的服务端账号存储或 Upstash,API Key 与 OAuth 账号会按旧逻辑保存在此浏览器。',
encrypted: '敏感字段:仅保存在当前浏览器;换设备、无痕模式或清理浏览器数据后需要重新配置。',
};
}
function syncAccountStoreUi() {
const capabilities = state.accountStoreCapabilities || fallbackAccountStoreCapabilities('not-loaded');
const store = capabilities.store || {};
const copy = describeAccountStore(store);
const quickStatus = $('#settingsAccountStorageStatus');
if (quickStatus) quickStatus.textContent = copy.pill;
const storageStatus = $('#storageAccountStoreStatus');
if (storageStatus) storageStatus.textContent = copy.pill.replace('账号当前保存位置:', '');
const typeEl = $('#accountStoreType');
if (typeEl) typeEl.textContent = copy.type;
const detailEl = $('#accountStoreDetail');
if (detailEl) detailEl.textContent = copy.detail;
const encryptedEl = $('#accountStoreEncrypted');
if (encryptedEl) encryptedEl.textContent = copy.encrypted;
syncAccountMigrationUi();
}
function canUseServerAccountStore() {
const store = state.accountStoreCapabilities?.store || {};
return hasValidAdminSession()
&& store.available === true
&& store.type !== 'browser';
}
function accountStoreSyncWarning(action, error) {
const message = error?.message || error;
console.warn(`Failed to ${action} server account store:`, message);
}
function compactServerAccountPayload(account = {}) {
const payload = sanitizeAccountForExport(account, true);
for (const key of ['apiKey', 'refreshToken', 'email', 'accountId', 'planType', 'openaiDeviceId', 'openaiSessionId']) {
if (!String(payload[key] || '').trim()) delete payload[key];
}
if (!Number.isFinite(Number(payload.tokenExpiresAt || 0))) delete payload.tokenExpiresAt;
return payload;
}
function compactServerAccountPatch(fields = {}) {
const source = fields && typeof fields === 'object' ? fields : {};
const patch = {};
const textKeys = ['type', 'name', 'apiUrl', 'model', 'responsesModel', 'email', 'accountId', 'planType'];
const secretKeys = ['apiKey', 'refreshToken', 'openaiDeviceId', 'openaiSessionId'];
for (const key of textKeys) {
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
const value = String(source[key] || '').trim();
if (value) patch[key] = value;
}
for (const key of secretKeys) {
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
const value = String(source[key] || '').trim();
if (value) patch[key] = value;
}
for (const key of ['streamMode', 'responsesAutoFallback', 'imageEditsCompatMode']) {
if (Object.prototype.hasOwnProperty.call(source, key)) patch[key] = source[key] === true;
}
if (Object.prototype.hasOwnProperty.call(source, 'tokenExpiresAt')) {
const expires = Number(source.tokenExpiresAt);
if (Number.isFinite(expires) && expires > 0) patch.tokenExpiresAt = expires;
}
return patch;
}
async function readAccountStoreResponse(resp, label) {
const data = await resp.json().catch(() => ({}));
if (!resp.ok) {
const error = new Error(data.error || `${label} failed: HTTP ${resp.status}`);
error.status = resp.status;
error.code = data.code || 'ACCOUNT_STORE_SYNC_FAILED';
error.context = 'account-store';
throw error;
}
return data;
}
async function listServerAccounts() {
if (!canUseServerAccountStore()) return null;
const resp = await adminFetch('/api/accounts', {
method: 'GET',
});
return readAccountStoreResponse(resp, 'List accounts');
}
function mergeServerAccountsIntoLocal(data = {}) {
const accounts = Array.isArray(data?.accounts) ? data.accounts : [];
let changed = false;
for (const serverAccount of accounts) {
const id = String(serverAccount?.id || '').trim();
if (!id) continue;
const existing = state.data.accounts.find((item) => item.id === id);
const merged = {
...(existing || {}),
...serverAccount,
id,