-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
7258 lines (7001 loc) · 321 KB
/
Copy pathscript.js
File metadata and controls
7258 lines (7001 loc) · 321 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 API = "https://api.modrinth.com/v2";
let unresolvableDeps = [];
let importedPackNotes = [];
let lastImportReport = null;
let passthroughFiles = [];
let importedOverrides = [];
/* =============================================================================
SECURITY HARDENING — read this before touching auth, fetch, or share-code code
=============================================================================
ModBench is a static, client-only app (GitHub Pages, no server we control).
That shapes what "security hardening" can mean here:
1) RATE LIMITING
A page of JavaScript can never enforce real IP-based rate limiting —
anyone can just reload the page or open dev tools and skip our code.
The actual security boundary lives on the servers we call:
- Supabase Auth (GoTrue) already rate-limits sign-in/sign-up/password
reset/email-sending per project. Tune it under
Project Settings -> Auth -> Rate Limits in the Supabase dashboard —
that is the authoritative control, not anything below.
- Share-code creation is capped server-side (see DAILY_SHARE_LIMIT /
createShortShareCode) via a Postgres check tied to the signed-in
user, enforced by RLS + a DB constraint/function, not by the client.
- Modrinth's public API enforces its own per-IP rate limits and
returns HTTP 429 when exceeded.
What we *can* usefully do client-side is (a) be a good citizen and slow
ourselves down before we get a 429, (b) stop a user from hammering a
button (double-submits, accidental spam), and (c) turn a raw 429 into a
clear "try again in Xs" message instead of a confusing generic error.
That's what clientRateLimit() / apiFetch() below do. Treat them as UX
polish and abuse-friction, not as the real defense.
2) INPUT VALIDATION
Anything typed by a user, or decoded from a share code someone else
generated, is untrusted. We validate shape/type/length here for two
real reasons even without a server of our own: it stops malformed data
from corrupting localStorage / the exported .mrpack, and it stops a
hostile share code (arbitrary base64 someone crafted by hand and sent
as a link) from injecting oversized or unexpected data into the app.
The DOM-injection side (XSS) is handled by consistently escaping with
escapeHtml() at render time — validateFields() below additionally
rejects the input up front so bad data never gets that far.
3) API KEYS
The only credential in this file is SUPABASE_ANON_KEY. That is not a
secret — per Supabase's own docs, the anon key is meant to ship in
client bundles, and it is safe specifically because every table it can
touch is protected by Postgres Row Level Security (RLS) policies on
the server. Hiding it (env vars, a build step, obfuscation) would not
add real security, since anything sent to the browser is visible to
the user by definition — it would just move the same string into a
bundler config while giving a false sense of secrecy. The actual
security control is: keep RLS policies correct, and never add a
genuinely secret key (a Supabase service_role key, a paid API key with
a quota you're billed for, etc.) to this client-side file. If a future
feature needs a real secret, it MUST go behind a server component we
control (e.g. a Supabase Edge Function) that holds the secret and the
browser never sees it — not into script.js.
============================================================================= */
/**
* Client-side sliding-window rate limiter. Backed by localStorage so a
* cooldown survives a page reload (closing the modal and reopening it
* shouldn't reset the clock). This is UX friction, not a security boundary —
* see the note above.
*
* @param {string} action unique key for the thing being limited, e.g. "auth:reset"
* @param {number} max max allowed hits inside the window
* @param {number} windowMs window size in ms
* @returns {{allowed:boolean, retryAfterMs:number}}
*/
function clientRateLimit(action, max, windowMs){
const key = `modbench_ratelimit_${action}`;
const now = Date.now();
let hits = [];
try{
hits = JSON.parse(safeLocalStorageGet(key, "[]"));
if(!Array.isArray(hits)) hits = [];
}catch(e){ hits = []; }
hits = hits.filter(ts=>now - ts < windowMs);
if(hits.length >= max){
const retryAfterMs = windowMs - (now - hits[0]);
return { allowed: false, retryAfterMs: Math.max(0, retryAfterMs) };
}
hits.push(now);
safeLocalStorageSet(key, JSON.stringify(hits));
return { allowed: true, retryAfterMs: 0 };
}
/** Formats a millisecond duration as "in 12s" / "in 2m" for cooldown messages. */
function formatRetryAfter(ms){
const secs = Math.ceil(ms / 1000);
if(secs < 60) return t('rateLimitInSeconds', 'in {n}s').replace('{n}', secs);
const mins = Math.ceil(secs / 60);
return t('rateLimitInMinutes', 'in {n}m').replace('{n}', mins);
}
/** Error type thrown when a request is refused for being rate-limited. */
class RateLimitedError extends Error{
constructor(message, retryAfterMs){
super(message);
this.name = "RateLimitedError";
this.retryAfterMs = retryAfterMs || 0;
}
}
async function fetchWithTimeout(url, options = {}, timeoutMs = 15000){
const controller = new AbortController();
const timer = setTimeout(()=>controller.abort(), timeoutMs);
try{
return await fetch(url, { ...options, signal: controller.signal });
}catch(e){
if(e.name === "AbortError") throw new Error("Request timed out.");
throw e;
}finally{
clearTimeout(timer);
}
}
/**
* Wraps fetchWithTimeout for calls to third-party public APIs (Modrinth,
* loader metadata services, etc.) and turns their own rate limiting into a
* clean signal instead of a confusing generic failure:
* - On HTTP 429, honors a Retry-After header (seconds or HTTP-date) with a
* short bounded backoff and retries once; if it's still 429, throws a
* RateLimitedError with the wait time so the UI can show
* "Too many requests, try again in Xs" instead of a stack trace.
* Callers that already do their own res.ok handling keep working unchanged —
* this only changes behavior on an actual 429.
*/
async function apiFetch(url, options = {}, timeoutMs = 15000){
let res = await fetchWithTimeout(url, options, timeoutMs);
if(res.status === 429){
const waitMs = parseRetryAfter(res.headers.get("Retry-After"), 2000, 8000);
await new Promise(r=>setTimeout(r, waitMs));
res = await fetchWithTimeout(url, options, timeoutMs);
if(res.status === 429){
const retryAfterMs = parseRetryAfter(res.headers.get("Retry-After"), 5000, 30000);
throw new RateLimitedError("Too many requests — please slow down.", retryAfterMs);
}
}
return res;
}
/** Parses a Retry-After header (seconds or HTTP-date) into a bounded ms value. */
function parseRetryAfter(header, minMs, maxMs){
if(!header) return minMs;
const asSeconds = Number(header);
let ms;
if(!isNaN(asSeconds)) ms = asSeconds * 1000;
else {
const date = Date.parse(header);
ms = isNaN(date) ? minMs : (date - Date.now());
}
return Math.min(maxMs, Math.max(minMs, ms || minMs));
}
/**
* Minimal schema validator for untrusted input (form fields, decoded share
* codes). Rejects unknown fields, enforces type/length/pattern, and returns
* a *new*, clamped object — callers should use the returned value, not the
* original, so nothing unvalidated slips through.
*
* schema: { fieldName: { type: 'string'|'number'|'array', required, maxLength,
* minLength, pattern, max, min, itemPattern, itemMaxLength, maxItems } }
*/
function validateFields(input, schema){
const errors = [];
const out = {};
const src = (input && typeof input === "object") ? input : {};
for(const field of Object.keys(schema)){
const rule = schema[field];
let value = src[field];
if(value === undefined || value === null){
if(rule.required){ errors.push(`${field} is required`); }
else if(rule.default !== undefined){ out[field] = rule.default; }
continue;
}
if(rule.type === "string"){
value = String(value);
// Strip control/zero-width characters that have no legitimate use in
// names, versions, codes, etc. and are a common obfuscation vector.
value = value.replace(/[\u0000-\u001F\u007F\u200B-\u200D\uFEFF]/g, "");
if(rule.trim !== false) value = value.trim();
if(typeof rule.maxLength === "number") value = value.slice(0, rule.maxLength);
if(typeof rule.minLength === "number" && value.length < rule.minLength){
errors.push(`${field} is too short`); continue;
}
if(rule.pattern && !rule.pattern.test(value)){
errors.push(`${field} has an invalid format`); continue;
}
out[field] = value;
} else if(rule.type === "number"){
value = Number(value);
if(!Number.isFinite(value)){ errors.push(`${field} must be a number`); continue; }
if(typeof rule.min === "number") value = Math.max(rule.min, value);
if(typeof rule.max === "number") value = Math.min(rule.max, value);
out[field] = value;
} else if(rule.type === "array"){
if(!Array.isArray(value)){ errors.push(`${field} must be a list`); continue; }
let arr = value.slice(0, rule.maxItems || 500);
if(rule.itemMaxLength || rule.itemPattern){
arr = arr
.map(v=>String(v).slice(0, rule.itemMaxLength || 200))
.filter(v=>!rule.itemPattern || rule.itemPattern.test(v));
}
out[field] = arr;
} else {
out[field] = value;
}
}
// Unexpected fields are dropped silently (not copied into `out`) rather
// than rejected outright — a hostile input can't smuggle extra data in,
// but this stays permissive enough not to break forward-compatible codes.
return { valid: errors.length === 0, errors, value: out };
}
const projectAuthorCache = new Map();
async function resolveProjectAuthor(projectId){
if(!projectId) return "";
if(!projectAuthorCache.has(projectId)){
projectAuthorCache.set(projectId, (async ()=>{
try{
const res = await fetchWithTimeout(`${API}/project/${projectId}/members`);
if(!res.ok) return "";
const members = await res.json();
if(!Array.isArray(members) || !members.length) return "";
const owner = members.find(m=>m.role === "Owner") || members[0];
return (owner && owner.user && owner.user.username) || "";
}catch(e){
return "";
}
})());
}
return projectAuthorCache.get(projectId);
}
document.addEventListener("click", (e)=>{
const toggle = e.target.closest(".modlist-toggle, .modlist-toggle-chip, .modlist-toggle-row");
if(!toggle) return;
const rest = document.getElementById(toggle.dataset.target);
if(rest){ rest.hidden = false; }
toggle.remove();
});
const MAX_VISIBLE_TOASTS = 4;
function collapseAndRemoveToast(el){
if(!el.isConnected) return;
clearTimeout(el._dismissTimer);
const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
el.classList.add("leaving");
if(reduced){ el.remove(); return; }
const rect = el.getBoundingClientRect();
el.style.height = rect.height + "px";
void el.offsetHeight;
requestAnimationFrame(()=>{
el.style.height = "0px";
el.style.marginBottom = "0px";
el.style.paddingTop = "0px";
el.style.paddingBottom = "0px";
});
let done = false;
const finish = ()=>{ if(done) return; done = true; el.remove(); };
el.addEventListener("transitionend", (e)=>{ if(e.propertyName === "height") finish(); });
setTimeout(finish, 160);
}
function dismissToastEl(el){
collapseAndRemoveToast(el);
}
function showToast(message, opts = {}){
const { actionLabel, onAction, duration = 6000, variant } = opts;
const stack = document.getElementById("toastStack");
if(!stack) return null;
// Cap how many toasts can be stacked on screen at once - bump the
// oldest one(s) out (with the same leaving animation as a normal
// dismissal) to make room, rather than letting the stack grow
// unbounded when several toasts fire in quick succession.
const excess = stack.children.length - (MAX_VISIBLE_TOASTS - 1);
if(excess > 0){
Array.from(stack.children).slice(0, excess).forEach(dismissToastEl);
}
const toast = document.createElement("div");
toast.className = "toast";
if(variant === "success" || variant === "error") toast.classList.add(variant);
toast.setAttribute("role", "status");
const msg = document.createElement("span");
msg.className = "toast-msg";
msg.innerHTML = escapeHtml(message).replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
toast.appendChild(msg);
let dismissTimer;
const dismiss = ()=>{
clearTimeout(dismissTimer);
collapseAndRemoveToast(toast);
};
if(actionLabel && onAction){
const actionBtn = document.createElement("button");
actionBtn.type = "button";
actionBtn.className = "toast-action";
actionBtn.textContent = actionLabel;
actionBtn.addEventListener("click", ()=>{
onAction();
dismiss();
});
toast.appendChild(actionBtn);
}
const closeBtn = document.createElement("button");
closeBtn.type = "button";
closeBtn.className = "toast-close";
closeBtn.setAttribute("aria-label", t('toastDismiss','Dismiss'));
closeBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
closeBtn.addEventListener("click", dismiss);
toast.appendChild(closeBtn);
stack.appendChild(toast);
dismissTimer = setTimeout(dismiss, duration);
return { dismiss };
}
const actionHistory = { past: [], future: [] };
const MAX_HISTORY_ENTRIES = 25;
function pushHistoryAction(label, undoFn, redoFn){
const entry = { label, undo: undoFn, redo: redoFn };
actionHistory.past.push(entry);
if(actionHistory.past.length > MAX_HISTORY_ENTRIES) actionHistory.past.shift();
actionHistory.future = [];
renderHistoryControls();
return entry;
}
function removeHistoryEntry(entry){
const idx = actionHistory.past.indexOf(entry);
if(idx !== -1) actionHistory.past.splice(idx, 1);
renderHistoryControls();
}
function undoLastAction(){
const entry = actionHistory.past.pop();
if(!entry) return;
entry.undo();
actionHistory.future.push(entry);
renderHistoryControls();
}
function redoLastAction(){
const entry = actionHistory.future.pop();
if(!entry) return;
entry.redo();
actionHistory.past.push(entry);
renderHistoryControls();
}
function undoHistoryToIndex(idx){
while(actionHistory.past.length > idx){
undoLastAction();
}
closeHistoryPopover();
}
function closeHistoryPopover(){
const popover = document.getElementById("historyPopover");
const toggleBtn = document.getElementById("historyListToggleBtn");
if(popover) popover.hidden = true;
if(toggleBtn) toggleBtn.setAttribute("aria-expanded", "false");
}
function renderHistoryControls(){
const undoBtn = document.getElementById("historyUndoBtn");
const redoBtn = document.getElementById("historyRedoBtn");
const toggleBtn = document.getElementById("historyListToggleBtn");
if(undoBtn) undoBtn.disabled = actionHistory.past.length === 0;
if(redoBtn) redoBtn.disabled = actionHistory.future.length === 0;
if(toggleBtn) toggleBtn.disabled = actionHistory.past.length === 0;
if(actionHistory.past.length === 0) closeHistoryPopover();
const listEl = document.getElementById("historyList");
if(!listEl) return;
if(!actionHistory.past.length){
listEl.innerHTML = `<div class="history-empty">${t('historyEmpty','No recent actions')}</div>`;
return;
}
listEl.innerHTML = actionHistory.past.map((entry, idx)=>{
const isLast = idx === actionHistory.past.length - 1;
return `<button type="button" class="history-item${isLast ? " is-latest" : ""}" data-history-idx="${idx}">
<span class="history-item-dot"></span>
<span class="history-item-label">${escapeHtml(entry.label)}</span>
<span class="history-item-undo">${isLast ? t('historyUndo','Undo') : t('historyUndoToHere','Undo to here')}</span>
</button>`;
}).reverse().join("");
}
function startLoadingButton(btn, label){
if(!btn) return;
if(btn.dataset.originalLabel === undefined) btn.dataset.originalLabel = btn.textContent;
if(label !== undefined) btn.textContent = label;
btn.setAttribute("aria-disabled", "true");
btn.classList.add("btn-loading");
if(!btn._slowLoadTimer){
btn._slowLoadTimer = setTimeout(()=>{
showToast(t('toastSlowLoad','**Taking more time than expected.** Modbench is still working on getting your mods added.'));
btn._slowLoadTimer = null;
}, 15000);
}
}
function stopLoadingButton(btn, finalLabel){
if(!btn) return;
btn.removeAttribute("aria-disabled");
btn.classList.remove("btn-loading");
btn.textContent = finalLabel !== undefined ? finalLabel : (btn.dataset.originalLabel ?? btn.textContent);
delete btn.dataset.originalLabel;
if(btn._slowLoadTimer){
clearTimeout(btn._slowLoadTimer);
btn._slowLoadTimer = null;
}
}
function isLoadingButton(btn){
return !!btn && btn.classList.contains("btn-loading");
}
const SUPABASE_URL = "https://nwshmuzkphmozilcpdti.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im53c2htdXprcGhtb3ppbGNwZHRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODczMzY2NTcsImV4cCI6MjEwMjkxMjY1N30.8nizLEGs7gckz3MSZvn9uznI_NqHD9fKJvMej-wyLiE";
const SHARE_TABLE = "shared_packs";
function shareBackendConfigured(){
return Boolean(SUPABASE_URL && SUPABASE_ANON_KEY);
}
const sb = (SUPABASE_URL && SUPABASE_ANON_KEY && window.supabase)
? window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
: null;
function authConfigured(){ return Boolean(sb); }
function cropImageToSquare(file, size = 256, quality = 0.86){
return new Promise((resolve, reject)=>{
const reader = new FileReader();
reader.onerror = ()=>reject(new Error("read failed"));
reader.onload = ()=>{
const img = new Image();
img.onerror = ()=>reject(new Error("decode failed"));
img.onload = ()=>{
const side = Math.min(img.naturalWidth, img.naturalHeight);
const sx = (img.naturalWidth - side) / 2;
const sy = (img.naturalHeight - side) / 2;
const canvas = document.createElement("canvas");
canvas.width = canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high";
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, size, size);
ctx.drawImage(img, sx, sy, side, side, 0, 0, size, size);
const dataUrl = canvas.toDataURL("image/jpeg", quality);
canvas.toBlob(blob=>{
if(blob) return resolve({ dataUrl, blob, width: size, height: size });
try{
const bin = atob(dataUrl.split(",")[1]);
const bytes = new Uint8Array(bin.length);
for(let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
resolve({ dataUrl, blob: new Blob([bytes], { type: "image/jpeg" }), width: size, height: size });
}catch(err){ reject(err); }
}, "image/jpeg", quality);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
});
}
function scrollToTopSmooth(){
const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
window.scrollTo({ top: 0, behavior: reduced ? "auto" : "smooth" });
}
function getInitials(email){
if(!email) return "?";
const namePart = email.split("@")[0];
const parts = namePart.split(/[._-]+/).filter(Boolean);
if(parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
return namePart.slice(0, 2).toUpperCase();
}
async function resolveGravatar(user){
if(!user || getAuthProvider(user) !== "email") return;
const email = (user.email || "").trim().toLowerCase();
if(!email) return;
const cacheKey = `modbench_gravatar_${user.id}`;
const cached = safeLocalStorageGet(cacheKey);
if(cached !== null) return;
if(!(window.crypto && window.crypto.subtle)) return;
try{
const buf = await window.crypto.subtle.digest("SHA-256", new TextEncoder().encode(email));
const hash = Array.from(new Uint8Array(buf)).map(b=>b.toString(16).padStart(2, "0")).join("");
const url = `https://www.gravatar.com/avatar/${hash}?s=200&d=404`;
const ok = await new Promise(resolve=>{
const img = new Image();
img.onload = ()=>resolve(true);
img.onerror = ()=>resolve(false);
img.src = url;
});
safeLocalStorageSet(cacheKey, ok ? url : "");
if(ok) renderAccountUI();
}catch(e){
console.warn("Gravatar lookup failed", e);
}
}
function getAvatarUrl(user){
const meta = user && user.user_metadata;
const remote = (meta && (meta.avatar_url || meta.picture)) || null;
if(remote) return remote;
if(user && getAuthProvider(user) === "email"){
return safeLocalStorageGet(`modbench_avatar_${user.id}`)
|| safeLocalStorageGet(`modbench_gravatar_${user.id}`)
|| null;
}
return null;
}
function canChangeAvatar(user){
return Boolean(user) && getAuthProvider(user) === "email";
}
function getAuthProvider(user){
return (user && user.app_metadata && user.app_metadata.provider) || "email";
}
function getDisplayName(user){
const meta = user && user.user_metadata;
return (meta && (meta.display_name || meta.full_name || meta.name)) || null;
}
function nameFromEmail(email){
const local = String(email || "").split("@")[0];
if(!local) return null;
const words = local
.replace(/[._-]+/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/\s*\d+\s*$/, "")
.trim()
.split(/\s+/)
.filter(Boolean);
if(!words.length) return null;
return words.map(w=>w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
}
function getProviderUsername(user){
const meta = user && user.user_metadata;
if(!meta) return null;
return meta.preferred_username || meta.user_name
|| (meta.custom_claims && meta.custom_claims.global_name) || null;
}
const SIGNIN_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path><polyline points="10 17 15 12 10 7"></polyline><line x1="15" y1="12" x2="3" y2="12"></line></svg>`;
const PROFILE_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>`;
const SYNC_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"></path><path d="M3 12a9 9 0 0 1 15-6.7L21 8"></path><path d="M3 22v-6h6"></path><path d="M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;
const AVATAR_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>`;
const RESTORE_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>`;
const SIGNOUT_ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>`;
function renderAccountUI(){
const slot = document.getElementById("accountSlot");
if(!slot) return;
closeAccountMenu(true);
refreshAllCardButtons();
if(typeof updateShareUsageDisplays === "function") updateShareUsageDisplays();
const user = state.user;
if(!user){
slot.innerHTML = `<button type="button" class="signin-btn" id="signInBtn">${SIGNIN_ICON_SVG}${t('signInBtn','Sign in')}</button>`;
document.getElementById("signInBtn").addEventListener("click", ()=>showAuthModal("signin"));
return;
}
const email = user.email || "";
const avatarUrl = getAvatarUrl(user);
const avatarInner = avatarUrl
? `<img src="${escapeHtml(avatarUrl)}" alt="" referrerpolicy="no-referrer">`
: escapeHtml(getInitials(email));
slot.innerHTML = `<button type="button" class="account-btn${avatarUrl ? ' has-avatar' : ''}" id="accountMenuBtn" aria-haspopup="true" aria-expanded="false" aria-label="${t('accountMenuLabel','Account menu')}" title="${escapeHtml(email)}">${avatarInner}</button>`;
const btn = document.getElementById("accountMenuBtn");
btn.addEventListener("click", (e)=>{
e.stopPropagation();
toggleAccountMenu();
});
if(avatarUrl){
const img = btn.querySelector("img");
if(img) img.addEventListener("error", ()=>{
btn.classList.remove("has-avatar");
btn.textContent = getInitials(email);
});
}
}
let accountMenuEl = null;
function closeAccountMenuOnOutsideClick(e){
if(accountMenuEl && !accountMenuEl.contains(e.target)) closeAccountMenu();
}
function closeAccountMenuOnEscape(e){
if(e.key === "Escape") closeAccountMenu();
}
function closeAccountMenu(immediate){
if(!accountMenuEl) return;
const el = accountMenuEl;
accountMenuEl = null;
document.removeEventListener("click", closeAccountMenuOnOutsideClick);
document.removeEventListener("keydown", closeAccountMenuOnEscape);
const btn = document.getElementById("accountMenuBtn");
if(btn) btn.setAttribute("aria-expanded", "false");
const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if(immediate || reduced){ el.remove(); return; }
el.setAttribute("aria-hidden", "true");
el.classList.add("closing");
let done = false;
const drop = ()=>{ if(done) return; done = true; el.remove(); };
el.addEventListener("animationend", drop, { once: true });
setTimeout(drop, 260);
}
function toggleAccountMenu(){
if(accountMenuEl){ closeAccountMenu(); return; }
if(typeof closeHeaderMenu === "function") closeHeaderMenu(true);
const slot = document.getElementById("accountSlot");
const btn = document.getElementById("accountMenuBtn");
if(!slot || !btn) return;
slot.querySelectorAll(".account-menu.closing").forEach(el=>el.remove());
const user = state.user;
const email = (user && user.email) || "";
const provider = getAuthProvider(user);
const displayName = getDisplayName(user);
let nameLine = null;
let subLine = email;
if(provider === "discord" && displayName){
nameLine = displayName;
const username = getProviderUsername(user);
subLine = username ? `@${username}` : email;
} else if(provider === "google" && displayName){
nameLine = displayName;
subLine = email;
} else {
nameLine = displayName || nameFromEmail(email);
subLine = email;
}
accountMenuEl = document.createElement("div");
accountMenuEl.className = "account-menu";
const avatarUrl = getAvatarUrl(user);
const avatarHtml = avatarUrl
? `<img class="account-menu-avatar" src="${escapeHtml(avatarUrl)}" alt="" referrerpolicy="no-referrer">`
: `<div class="account-menu-avatar account-menu-avatar-fallback">${escapeHtml(getInitials(email))}</div>`;
accountMenuEl.innerHTML = `
<div class="account-menu-header">
${avatarHtml}
<div class="account-menu-identity">
<strong>${escapeHtml(nameLine || t('accountSignedInAs','Signed in as'))}</strong>
<span>${escapeHtml(subLine)}</span>
</div>
</div>
<div class="account-status-row">
<button type="button" class="account-sync-note ${syncStatus === 'error' ? 'err' : ''}" id="accountSyncNote"><span class="dot"></span><span>${syncStatusLabel()}</span></button>
<span class="account-share-count" id="accountShareCount"></span>
</div>
<div class="account-menu-divider"></div>
${canChangeAvatar(user) ? `<button type="button" class="menu-item" id="changeAvatarBtn">${AVATAR_ICON_SVG}${t('changeAvatarBtn','Change profile picture')}</button>` : ""}
<button type="button" class="menu-item" id="restoreSyncBtn">${RESTORE_ICON_SVG}${t('restoreSyncBtn','Restore from account')}</button>
<div class="account-menu-divider"></div>
<button type="button" class="menu-item danger" id="signOutBtn">${SIGNOUT_ICON_SVG}${t('signOutBtn','Sign out')}</button>
`;
if(avatarUrl){
const avatarImg = accountMenuEl.querySelector("img.account-menu-avatar");
if(avatarImg) avatarImg.addEventListener("error", ()=>{
avatarImg.outerHTML = `<div class="account-menu-avatar account-menu-avatar-fallback">${escapeHtml(getInitials(email))}</div>`;
});
}
slot.appendChild(accountMenuEl);
btn.setAttribute("aria-expanded", "true");
document.getElementById("signOutBtn").addEventListener("click", handleSignOut);
updateAccountShareCounter();
refreshShareUsageFromServer();
const avatarBtn = document.getElementById("changeAvatarBtn");
if(avatarBtn) avatarBtn.addEventListener("click", (e)=>{ e.stopPropagation(); showAvatarModal(); });
const restoreBtn = document.getElementById("restoreSyncBtn");
if(restoreBtn) restoreBtn.addEventListener("click", (e)=>{ e.stopPropagation(); restoreFromAccount(); });
const syncNote = document.getElementById("accountSyncNote");
if(syncNote) syncNote.addEventListener("click", (e)=>{
e.stopPropagation();
if(syncStatus !== "error") return;
showToast(lastSyncError || t('syncErrUnknown',"Sync failed for an unknown reason."), { duration: 11000 });
});
setTimeout(()=>{
document.addEventListener("click", closeAccountMenuOnOutsideClick);
document.addEventListener("keydown", closeAccountMenuOnEscape);
}, 0);
}
async function handleSignOut(){
closeAccountMenu();
if(!sb) return;
try{
const savedToAccount = await finalizeSyncBeforeSignOut();
signedOutIntentionally = true;
await sb.auth.signOut();
if(savedToAccount){
clearLocalAccountData();
showToast(t('toastSignedOut','Signed out.'));
} else {
showToast(t('toastSignOutKeptLocal',"Signed out. Your last changes couldn't be confirmed as saved, so they're kept on this device."), { duration: 8000 });
}
}catch(e){
console.error("Sign out failed", e);
showToast(t('toastSignOutError',"Couldn't sign out, try again."));
}
}
const PW_REVEAL_MS = 650;
const PW_MASK_CHAR = "\u2022";
const PW_ICON_EYE = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>`;
const PW_ICON_EYE_OFF = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a20.7 20.7 0 0 1 5.06-6.06M9.9 4.24A10.4 10.4 0 0 1 12 4c7 0 11 8 11 8a20.6 20.6 0 0 1-3.22 4.66M14.12 14.12a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>`;
function stripSpaces(input){
const value = input.value;
if(!/\s/.test(value)) return value;
const selStart = input.selectionStart ?? value.length;
const spacesBefore = (value.slice(0, selStart).match(/\s/g) || []).length;
const cleaned = value.replace(/\s/g, "");
input.value = cleaned;
const newPos = Math.max(0, selStart - spacesBefore);
try{ input.setSelectionRange(newPos, newPos); }catch(e){ }
return cleaned;
}
function attachPasswordReveal(input){
if(!input || input.dataset.pwRevealAttached) return;
const wrap = input.closest(".auth-field-input-wrap") || input.parentElement;
if(!wrap) return;
input.dataset.pwRevealAttached = "1";
input.classList.add("pw-reveal-input");
const overlay = document.createElement("div");
overlay.className = "pw-reveal-overlay";
overlay.setAttribute("aria-hidden", "true");
wrap.appendChild(overlay);
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "pw-reveal-toggle";
wrap.appendChild(toggle);
const caret = document.createElement("div");
caret.className = "pw-fake-caret";
caret.setAttribute("aria-hidden", "true");
wrap.appendChild(caret);
const state = { prevValue: input.value || "", revealFrom: null, revealTo: null, timer: null, forceShow: false };
const measureCanvas = document.createElement("canvas");
const measureCtx = measureCanvas.getContext("2d");
function textWidth(str){
measureCtx.font = getComputedStyle(overlay).font;
return measureCtx.measureText(str).width;
}
function render(){
const value = input.value;
let out = "";
for(let i = 0; i < value.length; i++){
const revealed = state.forceShow || (state.revealFrom !== null && i >= state.revealFrom && i < state.revealTo);
out += revealed ? value[i] : PW_MASK_CHAR;
}
overlay.textContent = out;
syncScroll();
}
function syncScroll(){
const text = overlay.textContent;
const caretIndex = Math.max(0, Math.min(text.length, input.selectionEnd ?? text.length));
const caretX = textWidth(text.slice(0, caretIndex));
const visible = overlay.clientWidth;
const maxScroll = Math.max(0, overlay.scrollWidth - visible);
const pad = 2;
let target = overlay.scrollLeft;
if(caretX - target > visible - pad) target = caretX - visible + pad;
if(caretX - target < pad) target = caretX - pad;
target = Math.max(0, Math.min(target, maxScroll));
overlay.scrollLeft = target;
const padLeft = parseFloat(getComputedStyle(overlay).paddingLeft) || 0;
caret.style.left = (padLeft + caretX - target) + "px";
}
function maskAll(){
clearTimeout(state.timer);
state.timer = null;
state.revealFrom = null;
state.revealTo = null;
render();
}
function updateToggleUI(){
const label = state.forceShow ? t('authHidePassword','Hide password') : t('authShowPassword','Show password');
toggle.innerHTML = state.forceShow ? PW_ICON_EYE_OFF : PW_ICON_EYE;
toggle.setAttribute("aria-label", label);
toggle.title = label;
toggle.setAttribute("aria-pressed", state.forceShow ? "true" : "false");
}
input.addEventListener("keydown", (e)=>{
if(e.key === " ") e.preventDefault();
});
input.addEventListener("input", ()=>{
const value = stripSpaces(input);
const prev = state.prevValue;
const minLen = Math.min(prev.length, value.length);
let common = 0;
while(common < minLen && prev[common] === value[common]) common++;
state.prevValue = value;
if(state.forceShow){ render(); return; }
clearTimeout(state.timer);
if(value.length > common){
state.revealFrom = common;
state.revealTo = value.length;
state.timer = setTimeout(()=>{
state.revealFrom = null;
state.revealTo = null;
render();
}, PW_REVEAL_MS);
} else {
state.revealFrom = null;
state.revealTo = null;
}
render();
});
input.addEventListener("click", syncScroll);
input.addEventListener("keyup", (e)=>{
if(["ArrowLeft","ArrowRight","Home","End"].includes(e.key)) syncScroll();
});
input.addEventListener("change", ()=>{ state.prevValue = stripSpaces(input); render(); });
input.addEventListener("focus", ()=>{ caret.classList.add("active"); syncScroll(); });
input.addEventListener("blur", ()=>{ caret.classList.remove("active"); if(!state.forceShow) maskAll(); });
toggle.addEventListener("mousedown", (e)=>{ e.preventDefault(); });
toggle.addEventListener("click", ()=>{
state.forceShow = !state.forceShow;
clearTimeout(state.timer);
state.timer = null;
state.revealFrom = null;
state.revealTo = null;
updateToggleUI();
render();
input.focus();
});
updateToggleUI();
render();
}
function gradePassword(pw){
const hasLower = /[a-z]/.test(pw);
const hasUpper = /[A-Z]/.test(pw);
const hasNumber = /[0-9]/.test(pw);
const hasSymbol = /[^A-Za-z0-9]/.test(pw);
const reqs = {
length: pw.length >= 8,
case: hasUpper,
number: hasNumber,
symbol: hasSymbol
};
let points = 0;
if(pw.length >= 8) points++;
if(pw.length >= 12) points++;
if(hasLower) points++;
if(hasUpper) points++;
if(hasNumber) points++;
if(hasSymbol) points++;
let level = 0;
if(pw.length > 0){
if(points <= 1) level = 1;
else if(points <= 3) level = 2;
else if(points === 4) level = 3;
else level = 4;
}
return { level, reqs };
}
const PW_STRENGTH_LEVELS = [
null,
{ key:'weak', label: ()=>t('authPwStrengthWeak','Weak') },
{ key:'fair', label: ()=>t('authPwStrengthFair','Fair') },
{ key:'good', label: ()=>t('authPwStrengthGood','Good') },
{ key:'strong', label: ()=>t('authPwStrengthStrong','Strong') }
];
const PW_REQ_ICON_CHECK = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
const PW_REQ_ICON_DOT = `<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="4"></circle></svg>`;
function pwStrengthMarkup(idPrefix){
return `
<div class="pw-strength" id="${idPrefix}Strength" aria-live="polite">
<div class="pw-strength-bar">
<div class="pw-strength-seg"></div>
<div class="pw-strength-seg"></div>
<div class="pw-strength-seg"></div>
<div class="pw-strength-seg"></div>
</div>
<div class="pw-strength-label"></div>
<ul class="pw-requirements">
<li data-req="length"><span class="pw-req-icon">${PW_REQ_ICON_DOT}</span><span>${t('authPwReqLength','8 characters or more')}</span></li>
<li data-req="case"><span class="pw-req-icon">${PW_REQ_ICON_DOT}</span><span>${t('authPwReqCase','At least one uppercase letter')}</span></li>
<li data-req="number"><span class="pw-req-icon">${PW_REQ_ICON_DOT}</span><span>${t('authPwReqNumber','At least one number')}</span></li>
<li data-req="symbol"><span class="pw-req-icon">${PW_REQ_ICON_DOT}</span><span>${t('authPwReqSymbol','At least one symbol')}</span></li>
</ul>
</div>`;
}
function attachPasswordStrength(input, container){
if(!input || !container || input.dataset.pwStrengthAttached) return;
input.dataset.pwStrengthAttached = "1";
const segs = container.querySelectorAll(".pw-strength-seg");
const labelEl = container.querySelector(".pw-strength-label");
const reqEls = container.querySelectorAll(".pw-requirements li");
function update(){
const { level, reqs } = gradePassword(input.value);
const meta = level > 0 ? PW_STRENGTH_LEVELS[level] : null;
segs.forEach((seg, i)=>{
seg.className = "pw-strength-seg" + (meta && i < level ? " filled-" + meta.key : "");
});
labelEl.textContent = meta ? meta.label() : "";
labelEl.className = "pw-strength-label" + (meta ? " " + meta.key : "");
reqEls.forEach(li=>{
const met = !!reqs[li.dataset.req];
li.classList.toggle("met", met);
li.querySelector(".pw-req-icon").innerHTML = met ? PW_REQ_ICON_CHECK : PW_REQ_ICON_DOT;
});
}
input.addEventListener("input", update);
update();
}
function friendlyAuthError(err){
if(!err) return t('authErrGeneric','Something went wrong. Try again.');
const msg = err.message || String(err);
if(msg.includes("Invalid login credentials")) return t('authErrInvalidCreds','Incorrect email or password.');
if(msg.includes("User already registered")) return t('authErrAlreadyRegistered','An account with that email already exists — try signing in instead.');
if(msg.includes("Email not confirmed")) return t('authErrEmailNotConfirmed','Check your inbox and confirm your email before signing in.');
if(/password/i.test(msg) && /(least|short|6 char)/i.test(msg)) return t('authErrWeakPassword','Password must be at least 6 characters.');
if(/email/i.test(msg) && /invalid/i.test(msg)) return t('authErrInvalidEmail',"That doesn't look like a valid email address.");
if(/rate limit/i.test(msg)) return t('authErrRateLimited','Too many attempts — wait a bit and try again.');
return msg;
}
function dismissModalBackdrop(backdrop){
if(!backdrop || backdrop.dataset.closing === "1"){ return; }
const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if(reduced){ backdrop.remove(); return; }
backdrop.dataset.closing = "1";
backdrop.classList.add("closing");
let done = false;
const drop = ()=>{ if(done) return; done = true; backdrop.remove(); };
backdrop.addEventListener("animationend", drop, { once: true });
setTimeout(drop, 300);
}
// Explicit allowlist rather than "starts with image/": SVG is technically
// an image MIME type but can embed <script>/event-handler payloads, so it's
// deliberately excluded from anything we render back (avatar, pack icon).
const ALLOWED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
function isAllowedImageFile(file){
return Boolean(file) && ALLOWED_IMAGE_TYPES.includes(file.type);
}
const AVATAR_BUCKET = "avatars";
async function uploadAvatarToStorage(blob){
if(!state.user || !state.session) throw new Error("not signed in");
const path = `${state.user.id}/avatar.jpg`;
const res = await fetch(`${SUPABASE_URL}/storage/v1/object/${AVATAR_BUCKET}/${path}`, {
method: "POST",
headers: {
"apikey": SUPABASE_ANON_KEY,
"Authorization": `Bearer ${state.session.access_token}`,
"Content-Type": "image/jpeg",
"x-upsert": "true"
},
body: blob
});
if(!res.ok){
let detail = "";
try{ detail = await res.text(); }catch(e){}
const err = new Error(`avatar upload failed (${res.status}) ${detail}`);
err.missingBucket = res.status === 404 || /Bucket not found/i.test(detail);
throw err;
}
return `${SUPABASE_URL}/storage/v1/object/public/${AVATAR_BUCKET}/${path}?v=${Date.now()}`;
}
function showAvatarModal(){
if(!canChangeAvatar(state.user)) return;
closeAccountMenu(true);
document.querySelectorAll(".modal-backdrop").forEach(b=>dismissModalBackdrop(b));
const backdrop = document.createElement("div");
backdrop.className = "modal-backdrop";
backdrop.style.alignItems = "center";
const current = getAvatarUrl(state.user);
backdrop.innerHTML = `
<div class="modal auth-modal avatar-modal">
<div class="modal-head" style="margin-bottom:14px;">
<div class="name" style="font-size:1.1rem;">${t('avatarTitle','Your profile')}</div>
<button class="modal-close" id="avatarCloseBtn" aria-label="${t('close','Close')}">✕</button>
</div>
<div class="avatar-preview-wrap">
<div class="avatar-preview" id="avatarPreview">
${current ? `<img src="${escapeHtml(current)}" alt="">` : `<span>${escapeHtml(getInitials(state.user.email || ""))}</span>`}
</div>
</div>
<div class="auth-field" style="margin-bottom:16px;">
<label for="displayNameInput" style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-dim); margin-bottom:6px;">${t('displayNameLabel','Display name')}</label>
<input type="text" id="displayNameInput" maxlength="40" autocomplete="nickname"
placeholder="${escapeHtml(nameFromEmail(state.user.email || "") || "")}"
value="${escapeHtml(getDisplayName(state.user) || "")}"
style="width:100%;">
<p style="margin:6px 0 0; font-size:0.76rem; color:var(--text-dim);">${t('displayNameHint','Leave empty to use the name derived from your email address.')}</p>
</div>
<div class="avatar-drop" id="avatarDrop" tabindex="0" role="button" aria-label="${t('avatarDropLabel','Choose or drop an image')}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
<strong>${t('avatarDropTitle','Drop an image here')}</strong>
<span>${t('avatarDropHint','or click to browse · PNG, JPG or WebP, up to 5 MB')}</span>
</div>
<input type="file" id="avatarFileInput" accept="image/png,image/jpeg,image/webp,image/gif" hidden>
<p class="avatar-note" id="avatarNote" hidden></p>
<div class="avatar-actions">
${current ? `<button type="button" class="page-btn" id="avatarRemoveBtn">${t('avatarRemove','Remove')}</button>` : ""}
<button type="button" class="export-btn" id="avatarSaveBtn" style="margin:0; flex:1;">${t('avatarSave','Save changes')}</button>
</div>
</div>`;
document.body.appendChild(backdrop);
const drop = backdrop.querySelector("#avatarDrop");
const input = backdrop.querySelector("#avatarFileInput");
const preview = backdrop.querySelector("#avatarPreview");
const saveBtn = backdrop.querySelector("#avatarSaveBtn");
const note = backdrop.querySelector("#avatarNote");
const removeBtn = backdrop.querySelector("#avatarRemoveBtn");
let pending = null;
function setNote(msg, kind){
if(!msg){ note.hidden = true; note.textContent = ""; return; }
note.hidden = false;
note.textContent = msg;
note.className = "avatar-note" + (kind ? " " + kind : "");
}
async function accept(file){
if(!file) return;
if(!isAllowedImageFile(file)){
setNote(t('avatarNotImage',"That file isn't an image."), "err");
return;
}
if(file.size > 5 * 1024 * 1024){
setNote(t('avatarTooBig',"That image is over 5 MB. Pick a smaller one."), "err");
return;
}