-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2101 lines (1809 loc) · 85.9 KB
/
Copy pathindex.html
File metadata and controls
2101 lines (1809 loc) · 85.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Private GH Loader</title>
<style>
:root {
color-scheme: light;
--bg: radial-gradient(circle at 15% 20%, #f3f5ff 0%, #eef8ff 32%, #fffef8 100%);
--surface: #ffffffcc;
--stroke: #d7dce8;
--text: #132033;
--muted: #4d607a;
--primary: #0a6b7a;
--danger: #9f1f31;
--ok: #17662f;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
font-family: "Avenir Next", "Segoe UI", sans-serif;
color: var(--text);
background: var(--bg);
display: grid;
place-items: center;
padding: 24px;
}
.panel {
width: min(640px, 100%);
border: 1px solid var(--stroke);
background: var(--surface);
border-radius: 16px;
box-shadow: 0 12px 42px #1f2f5540;
backdrop-filter: blur(8px);
padding: 20px;
}
h1 {
margin: 0 0 8px;
font-size: 1.3rem;
}
p {
margin: 0 0 14px;
color: var(--muted);
line-height: 1.4;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
gap: 10px;
}
input,
button {
font: inherit;
border-radius: 10px;
border: 1px solid var(--stroke);
padding: 10px 12px;
}
button {
background: var(--primary);
color: white;
cursor: pointer;
border-color: #0c5b68;
min-width: 120px;
}
button:disabled {
cursor: not-allowed;
opacity: 0.75;
}
.status {
margin-top: 14px;
border-radius: 10px;
border: 1px dashed var(--stroke);
padding: 10px 12px;
background: #fff;
min-height: 44px;
font-size: 0.95rem;
}
.status.error {
border-color: #e3a3ac;
color: var(--danger);
}
.status.ok {
border-color: #99cfad;
color: var(--ok);
}
.remember-row {
margin-top: 10px;
color: var(--muted);
font-size: 0.92rem;
}
.remember-row label {
display: inline-flex;
align-items: center;
gap: 8px;
cursor: pointer;
user-select: none;
}
</style>
<script src="encrypted/runtime-config.js"></script>
</head>
<body>
<main class="panel" id="unlockPanel">
<h1>Project Name</h1>
<p>Description</p>
<div class="row">
<input id="pass" type="password" autocomplete="current-password" placeholder="Enter passphrase" />
<button id="unlockBtn">Unlock</button>
</div>
<div class="remember-row">
<label for="rememberPass">
<input id="rememberPass" type="checkbox" checked />
<span>Remember passcode on this browser (30 days)</span>
</label>
</div>
<div class="status" id="status">Awaiting unlock.</div>
</main>
<script>
(() => {
"use strict";
const OP_DEFINE_FILE = 0x01;
const PASSCODE_STORAGE_KEY = "PRIVATE_GH_PASSCODE_V1";
const PASSCODE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const DEBUG_GUARD_INTERVAL_MS = 1200;
const ENABLE_SESSION_CLEANUP_ON_LEAVE = true;
const SESSION_CLEANUP_STORAGE_KEY = "PRIVATE_GH_LAST_SESSION_CLEANUP_V1";
const SESSION_ID_RE = /^[A-Z0-9]{3}$/;
const te = new TextEncoder();
const td = new TextDecoder();
const nativeFetch = window.fetch.bind(window);
const wasmBytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
0x03, 0x02, 0x01, 0x00,
0x07, 0x0a, 0x01, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, 0x00,
0x0a, 0x06, 0x01, 0x04, 0x00, 0x20, 0x00, 0x0b
]);
const state = {
manifest: null,
partA: "",
partB: null,
vmFiles: new Map(),
loadedFragments: new Set(),
wasm: null,
entryPath: "",
networkShimInstalled: false,
assetElementShimInstalled: false,
assetBlobUrls: new Map(),
assetBlobPromises: new Map(),
assetRewriteVersion: new WeakMap(),
nativeFetch,
locked: false,
debugGuardTimer: null,
navBridgeInstalled: false,
sessionCleanupInstalled: false,
cleanupSessionId: "",
cleanupSupabaseOrigin: "",
cleanupApiKey: "",
cleanupAuthHeader: "",
cleanupSignalSent: false,
};
const passEl = document.getElementById("pass");
const rememberPassEl = document.getElementById("rememberPass");
const unlockBtn = document.getElementById("unlockBtn");
const statusEl = document.getElementById("status");
function setStatus(msg, cls = "") {
statusEl.textContent = (msg && String(msg).trim()) || "Unlock failed. Please try again.";
statusEl.className = `status ${cls}`.trim();
}
function b64FromU8(bytes) {
let raw = "";
for (let i = 0; i < bytes.length; i += 1) {
raw += String.fromCharCode(bytes[i]);
}
return btoa(raw);
}
function u8FromB64(input) {
const raw = atob(input);
const out = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i += 1) {
out[i] = raw.charCodeAt(i);
}
return out;
}
function savePasscode(passcode) {
try {
const envelope = {
v: 1,
passcode,
expiresAt: Date.now() + PASSCODE_TTL_MS,
};
const serialized = JSON.stringify(envelope);
const encoded = b64FromU8(te.encode(serialized));
localStorage.setItem(PASSCODE_STORAGE_KEY, encoded);
} catch {
// Best effort only.
}
}
function clearSavedPasscode() {
try {
localStorage.removeItem(PASSCODE_STORAGE_KEY);
} catch {
// Best effort only.
}
}
function loadSavedPasscode() {
try {
const encoded = localStorage.getItem(PASSCODE_STORAGE_KEY);
if (!encoded) {
return "";
}
const decoded = td.decode(u8FromB64(encoded));
const payload = JSON.parse(decoded);
if (!payload || typeof payload.passcode !== "string" || typeof payload.expiresAt !== "number") {
clearSavedPasscode();
return "";
}
if (Date.now() > payload.expiresAt) {
clearSavedPasscode();
return "";
}
return payload.passcode;
} catch {
clearSavedPasscode();
return "";
}
}
function normalizeUnlockError(error) {
if (error instanceof DOMException && error.name === "OperationError") {
return "Incorrect passphrase. Please try again.";
}
const rawMessage = error instanceof Error
? (error.message || "")
: String(error || "");
const message = rawMessage.trim();
if (!message) {
return "Incorrect passphrase. Please try again.";
}
if (/operationerror|decrypt|decryption failed|authentication/i.test(message)) {
return "Incorrect passphrase. Please try again.";
}
return message;
}
function clearDebugGuard() {
if (state.debugGuardTimer !== null) {
clearInterval(state.debugGuardTimer);
state.debugGuardTimer = null;
}
}
function lockRuntime(reason) {
if (state.locked) {
return;
}
state.locked = true;
clearDebugGuard();
state.manifest = null;
state.partA = "";
state.partB = null;
state.entryPath = "";
state.vmFiles.clear();
state.loadedFragments.clear();
for (const blobUrl of state.assetBlobUrls.values()) {
URL.revokeObjectURL(blobUrl);
}
state.assetBlobUrls.clear();
state.assetBlobPromises.clear();
state.assetRewriteVersion = new WeakMap();
window.fetch = state.nativeFetch;
clearSavedPasscode();
if (rememberPassEl) {
rememberPassEl.checked = false;
}
passEl.value = "";
passEl.disabled = true;
unlockBtn.disabled = true;
setStatus(reason || "Runtime locked due to analysis detection.", "error");
}
function ensureUnlocked() {
if (state.locked) {
throw new Error("Runtime locked due to analysis detection.");
}
}
function startDebugGuard() {
clearDebugGuard();
state.debugGuardTimer = setInterval(() => {
if (antiAnalysisTriggered()) {
lockRuntime("Debugging detected. Runtime locked.");
}
}, DEBUG_GUARD_INTERVAL_MS);
}
function concatBytes(...arrays) {
const total = arrays.reduce((sum, arr) => sum + arr.length, 0);
const out = new Uint8Array(total);
let cursor = 0;
for (const arr of arrays) {
out.set(arr, cursor);
cursor += arr.length;
}
return out;
}
function stableStringify(value) {
if (value === null || typeof value !== "object") {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
}
const keys = Object.keys(value).sort();
const body = keys
.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`)
.join(",");
return `{${body}}`;
}
async function sha256Hex(data) {
const hash = await crypto.subtle.digest("SHA-256", data);
const bytes = new Uint8Array(hash);
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
async function derivePartB(password, saltB64, iterations) {
const keyMaterial = await crypto.subtle.importKey(
"raw",
te.encode(password),
"PBKDF2",
false,
["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{
name: "PBKDF2",
hash: "SHA-256",
salt: u8FromB64(saltB64),
iterations,
},
keyMaterial,
256
);
return new Uint8Array(bits);
}
async function deriveSplitKey(partA, partB, partC) {
const joined = concatBytes(te.encode(partA), partB, partC);
const digest = await crypto.subtle.digest("SHA-256", joined);
return new Uint8Array(digest);
}
async function initWasm() {
try {
const result = await WebAssembly.instantiate(wasmBytes);
state.wasm = result.instance.exports;
} catch {
state.wasm = null;
}
}
function antiAnalysisTriggered() {
const widthGap = window.outerWidth - window.innerWidth;
const heightGap = window.outerHeight - window.innerHeight;
const geometryLooksLikeDevtools = widthGap > 170 || heightGap > 170;
const t0 = performance.now();
debugger;
const dt = performance.now() - t0;
const breakpointLatency = dt > 140;
return geometryLooksLikeDevtools && breakpointLatency;
}
async function loadManifest(manifestPath) {
ensureUnlocked();
const response = await fetch(manifestPath, { cache: "no-store" });
if (!response.ok) {
throw new Error(`Manifest fetch failed (${response.status})`);
}
const manifest = await response.json();
const expectedHash = manifest.manifest_hash;
if (typeof expectedHash !== "string" || expectedHash.length !== 64) {
throw new Error("Invalid manifest integrity metadata.");
}
const copy = typeof structuredClone === "function"
? structuredClone(manifest)
: JSON.parse(JSON.stringify(manifest));
delete copy.manifest_hash;
const canonical = te.encode(stableStringify(copy));
const actualHash = await sha256Hex(canonical);
if (actualHash !== expectedHash) {
throw new Error("Manifest integrity check failed.");
}
state.manifest = manifest;
}
async function decryptFragment(fragmentPath) {
ensureUnlocked();
const response = await fetch(fragmentPath, { cache: "no-store" });
if (!response.ok) {
throw new Error(`Fragment fetch failed (${response.status})`);
}
const envelope = await response.json();
const partC = u8FromB64(envelope.partC_b64);
const nonce = u8FromB64(envelope.nonce_b64);
const ciphertext = u8FromB64(envelope.ciphertext_b64);
const keyRaw = await deriveSplitKey(state.partA, state.partB, partC);
const cryptoKey = await crypto.subtle.importKey(
"raw",
keyRaw,
{ name: "AES-GCM" },
false,
["decrypt"]
);
const plainBuffer = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: nonce },
cryptoKey,
ciphertext
);
const plainBytes = new Uint8Array(plainBuffer);
const bytecodeHash = await sha256Hex(plainBytes);
if (bytecodeHash !== envelope.bytecode_sha256) {
throw new Error("Bytecode checksum mismatch.");
}
return plainBytes;
}
function readU16(bytes, cursor) {
return (bytes[cursor] << 8) | bytes[cursor + 1];
}
function readU32(bytes, cursor) {
return (
(bytes[cursor] << 24) |
(bytes[cursor + 1] << 16) |
(bytes[cursor + 2] << 8) |
bytes[cursor + 3]
) >>> 0;
}
function executeBytecode(bytecode) {
let cursor = 0;
while (cursor < bytecode.length) {
const opcode = bytecode[cursor];
cursor += 1;
if (state.wasm && typeof state.wasm.accept === "function") {
const accepted = state.wasm.accept(opcode);
if (accepted !== opcode) {
throw new Error("WASM opcode gate rejected the instruction.");
}
}
if (opcode !== OP_DEFINE_FILE) {
throw new Error(`Unsupported opcode ${opcode}`);
}
const pathLen = readU16(bytecode, cursor);
cursor += 2;
const pathBytes = bytecode.slice(cursor, cursor + pathLen);
cursor += pathLen;
const logicalPath = td.decode(pathBytes);
const mimeLen = readU16(bytecode, cursor);
cursor += 2;
const mimeBytes = bytecode.slice(cursor, cursor + mimeLen);
cursor += mimeLen;
const mime = td.decode(mimeBytes);
const dataLen = readU32(bytecode, cursor);
cursor += 4;
const data = bytecode.slice(cursor, cursor + dataLen);
cursor += dataLen;
state.vmFiles.set(logicalPath, { mime, data });
}
}
async function fetchLogicalFile(logicalPath) {
ensureUnlocked();
// Normalize: strip leading "./" so paths like "./images/foo.png" resolve
// to the same manifest key as "images/foo.png".
const key = logicalPath.replace(/^(\.\/)+/, "");
const existing = state.vmFiles.get(key) || state.vmFiles.get(logicalPath);
if (existing) {
return existing;
}
const fileMeta = state.manifest.files[key] || state.manifest.files[logicalPath];
if (!fileMeta) {
throw new Error(`Protected file not found: ${key}`);
}
if (!state.loadedFragments.has(fileMeta.fragment)) {
const bytecode = await decryptFragment(fileMeta.fragment);
executeBytecode(bytecode);
state.loadedFragments.add(fileMeta.fragment);
}
const loaded = state.vmFiles.get(key) || state.vmFiles.get(logicalPath);
if (!loaded) {
throw new Error(`Fragment did not define requested file: ${key}`);
}
return loaded;
}
function isExternalReference(input) {
return /^(?:https?:|data:|blob:|\/\/|#|mailto:|tel:)/i.test(input);
}
function resolvePath(basePath, target) {
const clean = target.split("#")[0].split("?")[0];
if (clean.startsWith("/")) {
return clean.slice(1);
}
const baseDir = basePath.includes("/") ? basePath.slice(0, basePath.lastIndexOf("/") + 1) : "";
const joined = new URL(clean, `https://private.local/${baseDir}`).pathname;
return joined.startsWith("/") ? joined.slice(1) : joined;
}
function buildRuntimeUrl(logicalPath) {
return `${window.location.pathname}#~${encodeURIComponent(logicalPath)}`;
}
function readRoutePathFromHash() {
const hash = window.location.hash || "";
if (!hash.startsWith("#~")) {
return "";
}
try {
return decodeURIComponent(hash.slice(2));
} catch {
return "";
}
}
function isHtmlMime(mime) {
return typeof mime === "string" && /^text\/html\b/i.test(mime);
}
function getPathDir(path) {
return path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
}
function toAbsoluteUrl(raw) {
try {
return new URL(raw, window.location.href);
} catch {
return null;
}
}
function getRequestMethod(input, init) {
const method = init?.method || (input instanceof Request ? input.method : "GET");
return String(method || "GET").toUpperCase();
}
function getHeaderValueFromContainer(headers, targetName) {
if (!headers) {
return "";
}
const name = String(targetName || "").toLowerCase();
if (!name) {
return "";
}
if (headers instanceof Headers) {
return String(headers.get(name) || "").trim();
}
if (Array.isArray(headers)) {
for (const pair of headers) {
if (!Array.isArray(pair) || pair.length < 2) {
continue;
}
if (String(pair[0]).toLowerCase() === name) {
return String(pair[1] || "").trim();
}
}
return "";
}
if (typeof headers === "object") {
for (const [key, value] of Object.entries(headers)) {
if (String(key).toLowerCase() === name) {
return String(value || "").trim();
}
}
}
return "";
}
function getHeaderValue(input, init, name) {
const target = String(name || "").toLowerCase();
const fromInit = getHeaderValueFromContainer(init?.headers || null, target);
if (fromInit) {
return fromInit;
}
if (input instanceof Request) {
return String(input.headers.get(target) || "").trim();
}
return "";
}
function toAbsoluteRequestUrl(input) {
try {
if (input instanceof Request) {
return new URL(input.url, window.location.href);
}
if (input instanceof URL) {
return input;
}
if (typeof input === "string") {
return new URL(input, window.location.href);
}
if (input && typeof input.url === "string") {
return new URL(input.url, window.location.href);
}
} catch {
return null;
}
return null;
}
function persistCleanupState() {
try {
const payload = {
sessionId: state.cleanupSessionId,
supabaseOrigin: state.cleanupSupabaseOrigin,
apikey: state.cleanupApiKey,
authHeader: state.cleanupAuthHeader,
};
sessionStorage.setItem(SESSION_CLEANUP_STORAGE_KEY, JSON.stringify(payload));
} catch {
// Best effort only.
}
}
function hydrateCleanupState() {
try {
const raw = sessionStorage.getItem(SESSION_CLEANUP_STORAGE_KEY);
if (!raw) {
return;
}
const parsed = JSON.parse(raw);
const sessionId = String(parsed?.sessionId || "").trim().toUpperCase();
const origin = String(parsed?.supabaseOrigin || "").trim();
const apikey = String(parsed?.apikey || "").trim();
const authHeader = String(parsed?.authHeader || "").trim();
if (!SESSION_ID_RE.test(sessionId)) {
return;
}
if (!origin || !apikey) {
return;
}
state.cleanupSessionId = sessionId;
state.cleanupSupabaseOrigin = origin;
state.cleanupApiKey = apikey;
state.cleanupAuthHeader = authHeader;
state.cleanupSignalSent = false;
} catch {
// Best effort only.
}
}
function maybeRememberEventsWrite(input, init, method) {
if (!ENABLE_SESSION_CLEANUP_ON_LEAVE) {
return;
}
if (!(method === "POST" || method === "PUT" || method === "PATCH")) {
return;
}
const absoluteUrl = toAbsoluteRequestUrl(input);
if (!absoluteUrl || !/\.supabase\.co$/i.test(absoluteUrl.hostname)) {
return;
}
if (!/^\/rest\/v1\/events\/?$/i.test(absoluteUrl.pathname)) {
return;
}
const body = init?.body;
if (typeof body !== "string") {
return;
}
let payload;
try {
payload = JSON.parse(body);
} catch {
return;
}
const first = Array.isArray(payload) ? payload[0] : payload;
if (!first || typeof first !== "object") {
return;
}
const sessionId = String(first.session_id || first.sessionId || "").trim().toUpperCase();
if (!SESSION_ID_RE.test(sessionId)) {
return;
}
const apikey = getHeaderValue(input, init, "apikey");
if (!apikey) {
return;
}
state.cleanupSessionId = sessionId;
state.cleanupSupabaseOrigin = absoluteUrl.origin;
state.cleanupApiKey = apikey;
const authHeader = getHeaderValue(input, init, "authorization");
if (authHeader) {
state.cleanupAuthHeader = authHeader;
}
state.cleanupSignalSent = false;
persistCleanupState();
}
function sendSessionCleanupSignal(reason) {
if (!ENABLE_SESSION_CLEANUP_ON_LEAVE) {
return;
}
if (state.cleanupSignalSent) {
return;
}
if (!SESSION_ID_RE.test(state.cleanupSessionId)) {
return;
}
if (!state.cleanupSupabaseOrigin || !state.cleanupApiKey) {
return;
}
state.cleanupSignalSent = true;
const authHeader = state.cleanupAuthHeader || `Bearer ${state.cleanupApiKey}`;
const deleteUrl = `${state.cleanupSupabaseOrigin}/rest/v1/events?session_id=eq.${encodeURIComponent(state.cleanupSessionId)}`;
state.nativeFetch(deleteUrl, {
method: "DELETE",
keepalive: true,
headers: {
apikey: state.cleanupApiKey,
Authorization: authHeader,
Prefer: "return=minimal",
"X-Private-GH-Reason": String(reason || "leave"),
},
}).catch(() => {
// Best effort only.
});
}
function resolveManifestPathFromRequest(input) {
if (!state.manifest || !state.manifest.files) {
return null;
}
const entryPath = state.entryPath || state.manifest.entry || "";
const candidates = [];
const addCandidate = (candidate) => {
if (!candidate) {
return;
}
const normalized = String(candidate).replace(/^\/+/, "");
if (normalized && !candidates.includes(normalized)) {
candidates.push(normalized);
}
};
let raw = "";
if (typeof input === "string") {
raw = input;
} else if (input instanceof URL) {
raw = input.toString();
}
if (raw && !isExternalReference(raw)) {
addCandidate(resolvePath(entryPath, raw));
}
let absolute = null;
if (input instanceof Request) {
absolute = toAbsoluteUrl(input.url);
} else if (raw) {
absolute = toAbsoluteUrl(raw);
} else if (input && typeof input.url === "string") {
absolute = toAbsoluteUrl(input.url);
}
if (absolute && absolute.origin === window.location.origin) {
const fromPathname = absolute.pathname.replace(/^\/+/, "");
addCandidate(fromPathname);
const entryDir = getPathDir(entryPath);
if (entryDir && fromPathname && !fromPathname.startsWith(entryDir)) {
addCandidate(entryDir + fromPathname);
}
}
for (const candidate of candidates) {
if (Object.prototype.hasOwnProperty.call(state.manifest.files, candidate)) {
return candidate;
}
}
return null;
}
function resolveManifestPathFromRaw(rawValue) {
if (!state.manifest || !state.manifest.files || !rawValue) {
return "";
}
const raw = String(rawValue || "").trim();
if (!raw || isExternalReference(raw)) {
return "";
}
const fromRequest = resolveManifestPathFromRequest(raw);
if (fromRequest) {
return fromRequest;
}
const entryPath = state.entryPath || state.manifest.entry || "";
const fromEntry = resolvePath(entryPath, raw);
if (fromEntry && Object.prototype.hasOwnProperty.call(state.manifest.files, fromEntry)) {
return fromEntry;
}
return "";
}
function resolveManifestPathFromRawWithBase(rawValue, basePath = "") {
if (!rawValue) {
return "";
}
let logicalPath = resolveManifestPathFromRaw(rawValue);
if (logicalPath) {
return logicalPath;
}
if (!basePath || !state.manifest || !state.manifest.files) {
return "";
}
const fromBase = resolvePath(basePath, String(rawValue));
if (fromBase && Object.prototype.hasOwnProperty.call(state.manifest.files, fromBase)) {
logicalPath = fromBase;
}
return logicalPath || "";
}
async function getBlobUrlForLogicalPath(logicalPath) {
if (!logicalPath) {
return "";
}
const cached = state.assetBlobUrls.get(logicalPath);
if (cached) {
return cached;
}
const inFlight = state.assetBlobPromises.get(logicalPath);
if (inFlight) {
return inFlight;
}
const pending = (async () => {
const file = await fetchLogicalFile(logicalPath);
const blob = new Blob([file.data], { type: file.mime });
const blobUrl = URL.createObjectURL(blob);
state.assetBlobUrls.set(logicalPath, blobUrl);
return blobUrl;
})();
state.assetBlobPromises.set(logicalPath, pending);
try {
return await pending;
} finally {
state.assetBlobPromises.delete(logicalPath);
}
}
function parseSrcsetCandidates(srcsetValue) {
if (!srcsetValue) {
return [];
}
return String(srcsetValue)
.split(",")
.map((chunk) => String(chunk || "").trim())
.filter(Boolean)
.map((original) => {
const parts = original.split(/\s+/).filter(Boolean);
const raw = parts.shift() || "";
const descriptor = parts.join(" ");
return { original, raw, descriptor };
})
.filter((item) => Boolean(item.raw));
}
function hasProtectedSrcsetCandidate(srcsetValue) {
const candidates = parseSrcsetCandidates(srcsetValue);
for (const candidate of candidates) {
if (resolveManifestPathFromRaw(candidate.raw)) {
return true;
}
}
return false;
}
async function rewriteSrcsetValueForRuntime(srcsetValue, basePath = "") {
const candidates = parseSrcsetCandidates(srcsetValue);
if (!candidates.length) {
return String(srcsetValue || "");
}
const rewritten = await Promise.all(candidates.map(async ({ original, raw, descriptor }) => {
if (isExternalReference(raw)) {
return original;
}
const logicalPath = resolveManifestPathFromRawWithBase(raw, basePath);