-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
8642 lines (8216 loc) Β· 431 KB
/
Copy pathserver.mjs
File metadata and controls
8642 lines (8216 loc) Β· 431 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import http from 'http';
import https from 'https';
import fs from 'fs';
import path from 'path';
import zlib from 'zlib';
import crypto from 'crypto';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
import { createBackupManager } from './server/backup-manager.mjs';
import {
buildCanonicalBackupPayload as normalizeToCanonicalBackupPayload,
mergeBackupData as mergeNormalizedBackupData,
} from './public/sync/backup-normalizer.js';
// ββ Simple in-memory rate limiter for auth routes βββββββββββββββββββββββββββββ
const _rateLimiter = new Map(); // ip β { count, resetAt }
const RATE_LIMIT_MAX = 10; // max requests per window per IP
const RATE_LIMIT_WIN = 60000; // 60-second window
function checkRateLimit(ip) {
const now = Date.now();
let entry = _rateLimiter.get(ip);
if (!entry || now > entry.resetAt) {
entry = { count: 0, resetAt: now + RATE_LIMIT_WIN };
_rateLimiter.set(ip, entry);
}
entry.count++;
return entry.count <= RATE_LIMIT_MAX; // true = allowed
}
// Prune stale entries every 5 minutes to avoid memory growth
setInterval(() => {
const now = Date.now();
for (const [k, v] of _rateLimiter) if (now > v.resetAt) _rateLimiter.delete(k);
}, 5 * 60 * 1000).unref();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_DIR = path.join(__dirname, 'public');
process.on('unhandledRejection', (err) => {
console.error('[Runtime] Unhandled promise rejection:', err && err.message ? err.message : err);
});
// ββ Auto-load .env file βββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Allows starting with just `node server.mjs`; host environment values win.
function loadDotEnvIfNeeded(filePath) {
try {
if (!fs.existsSync(filePath)) return { loaded: false, count: 0 };
let count = 0;
const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
for (const raw of lines) {
const line = raw.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq < 1) continue;
const key = line.slice(0, eq).trim();
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
if (Object.prototype.hasOwnProperty.call(process.env, key) && process.env[key] !== '') continue;
let val = line.slice(eq + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) ||
(val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
process.env[key] = val.replace(/\\n/g, '\n');
count++;
}
return { loaded: true, count };
} catch (e) {
console.warn('[Config] Could not load .env:', e.message);
return { loaded: false, count: 0 };
}
}
const _dotenvResults = [
loadDotEnvIfNeeded(path.join(__dirname, '.env')),
loadDotEnvIfNeeded(path.join(__dirname, '..', '..', '.env')),
].filter(r => r.loaded);
if (_dotenvResults.length) {
const count = _dotenvResults.reduce((sum, r) => sum + r.count, 0);
console.log(`[Config] .env loaded (${count} values applied)`);
}
const port = process.env.PORT || 3000;
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.json': 'application/json',
'.webmanifest': 'application/manifest+json',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.webp': 'image/webp',
'.txt': 'text/plain',
'.map': 'application/json',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.mov': 'video/quickstart',
'.ogv': 'video/ogg',
'.mkv': 'video/x-matroska',
};
const NO_STORE_CACHE = 'no-cache, no-store, must-revalidate';
const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';
const SHORT_CACHE = 'no-cache';
const RUNTIME_GLUE_PATHS = new Set([
'/',
'/index.html',
'/auth-bridge.js',
'/restore-and-launch.js',
'/pwa-local.js',
'/boot-recovery.js',
'/ux-setup.js',
'/focus-bg-import.js',
'/update-checker.js',
'/sw.js',
'/manifest.webmanifest',
]);
const RUNTIME_PATCHED_ASSET_PATHS = new Set([
'/assets/useAIStore-B2cv1FZz.js',
'/assets/App-pJGjDiPw.js',
'/assets/Auth-Cw0VAaCZ.js',
'/assets/Focus-BmgY-9vP.js',
'/assets/Onboarding-qvAqCBbb.js',
'/assets/SingleGroup-DU1IhoNK.js',
'/assets/useLeaderboard-BpvH5FXA.js',
'/assets/SettingsLayout-B4OgCkQ5.js',
'/assets/useSyncStore-vWs_TdIc.js',
'/assets/AppAccessGate-B975UtK7.js',
'/assets/sessionSync-mloIEnTd.js',
'/assets/useInvites-D9RLFwf8.js',
'/assets/Community-DIqF5406.js',
'/assets/CommunityHub-gANxZssO.js',
'/assets/FocusStore-D5cRXSIr.js',
'/assets/EventsCalendar-COHF8nOK.js',
'/assets/PWAManager-DjIYufp2.js',
]);
function isRuntimePatchedAsset(pathname) {
const clean = String(pathname || '/').split('?')[0] || '/';
return RUNTIME_PATCHED_ASSET_PATHS.has(clean);
}
function isHashedStaticAsset(pathname) {
const base = path.basename(String(pathname || '').split('?')[0]);
return /[-_][A-Za-z0-9_-]{6,14}\.(?:js|css|woff2?)$/i.test(base);
}
function cacheHeaderForRequest(pathname) {
const clean = String(pathname || '/').split('?')[0] || '/';
if (RUNTIME_GLUE_PATHS.has(clean) || clean.startsWith('/sync/')) return NO_STORE_CACHE;
if (isRuntimePatchedAsset(clean)) return NO_STORE_CACHE;
if (clean.endsWith('.html')) return NO_STORE_CACHE;
if (clean.startsWith('/assets/') && isHashedStaticAsset(clean)) return IMMUTABLE_CACHE;
return SHORT_CACHE;
}
const GEMINI_API_KEY = process.env.GEMINI_API_KEY || '';
const GROQ_API_KEY = process.env.GROQ_API_KEY || '';
// Default public cloud sync target for normal downloaded installs. These are
// anon/public Supabase values only; service-role/admin credentials remain env-only.
const DEFAULT_SUPABASE_URL = "https://vteqquoqvksshmfhuepu.supabase.co";
const DEFAULT_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ0ZXFxdW9xdmtzc2htZmh1ZXB1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODAwODU2NzUsImV4cCI6MjA5NTY2MTY3NX0.ZkRislOhJRQUjVa1y5ixu-xBhlgkXWWyZKI_CClWj64";
// ββ Required environment variables β hard-fail at startup if missing ββββββββββ
// All credentials MUST come from environment variables (.env or host environment).
// No fallback values are allowed β this prevents accidental credential exposure
// if someone forks or clones the repo without setting up their own secrets.
if (!process.env.SUPABASE_URL) process.env.SUPABASE_URL = DEFAULT_SUPABASE_URL;
if (!process.env.SUPABASE_ANON_KEY) process.env.SUPABASE_ANON_KEY = DEFAULT_SUPABASE_ANON_KEY;
const _missingEnv = ['SUPABASE_URL', 'SUPABASE_ANON_KEY']
.filter(k => !process.env[k]);
if (_missingEnv.length) {
console.error('[Config] Missing required environment variables:', _missingEnv.join(', '));
console.error('[Config] Set them in .env or your host environment. See .env.example for guidance.');
process.exit(1);
}
try {
const u = new URL(process.env.SUPABASE_URL);
if (!/^https?:$/.test(u.protocol) || !u.hostname.endsWith('.supabase.co')) {
throw new Error('SUPABASE_URL must be a Supabase project URL');
}
} catch (e) {
console.error('[Config] Invalid SUPABASE_URL:', e.message);
process.exit(1);
}
for (const keyName of ['SUPABASE_ANON_KEY']) {
const val = process.env[keyName] || '';
if (val.split('.').length < 3) {
console.error(`[Config] ${keyName} must be a JWT-like value`);
process.exit(1);
}
}
// ββ Supabase project β loaded exclusively from environment variables ββββββββββ
const SUPA_URL = process.env.SUPABASE_URL;
const SUPA_ANON_KEY = process.env.SUPABASE_ANON_KEY;
const SUPA_SERVICE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || '';
if (SUPA_SERVICE_KEY && SUPA_SERVICE_KEY.split('.').length < 3) {
console.error('[Config] SUPABASE_SERVICE_ROLE_KEY is set but is not JWT-like');
process.exit(1);
}
// ββ Admin panel access control ββββββββββββββββββββββββββββββββββββββββββββββββ
// Admin mode is explicit opt-in for owners/operators. Normal downloaded/local
// user mode must not require or expose service-role credentials.
const ENABLE_ADMIN_MODE = /^(1|true|yes)$/i.test(process.env.ENABLE_ADMIN_MODE || '');
const ADMIN_SECRET = process.env.ADMIN_SECRET || '';
// Admin user password β used when auto-creating the admin account on first boot.
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
// Admin email β used for admin user creation + verify check.
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || '';
const ADMIN_EMAILS = Array.from(new Set(
[ADMIN_EMAIL, ...(process.env.ADMIN_EMAILS || '').split(',')]
.map((v) => String(v || '').trim().toLowerCase())
.filter(Boolean)
));
const BROWSER_PROOF_EMAIL = String(process.env.BROWSER_PROOF_EMAIL || ADMIN_EMAIL || ADMIN_EMAILS[0] || '').trim().toLowerCase();
const ADMIN_COOKIE_SECRET = ADMIN_SECRET || SUPA_SERVICE_KEY;
const ADMIN_MODE_READY = ENABLE_ADMIN_MODE && !!SUPA_SERVICE_KEY && !!ADMIN_COOKIE_SECRET;
function isAdminAuthed(req) {
if (!ADMIN_MODE_READY) return false;
const headerTok = (req.headers['x-admin-secret'] || '').trim();
let queryTok = '';
try {
const sp = new URL('http://x' + req.url).searchParams;
queryTok = sp.get('secret') || '';
} catch {}
const cookieTok = readCookie(req, 'iso_admin');
return (!!ADMIN_SECRET && (headerTok === ADMIN_SECRET || queryTok === ADMIN_SECRET)) || cookieTok === adminCookieValue();
}
function readCookie(req, name) {
const raw = req.headers.cookie || '';
const prefix = name + '=';
for (const part of raw.split(';')) {
const item = part.trim();
if (item.startsWith(prefix)) return decodeURIComponent(item.slice(prefix.length));
}
return '';
}
function adminCookieValue() {
if (!ADMIN_COOKIE_SECRET) return '';
return 'v1.' + crypto.createHmac('sha256', ADMIN_COOKIE_SECRET).update('isotope-admin-cookie').digest('hex');
}
function isRequestHttps(req) {
const fwdProto = req.headers['x-forwarded-proto'];
if (fwdProto) return fwdProto.split(',')[0].trim().toLowerCase() === 'https';
return !!(req.socket && req.socket.encrypted);
}
function escapeHtml(value) {
return String(value || '').replace(/[&<>"']/g, (ch) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[ch]));
}
function readRequestText(req, maxBytes = 16384) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
if (body.length > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
}
});
req.on('end', () => resolve(body));
req.on('error', reject);
});
}
function verifySupabaseAccessToken(token) {
return new Promise((resolve, reject) => {
if (!token || String(token).split('.').length < 3) {
reject(new Error('Missing Supabase access token'));
return;
}
const u = new URL(SUPA_URL);
const rq = https.request({
hostname: u.hostname,
path: '/auth/v1/user',
method: 'GET',
headers: {
Authorization: 'Bearer ' + token,
apikey: SUPA_ANON_KEY,
Accept: 'application/json',
},
}, (r) => {
let body = '';
r.on('data', (chunk) => body += chunk);
r.on('end', () => {
try {
const json = JSON.parse(body || '{}');
if (r.statusCode >= 400 || !json.id) {
reject(new Error('Supabase session is not valid'));
return;
}
resolve(json);
} catch {
reject(new Error('Supabase auth response was invalid'));
}
});
});
rq.on('error', reject);
rq.setTimeout(10000, () => { rq.destroy(); reject(new Error('Supabase auth timeout')); });
rq.end();
});
}
async function isSupabaseAdminUser(user) {
const email = String(user?.email || '').trim().toLowerCase();
if (email && ADMIN_EMAILS.includes(email)) return true;
if (!ADMIN_MODE_READY || !user?.id) return false;
try {
const q = '/rest/v1/user_roles'
+ '?select=role'
+ '&user_id=eq.' + encodeURIComponent(user.id)
+ '&limit=10';
const r = await supaRestReq('GET', q, null);
if (r.status >= 400 || !Array.isArray(r.body)) return false;
return r.body.some((row) => /^(owner|admin|super_admin)$/i.test(String(row.role || '')));
} catch {
return false;
}
}
async function authenticateAdminUnlock(secret, token) {
if (ADMIN_SECRET && secret && secret === ADMIN_SECRET) return { ok: true };
if (token) {
const user = await verifySupabaseAccessToken(token);
if (await isSupabaseAdminUser(user)) return { ok: true, email: user.email || '' };
return { ok: false, error: 'Supabase user is not listed as an admin.' };
}
return { ok: false, error: 'Enter ADMIN_SECRET or log in as a configured Supabase admin.' };
}
function sendAdminLogin(req, res, message = '') {
let next = '/__admin/verify';
try {
const u = new URL('http://x' + req.url);
const requested = u.searchParams.get('next');
if (requested && requested.startsWith('/__admin/')) next = requested;
else if (u.pathname.startsWith('/__admin/') && u.pathname !== '/__admin/login') next = u.pathname + u.search;
} catch {}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(`<!doctype html><html><head><meta charset="utf-8"><title>Isotope Admin Login</title><style>body{font-family:system-ui;background:#0a0a0a;color:#eee;margin:0;padding:32px}.box{max-width:500px;margin:8vh auto;background:#111;border:1px solid #333;border-radius:10px;padding:24px}input{width:100%;box-sizing:border-box;background:#050505;color:#fff;border:1px solid #333;border-radius:8px;padding:12px;margin:10px 0 14px}button{background:#7c3aed;color:white;border:0;border-radius:8px;padding:11px 16px;font-weight:700;margin-right:8px}.secondary{background:#27272a}.err{color:#fca5a5;font-size:13px}.muted{color:#aaa;font-size:13px;line-height:1.5}</style></head><body><main class="box"><h1>Admin Unlock</h1><p class="muted">Enter your local <code>ADMIN_SECRET</code>, or use the Supabase account already logged into this browser. Supabase unlock requires the account email in private <code>ADMIN_EMAIL</code>/<code>ADMIN_EMAILS</code> or an active admin role in <code>user_roles</code>.</p>${message ? `<p class="err">${escapeHtml(message)}</p>` : ''}<form id="adminForm" method="post" action="/__admin/login"><input type="hidden" name="next" value="${escapeHtml(next)}"><input type="hidden" id="supabaseToken" name="token" value=""><input type="password" name="secret" autocomplete="current-password" autofocus placeholder="ADMIN_SECRET"><button type="submit">Open with Secret</button><button class="secondary" id="useSession" type="button">Use Supabase Login</button></form><p id="sessionMsg" class="muted"></p></main><script>(function(){var msg=document.getElementById('sessionMsg');function parse(raw){try{var p=JSON.parse(raw);if(p&&p.access_token)return p.access_token;if(p&&p.session&&p.session.access_token)return p.session.access_token;if(p&&p.currentSession&&p.currentSession.access_token)return p.currentSession.access_token;if(p&&p.state&&p.state.session&&p.state.session.access_token)return p.state.session.access_token;}catch(e){}return ''}function token(){try{var keys=['isotope-last-session-raw','isotope-auth-token'];for(var i=0;i<localStorage.length;i++){var k=localStorage.key(i);if(k&&k.indexOf('sb-')===0&&/-auth-token$/.test(k))keys.push(k);}for(var j=0;j<keys.length;j++){var t=parse(localStorage.getItem(keys[j]));if(t)return t;}}catch(e){}return ''}document.getElementById('useSession').onclick=function(){var t=token();if(!t){msg.textContent='No logged-in Supabase session found in this browser. Log into the app first, then reopen admin.';return;}document.getElementById('supabaseToken').value=t;document.getElementById('adminForm').submit();};})();</script></body></html>`);
}
function sendAdminDisabled(req, res) {
const missing = [];
if (!ENABLE_ADMIN_MODE) missing.push('ENABLE_ADMIN_MODE=true');
if (!SUPA_SERVICE_KEY) missing.push('SUPABASE_SERVICE_ROLE_KEY');
const payload = {
ok: false,
owner_tools: 'not_enabled',
message: 'The local app is ready. Owner tools are private and are not enabled for this install.',
enable_with: missing,
};
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(`<!doctype html><html><head><meta charset="utf-8"><title>Owner Tools</title><style>body{font-family:system-ui;background:#0a0a0a;color:#eee;margin:0;padding:32px}.box{max-width:720px;margin:auto;background:#111;border:1px solid #333;border-radius:10px;padding:24px}code{background:#222;padding:2px 6px;border-radius:4px;color:#a78bfa}a{color:#8b5cf6}</style></head><body><div class="box"><h1>Owner Tools Are Private</h1><p>The Isotope local app is running normally. This page is only for the project owner to manage Supabase diagnostics, schema patches, and event/admin data.</p><p>Normal users can return to <a href="/">the app</a>.</p><p>Owners can enable this area with <code>ENABLE_ADMIN_MODE=true</code> and <code>SUPABASE_SERVICE_ROLE_KEY</code> in a private <code>.env</code>, then restart. Add <code>ADMIN_SECRET</code> for local secret unlock, or <code>ADMIN_EMAIL</code>/<code>ADMIN_EMAILS</code> for Supabase login unlock.</p></div></body></html>`);
return;
}
res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(payload));
}
function adminEmailDisplay() {
// Redact most of the email to avoid leaking it in verify HTML
return ADMIN_EMAIL.replace(/^(.{2})(.*)(@.{2})(.*)(\..+)$/, '$1***$3***$5');
}
// Bundles are normalized at serve time so clients use this operator's env config.
const CUSTOM_SUPA = true;
const PROXY_PATH = '/__supa';
if (ADMIN_MODE_READY) console.log('[Admin] Admin mode enabled for server-only Supabase management');
else if (ENABLE_ADMIN_MODE) console.warn('[Admin] Admin mode requested but disabled: set SUPABASE_SERVICE_ROLE_KEY');
if (CUSTOM_SUPA) {
console.log('[Cloud] Supabase cloud sync target ready');
}
// ββ AI key injection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function buildKeyScript() {
const keys = {};
if (GEMINI_API_KEY) keys.gemini = GEMINI_API_KEY;
if (GROQ_API_KEY) keys.groq = GROQ_API_KEY;
if (Object.keys(keys).length === 0) return '';
return `<script>
(function(){
var k=${JSON.stringify(keys)};
window.__IK__=new Proxy(k,{
get:function(t,p){
if(typeof navigator!=="undefined"&&!navigator.onLine)return undefined;
return t[p];
}
});
})();
</script>`;
}
const KEY_SCRIPT = buildKeyScript();
// ββ Username-auth client helper (injected into every HTML page) βββββββββββββββ
// Build dynamically so SUPA_REF reflects the actual SUPA_URL env var at startup
function buildUsernameAuthScript() {
const supaRef = new URL(SUPA_URL).hostname.split('.')[0];
return `<script>
(function(){
'use strict';
var SUPA_REF = '${supaRef}';
var SUPA_URL_BASE = '${SUPA_URL}';
var SUPA_ANON = '${SUPA_ANON_KEY}';
// ββ JWT deep-extractor ββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Recursively scans any JSON value for a JWT-shaped string (eyJβ¦).
// Handles every known Supabase session storage format without fragile key paths.
function _deepFindJwt(obj) {
if (!obj) return null;
if (typeof obj === 'string') {
if (/^eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/.test(obj)) return obj;
try { return _deepFindJwt(JSON.parse(obj)); } catch(e) { return null; }
}
if (typeof obj !== 'object') return null;
// Prefer access_token if present at this level (most common)
if (typeof obj.access_token === 'string' && obj.access_token.startsWith('eyJ')) return obj.access_token;
// Recurse: check all object values
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var v = obj[keys[i]];
if (typeof v === 'string' && /^eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/.test(v)) return v;
if (v && typeof v === 'object') {
var found = _deepFindJwt(v);
if (found) return found;
}
}
return null;
}
// Also deep-scan for refresh_token (string that does NOT look like a JWT)
function _deepFindRefreshToken(obj) {
if (!obj) return null;
if (typeof obj !== 'object') return null;
if (typeof obj.refresh_token === 'string' && obj.refresh_token && !obj.refresh_token.startsWith('eyJ')) return obj.refresh_token;
if (typeof obj.refresh_token === 'string' && obj.refresh_token) return obj.refresh_token;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === 'refresh_token' && typeof obj[keys[i]] === 'string' && obj[keys[i]]) return obj[keys[i]];
if (obj[keys[i]] && typeof obj[keys[i]] === 'object') {
var found = _deepFindRefreshToken(obj[keys[i]]);
if (found) return found;
}
}
return null;
}
function clearStoredSession() {
try {
var keys = ['isotope-auth-token', 'isotope-last-jwt', 'isotope-last-rt', 'isotope-last-session-raw'];
if (SUPA_REF) keys.push('sb-' + SUPA_REF + '-auth-token');
for (var i = 0; i < localStorage.length; i++) {
var lk = localStorage.key(i);
if (lk && lk.startsWith('sb-') && lk.endsWith('-auth-token')) keys.push(lk);
}
keys.forEach(function(k) { try { localStorage.removeItem(k); } catch(e) {} });
writeSyncMetadata({ last_sync_status: 'paused_auth', last_error: 'Signed out. Log in again to sync.' });
} catch(e) {}
}
// ββ localStorage write interceptor ββββββββββββββββββββββββββββββββββββββββ
// Captures the JWT the moment Supabase (or any auth code) writes ANY session
// key to localStorage β regardless of key name, nesting depth, or format.
// This makes getValidJwt() immune to format changes in future Supabase releases.
(function() {
try {
var _orig = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
_orig.call(this, key, value);
if (typeof key !== 'string' || typeof value !== 'string') return;
var isAuthKey = (key.startsWith('sb-') && key.endsWith('-auth-token'))
|| key === 'isotope-auth-token'
|| key === 'isotope-last-session-raw';
if (!isAuthKey) return;
try {
var parsed = JSON.parse(value);
var at = _deepFindJwt(parsed);
var rt = _deepFindRefreshToken(parsed);
if (at) {
_orig.call(this, 'isotope-last-jwt', at);
_orig.call(this, 'isotope-last-session-raw', value);
if (rt) _orig.call(this, 'isotope-last-rt', rt);
}
} catch(e) {}
};
} catch(e) {}
})();
// ββ Trigger initial capture on page load ββββββββββββββββββββββββββββββββββ
// In case the interceptor wasn't installed before the Supabase client wrote the session.
(function() {
try {
var keys = [];
for (var i = 0; i < localStorage.length; i++) keys.push(localStorage.key(i));
keys.forEach(function(k) {
if (!k) return;
if ((k.startsWith('sb-') && k.endsWith('-auth-token')) || k === 'isotope-auth-token' || k === 'isotope-last-session-raw') {
var raw = localStorage.getItem(k);
if (!raw) return;
try {
var parsed = JSON.parse(raw);
var at = _deepFindJwt(parsed);
var rt = _deepFindRefreshToken(parsed);
if (at) {
localStorage.setItem('isotope-last-jwt', at);
localStorage.setItem('isotope-last-session-raw', raw);
if (rt) localStorage.setItem('isotope-last-rt', rt);
}
} catch(e) {}
}
});
} catch(e) {}
})();
// Store session under BOTH keys so restore-and-launch.js and Supabase client both see it
function saveSession(session) {
if (!session || !session.access_token) return;
var s = JSON.stringify(session);
localStorage.setItem('sb-' + SUPA_REF + '-auth-token', s); // Supabase JS v2 standard key
localStorage.setItem('isotope-auth-token', s); // restore-and-launch.js legacy key
localStorage.setItem('isotope-last-jwt', session.access_token);
if (session.refresh_token) localStorage.setItem('isotope-last-rt', session.refresh_token);
localStorage.setItem('isotope-last-session-raw', s);
}
function parseSessionToken(raw) {
// Use the deep scanner β handles all Supabase JS v2 formats without fragile key paths
try { return _deepFindJwt(typeof raw === 'string' ? JSON.parse(raw) : raw) || null; }
catch(e) { return null; }
}
function readStoredSession() {
// Priority 1: Supabase-managed key (auto-refreshed by Supabase JS client)
var raw = SUPA_REF ? localStorage.getItem('sb-' + SUPA_REF + '-auth-token') : null;
// Priority 2: our legacy key (written by __isoLogin, may be stale after token refresh)
if (!raw) raw = localStorage.getItem('isotope-auth-token');
// Priority 3: last raw session snapshot captured from any auth writer
if (!raw) raw = localStorage.getItem('isotope-last-session-raw');
// Priority 4: scan all sb-*-auth-token keys as fallback
if (!raw) {
for (var i = 0; i < localStorage.length; i++) {
var lk = localStorage.key(i);
if (lk && lk.startsWith('sb-') && lk.endsWith('-auth-token')) { raw = localStorage.getItem(lk); break; }
}
}
if (!raw) return null;
try { return JSON.parse(raw); } catch(e) { return null; }
}
function currentJwt() {
// 1. Primary Supabase key (deep-scan handles all formats)
var raw = SUPA_REF ? localStorage.getItem('sb-' + SUPA_REF + '-auth-token') : null;
var at = raw ? parseSessionToken(raw) : null;
if (at) return at;
// 2. Our own saved key
raw = localStorage.getItem('isotope-auth-token');
at = raw ? parseSessionToken(raw) : null;
if (at) return at;
// 3. Last captured raw session snapshot
raw = localStorage.getItem('isotope-last-session-raw');
at = raw ? parseSessionToken(raw) : null;
if (at) return at;
// 4. Scan ALL localStorage for any sb-*-auth-token key
for (var i = 0; i < localStorage.length; i++) {
var lk = localStorage.key(i);
if (!lk) continue;
if (lk.startsWith('sb-') && lk.endsWith('-auth-token')) {
raw = localStorage.getItem(lk);
at = raw ? parseSessionToken(raw) : null;
if (at) return at;
}
}
// 5. Last captured JWT is only a fallback when raw session formats are absent.
var captured = localStorage.getItem('isotope-last-jwt');
if (captured && captured.startsWith('eyJ')) return captured;
return null;
}
// ββ JWT auto-refresh helpers ββββββββββββββββββββββββββββββββββββββββββββββββ
// Extract refresh_token from any known session format using the deep scanner
function _getRefreshToken() {
// 1. Pre-captured refresh token from interceptor
var captured = localStorage.getItem('isotope-last-rt');
if (captured) return captured;
// 2. Scan known keys with deep extractor
var sources = [];
if (SUPA_REF) sources.push('sb-' + SUPA_REF + '-auth-token');
sources.push('isotope-auth-token', 'isotope-last-session-raw');
for (var i = 0; i < sources.length; i++) {
var raw = localStorage.getItem(sources[i]);
if (!raw) continue;
try {
var rt = _deepFindRefreshToken(JSON.parse(raw));
if (rt) return rt;
} catch(e) {}
}
// 3. Scan all localStorage
for (var j = 0; j < localStorage.length; j++) {
var lk = localStorage.key(j);
if (!lk || !(lk.startsWith('sb-') && lk.endsWith('-auth-token'))) continue;
var raw2 = localStorage.getItem(lk);
if (!raw2) continue;
try {
var rt2 = _deepFindRefreshToken(JSON.parse(raw2));
if (rt2) return rt2;
} catch(e) {}
}
return null;
}
// Call Supabase /auth/v1/token to exchange refresh_token for a new session.
// Saves and returns the new access_token, or null on failure.
async function _refreshSession(refreshToken) {
if (!refreshToken) return null;
try {
var r = await fetch(SUPA_URL_BASE + '/auth/v1/token?grant_type=refresh_token', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'apikey': SUPA_ANON },
body: JSON.stringify({ refresh_token: refreshToken })
});
var data = await r.json().catch(function() { return {}; });
if (r.ok && data.access_token) {
saveSession(data);
return data.access_token;
}
} catch(e) {}
return null;
}
// Returns a valid (non-expired) JWT. Auto-refreshes if the stored token is
// expired or expiring within 120 seconds. If refresh fails, return null so the
// sync pipeline does not send a known-bad token and then claim progress.
async function getValidJwt() {
var at = currentJwt();
if (!at) return null;
// Decode payload to check expiry
var needsRefresh = false;
try {
var parts = at.split('.');
if (parts.length >= 2) {
var pad = parts[1].replace(/-/g, '+').replace(/_/g, '/');
while (pad.length % 4) pad += '=';
var payload = JSON.parse(atob(pad));
needsRefresh = !payload.exp || payload.exp < Math.floor(Date.now() / 1000) + 120;
}
} catch(e) {}
if (!needsRefresh) return at;
var fresh = await _refreshSession(_getRefreshToken());
return fresh || null;
}
// Force-refresh regardless of expiry (used after receiving a 401 response).
async function forceRefreshJwt() {
var fresh = await _refreshSession(_getRefreshToken());
return fresh || null;
}
window.__isoCurrentJwt = currentJwt;
window.__isoGetValidJwt = getValidJwt;
window.__isoForceRefreshJwt = forceRefreshJwt;
window.__isoWriteSession = saveSession;
window.__isoClearAuthSession = clearStoredSession;
function writeSyncMetadata(patch) {
try {
var cur = JSON.parse(localStorage.getItem('isotope_sync_metadata') || '{}') || {};
localStorage.setItem('isotope_sync_metadata', JSON.stringify(Object.assign({}, cur, patch || {})));
} catch(e) {}
}
function readSyncMetadata() {
try { return JSON.parse(localStorage.getItem('isotope_sync_metadata') || '{}') || {}; } catch(e) { return {}; }
}
function stableStringify(value) {
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']';
return '{' + Object.keys(value).sort().map(function(k) {
return JSON.stringify(k) + ':' + stableStringify(value[k]);
}).join(',') + '}';
}
async function hashText(text) {
var str = String(text || '');
try {
if (window.crypto && window.crypto.subtle && window.TextEncoder) {
var data = new TextEncoder().encode(str);
var digest = await window.crypto.subtle.digest('SHA-256', data);
return Array.prototype.map.call(new Uint8Array(digest), function(b) {
return b.toString(16).padStart(2, '0');
}).join('');
}
} catch(e) {}
var h1 = 2166136261, h2 = 16777619;
for (var i = 0; i < str.length; i++) {
h1 ^= str.charCodeAt(i);
h1 = Math.imul(h1, 16777619);
h2 = Math.imul(h2 ^ str.charCodeAt(i), 2246822519);
}
return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0') + ':' + str.length;
}
async function hashBackupData(backupText) {
try {
var normalizer = window.IsotopeBackupNormalizer || null;
if (normalizer && typeof normalizer.normalizeAnyBackup === 'function' && typeof normalizer.getBackupData === 'function') {
var normalized = normalizer.normalizeAnyBackup(backupText || '{}');
return await hashText(stableStringify(normalizer.getBackupData(normalized)));
}
} catch(e) {}
return await hashText(backupText);
}
function yieldToBrowser() {
return new Promise(function(resolve) {
if (typeof requestIdleCallback === 'function') requestIdleCallback(function(){ resolve(); }, { timeout: 250 });
else requestAnimationFrame(function(){ setTimeout(resolve, 0); });
});
}
window.__isoStringifyBackup = async function(value) {
await yieldToBrowser();
if (typeof Worker !== 'function' || typeof Blob !== 'function' || typeof URL === 'undefined') {
return JSON.stringify(value, null, 2);
}
return new Promise(function(resolve) {
var workerUrl = null;
var done = false;
function finish(result) {
if (done) return;
done = true;
try { if (workerUrl) URL.revokeObjectURL(workerUrl); } catch(e) {}
resolve(result);
}
try {
var source = 'self.onmessage=function(e){try{self.postMessage({ok:true,json:JSON.stringify(e.data,null,2)})}catch(err){self.postMessage({ok:false,error:err&&err.message||"stringify failed"})}}';
workerUrl = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
var worker = new Worker(workerUrl);
var tid = setTimeout(function() {
try { worker.terminate(); } catch(e) {}
finish(JSON.stringify(value, null, 2));
}, 20000);
worker.onmessage = function(event) {
clearTimeout(tid);
try { worker.terminate(); } catch(e) {}
var data = event.data || {};
finish(data.ok ? data.json : JSON.stringify(value, null, 2));
};
worker.onerror = function() {
clearTimeout(tid);
try { worker.terminate(); } catch(e) {}
finish(JSON.stringify(value, null, 2));
};
worker.postMessage(value);
} catch(e) {
finish(JSON.stringify(value, null, 2));
}
});
};
async function withTimeout(promiseFactory, timeoutMs, label) {
var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
var tid;
var timeout = new Promise(function(_, reject) {
tid = setTimeout(function() {
try { if (controller) controller.abort(); } catch(e) {}
reject(new Error(label || 'Operation timed out'));
}, timeoutMs || 45000);
});
try {
return await Promise.race([promiseFactory(controller ? controller.signal : null), timeout]);
} finally {
clearTimeout(tid);
}
}
var syncCoordinator = window.__isoSyncCoordinator || {
active: false,
activeName: null,
startedAt: 0,
lastAutoAt: 0
};
window.__isoSyncCoordinator = syncCoordinator;
async function withSyncLock(name, options, fn) {
options = options || {};
var now = Date.now();
var lockTimeoutMs = options.lockTimeoutMs || 90000;
if (syncCoordinator.active && now - syncCoordinator.startedAt < lockTimeoutMs) {
writeSyncMetadata({ last_sync_status: 'syncing', last_error: null, active_operation: syncCoordinator.activeName || 'sync' });
return { ok: false, skipped: true, reason: 'already_running', active: syncCoordinator.activeName };
}
if (syncCoordinator.active && now - syncCoordinator.startedAt >= lockTimeoutMs) {
syncCoordinator.active = false;
syncCoordinator.activeName = null;
syncCoordinator.startedAt = 0;
}
if (!options.force && options.autoDebounceMs && now - syncCoordinator.lastAutoAt < options.autoDebounceMs) {
return { ok: true, skipped: true, reason: 'debounced' };
}
if (!options.force && options.autoDebounceMs) syncCoordinator.lastAutoAt = now;
syncCoordinator.active = true;
syncCoordinator.activeName = name || 'sync';
syncCoordinator.startedAt = now;
try {
writeSyncMetadata({ last_sync_status: 'syncing', last_error: null, active_operation: syncCoordinator.activeName, active_started_at: new Date(now).toISOString() });
return await withTimeout(function(){ return fn(); }, options.timeoutMs || lockTimeoutMs, (name || 'Sync') + ' timed out');
} finally {
syncCoordinator.active = false;
syncCoordinator.activeName = null;
syncCoordinator.startedAt = 0;
writeSyncMetadata({ active_operation: null, active_started_at: null });
}
}
// Append one event to the rolling sync history (max 25 entries).
// entry: { op, status, error?, bytes?, mode?, source? }
function writeSyncHistory(entry) {
try {
var history = [];
try { history = JSON.parse(localStorage.getItem('isotope_sync_history') || '[]') || []; } catch(e) {}
if (!Array.isArray(history)) history = [];
var next = Object.assign({ at: new Date().toISOString() }, entry || {});
var prev = history[0] || {};
var sameRecent = prev.op === next.op &&
prev.status === next.status &&
prev.hash === next.hash &&
prev.source === next.source &&
(Date.now() - new Date(prev.at || 0).getTime()) < 5000;
if (sameRecent) {
history[0] = Object.assign({}, prev, next, { at: prev.at, repeats: (Number(prev.repeats) || 1) + 1 });
} else {
history.unshift(next);
}
if (history.length > 25) history = history.slice(0, 25);
localStorage.setItem('isotope_sync_history', JSON.stringify(history));
} catch(e) {}
// Refresh the live panel if it's mounted
try { if (window.__isoRefreshHistoryPanel) window.__isoRefreshHistoryPanel(); } catch(e) {}
}
window.__isoGetSyncHistory = function() {
try { return JSON.parse(localStorage.getItem('isotope_sync_history') || '[]') || []; } catch(e) { return []; }
};
window.__isoGetSyncMetadata = function() {
try { return JSON.parse(localStorage.getItem('isotope_sync_metadata') || '{}') || {}; } catch(e) { return {}; }
};
function cacheCloudSnapshot(snapshot, userId) {
try {
if (!snapshot || !userId || snapshot.user_id !== userId) return false;
snapshot.trusted = true;
snapshot.source = snapshot.source || 'supabase';
snapshot.downloaded_at = snapshot.downloaded_at || snapshot.exported_at || new Date().toISOString();
localStorage.setItem('isotope_cloud_snapshot_' + userId, JSON.stringify(snapshot));
localStorage.setItem('isotope_last_cloud_snapshot_user', JSON.stringify({ user_id: userId, downloaded_at: snapshot.downloaded_at }));
writeSyncMetadata({
last_sync_status: 'synced',
last_snapshot_at: snapshot.exported_at || snapshot.downloaded_at,
pending_count: 0,
last_error: null
});
return true;
} catch(e) { return false; }
}
// ββ Sync auth state machine ββββββββββββββββββββββββββββββββββββββββββββββ
// Auth failure is a STOP condition. Network failure is a RETRY condition.
// When any sync call gets an auth error we block all scheduled syncs.
// When a new valid session token arrives we unblock and queue one retry.
function isAuthError(e) {
if (!e) return false;
if (e.__isAuthError) return true;
var msg = String(e.message || e || '').toLowerCase();
return /authentication required|please log in|invalid token|token expired|jwt expired|not authenticated|invalid credentials|invalid claim|invalid jwt|session expired|no session|user not found/.test(msg) || (e.__httpStatus === 401);
}
function isPermissionError(e) {
if (!e) return false;
var msg = String(e.message || e || '').toLowerCase();
return /permission denied|policy|not authorized|forbidden|rls|row level security/.test(msg) || (e.__httpStatus === 403);
}
function isEmptyOverwriteBlocked(e) {
return !!(e && (e.__isEmptyOverwriteBlocked || e.__code === 'BLOCKED_EMPTY_OVERWRITE'));
}
function isNetworkError(e) {
if (!e) return false;
var msg = String(e.message || e || '').toLowerCase();
return /network|fetch|timeout|timed out|econnrefused|econnreset|dns|no internet|failed to fetch|load failed/.test(msg) || e.name === 'AbortError' || e.name === 'TypeError';
}
window.__isoSyncAuthBlocked = false;
// Block all scheduled syncs (auth failure). Stops the 30-min timer.
window.__isoSyncAuthBlock = function(reason) {
if (!window.__isoSyncAuthBlocked) {
window.__isoSyncAuthBlocked = true;
writeSyncMetadata({ last_sync_status: 'paused_auth', last_error: reason || 'Authentication required β please log in' });
writeSyncHistory({ op: 'auth_block', status: 'paused_auth', detail: reason || 'Authentication required' });
// Stop the 30-min timer so it cannot fire while auth is broken
if (typeof _autoSyncTimer !== 'undefined' && _autoSyncTimer) {
clearInterval(_autoSyncTimer);
_autoSyncTimer = null;
}
}
};
// Unblock syncs (new session token received). Restarts the timer + queues one sync.
window.__isoSyncAuthUnblock = function() {
var wasBlocked = window.__isoSyncAuthBlocked;
window.__isoSyncAuthBlocked = false;
if (wasBlocked) {
writeSyncHistory({ op: 'auth_unblock', status: 'ok', detail: 'Session restored β sync resuming' });
// Restart the recurring timer and schedule one sync attempt shortly
if (typeof startAutoSyncTimer === 'function') {
try { startAutoSyncTimer(); } catch(e) {}
}
setTimeout(function() {
try { window.__isoAutoSync('auth_recovered').catch(function() {}); } catch(e) {}
}, 2000);
}
};
async function authedJson(url, options) {
var jwt = await getValidJwt();
if (!jwt) {
var _noJwtErr = new Error('Authentication required β please log in');
_noJwtErr.__isAuthError = true;
throw _noJwtErr;
}
var headers = Object.assign({ 'Accept': 'application/json', 'Authorization': 'Bearer ' + jwt }, (options && options.headers) || {});
var timeoutMs = options && options.timeoutMs ? options.timeoutMs : 45000;
var r = await withTimeout(function(signal) {
var init = Object.assign({}, options || {}, { headers: headers });
delete init.timeoutMs;
if (signal) init.signal = signal;
return fetch(url, init);
}, timeoutMs, 'Cloud request timed out');
// If 401, force-refresh the token and retry once before giving up
if (r.status === 401) {
var refreshed = await forceRefreshJwt();
if (refreshed && refreshed !== jwt) {
headers = Object.assign({ 'Accept': 'application/json', 'Authorization': 'Bearer ' + refreshed }, (options && options.headers) || {});
r = await withTimeout(function(signal) {
var init = Object.assign({}, options || {}, { headers: headers });
delete init.timeoutMs;
if (signal) init.signal = signal;
return fetch(url, init);
}, timeoutMs, 'Cloud request timed out');
} else {
// Refresh failed β this is a genuine auth error
var _authErr = new Error('Authentication required β session could not be refreshed');
_authErr.__isAuthError = true;
_authErr.__httpStatus = 401;
throw _authErr;
}
}
var d = await r.json().catch(function(){ return {}; });
if (!r.ok || !d.ok) {
var errMsg = d.message || d.error || ('Request failed: ' + r.status);
var err = new Error(errMsg);
err.__httpStatus = r.status;
err.__code = d.code || null;
err.__state = d.state || null;
err.__payload = d;
if (r.status === 401 || /authentication required|please log in|invalid token|jwt|not authenticated|session/i.test(errMsg)) {
err.__isAuthError = true;
} else if (r.status === 403 || /permission|policy|forbidden|rls/i.test(errMsg)) {
err.__isPermissionError = true;
} else if (d.code === 'BLOCKED_EMPTY_OVERWRITE') {
err.__isEmptyOverwriteBlocked = true;
}
throw err;
}
if (d.cloud_snapshot && d.user_id) cacheCloudSnapshot(d.cloud_snapshot, d.user_id);
return d;