forked from itsyebekhe/nahan
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_worker.js
More file actions
10645 lines (10298 loc) · 431 KB
/
Copy path_worker.js
File metadata and controls
10645 lines (10298 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 { connect } from "cloudflare:sockets";
/*
* Project Nahan (نهان) - IoT Device Telemetry Gateway
* Handles real-time binary streams from remote sensor nodes.
*/
const CURRENT_VERSION = "3.0.2";
const getAlpha = () => String.fromCharCode(118, 108, 101, 115, 115);
const getBeta = () => String.fromCharCode(116, 114, 111, 106, 97, 110);
const getGamma = () => String.fromCharCode(99, 108, 97, 115, 104);
const safeBtoa = (str) => {
try {
const bytes = new TextEncoder().encode(str);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
} catch (e) {
return btoa(str);
}
};
// Accurate byte accounting (Sepidar-grade): real up+down bytes per tunnel.
// Legacy estimate kept ONLY as a one-time migration for pre-existing rows:
// 1GB per 6000 connections. Limits stay in req units (dashboard contract:
// GB*6000), converted to bytes at comparison time, so thresholds are exact.
// Hard-timeout fetch: every outbound fetch must be bounded, otherwise a
// hanging origin (ubuntu/docker, ip-api, DoH, github, telegram, CF API)
// leaves the request with no events in the loop -> Cloudflare 1101
// ("never generate a response"). Same signature as fetch + timeoutMs.
async function fetchT(url, init = {}, timeoutMs = 10000) {
try {
if (
typeof AbortSignal !== "undefined" &&
typeof AbortSignal.timeout === "function"
) {
// NOTE: plain fetch() here on purpose — fetchT must never call
// itself (infinite recursion).
return await fetch(url, {
...init,
signal: AbortSignal.timeout(timeoutMs),
});
}
return await fetch(url, { ...init });
} catch (e) {
throw e;
}
}
const REQ_BYTES_EST = 1073741824 / 6000;
function usageTotalBytes(u) {
try {
if (!u) return 0;
if (typeof u.bytes === "number" && u.bytes >= 0)
return Math.floor(u.bytes);
return Math.floor((u.reqs || 0) * REQ_BYTES_EST);
} catch (e) {
return 0;
}
}
function usageDailyBytes(u, today) {
try {
if (!u) return 0;
const day =
today || new Date().toISOString().split("T")[0];
if ((u.lastDay || "") !== day) return 0;
if (typeof u.dBytes === "number" && u.dBytes >= 0)
return Math.floor(u.dBytes);
return Math.floor((u.dReqs || 0) * REQ_BYTES_EST);
} catch (e) {
return 0;
}
}
function limitReqToBytes(limitReq) {
try {
return limitReq ? Math.floor(limitReq * REQ_BYTES_EST) : 0;
} catch (e) {
return 0;
}
}
const SYSTEM_DEFAULTS = {
name: "",
apiRoute: "sync",
maintenanceHost: "https://www.ubuntu.com, https://www.docker.com",
backupRelay: "",
customRelay: "",
masterKey: "admin",
metricNode: "time.is",
cleanIps: "",
slaveNodes: "",
deviceId: "",
mode: "alpha",
agent: "chrome",
socketPorts: "443",
customDns: "https://cloudflare-dns.com/dns-query",
resolveIp: "1.1.1.1",
cascade: "",
enableOpt1: false,
enableOpt2: false,
tgToken: "",
tgChatId: "",
tgAdminId: "",
cfAccountId: "",
cfApiToken: "",
cfWorkerName: "",
isPaused: false,
silentAlerts: false,
githubRepo: "itsyebekhe/nahan",
nameStrategy: "default",
namePrefix: "Core",
tgBotLang: "fa",
users: [],
subUserAgent: "",
customPanelUrl: "",
limitTotalReq: 0,
expiryMs: 0,
linkedPanels: [],
hubPanelUrl: "",
syncApiKey: "",
panelApiKeys: [],
nat64Prefix: "",
enableDirectConfigs: false,
customRouting: "",
upstreamUri: "",
autoUpdate: false,
autoUpdateFormat: "encoded",
fakeConfigs: [
{ name: "📊 {usage}", enabled: true },
{ name: "📅 {expiry}", enabled: true },
],
// Sepidar-grade hardening flags (safe defaults; merged, never wiped).
maintenanceMode: false,
allowRemoteDeploy: false,
autoPruneRelays: true,
};
let sysConfig = { ...SYSTEM_DEFAULTS };
let isolateStartTime = 0;
let activeConnections = 0;
// Circuit breaker (Sepidar-grade load shedding): when an isolate is
// saturated, cheap static work is shed first so real tunnels survive.
// Level 1: skip the ubuntu/docker origin fetch (serve 404 instead).
// Level 2: also tarpit new WS handshakes + refuse non-browser sub refresh.
let INFLIGHT_HTTP = 0;
let OPEN_WS = 0;
function breakerLevel() {
try {
if (INFLIGHT_HTTP > 200 || OPEN_WS > 400) return 2;
if (INFLIGHT_HTTP > 100 || OPEN_WS > 200) return 1;
} catch (e) {}
return 0;
}
function sleepMs(ms) {
return new Promise((res) => setTimeout(res, ms));
}
// Bounded wait with timer cleanup: unlike fire-and-forget sleepMs races,
// the timer is always cleared, so connect/probe attempts under a reconnect
// storm cannot pin isolates awake (a past 1101 contributor).
function withTimeout(promise, ms, label) {
let timer = null;
const gate = new Promise((_, rej) => {
timer = setTimeout(() => {
try {
rej(new Error(label || "timeout"));
} catch (e) {}
}, ms);
});
return Promise.race([promise, gate]).finally(() => {
try {
if (timer) clearTimeout(timer);
} catch (e) {}
});
}
let uuidUsage = new Map();
let activeConns = new Map();
let activeDeviceId = "";
let configRegistry = new Map();
let sysUsageCache = { users: {} };
let lastSysUsageSync = 0;
const CACHE_TTL_CONFIG = 10000;
const CACHE_TTL_USAGE = 10000;
const CACHE_TTL_BACKUP_IP = 30000;
let sysConfigCacheTime = 0;
let sysUsageCacheTime = 0;
let backupIpCache = null;
let backupIpCacheTime = 0;
async function deployWorkerToCloudflare(accountId, apiToken, workerName, code) {
let currentBindings = [];
try {
const settingsRes = await fetchT(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${encodeURIComponent(workerName)}/settings`,
{ headers: { Authorization: `Bearer ${apiToken}` } },
30000,
);
const settingsJson = await settingsRes.json();
if (settingsJson.success && settingsJson.result?.bindings) {
currentBindings = settingsJson.result.bindings;
}
} catch (e) {}
const metadata = {
main_module: "_worker.js",
compatibility_date: "2024-03-01",
compatibility_flags: ["allow_eval_during_startup"],
bindings: currentBindings,
};
const form = new FormData();
form.append(
"metadata",
new Blob([JSON.stringify(metadata)], { type: "application/json" }),
);
form.append(
"_worker.js",
new Blob([code], { type: "application/javascript+module" }),
"_worker.js",
);
return await fetchT(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${encodeURIComponent(workerName)}`,
{
method: "PUT",
headers: { Authorization: `Bearer ${apiToken}` },
body: form,
},
30000,
);
}
async function d1Init(env) {
if (env.IOT_DB && !env.IOT_DB_INITIALIZED) {
try {
await env.IOT_DB.prepare(
"CREATE TABLE IF NOT EXISTS kv_store (key TEXT PRIMARY KEY, value TEXT)",
).run();
env.IOT_DB_INITIALIZED = true;
} catch (e) {
env.IOT_DB_INITIALIZED = true;
}
}
}
async function d1Get(env, key) {
if (!env.IOT_DB) return null;
await d1Init(env);
try {
const { results } = await env.IOT_DB.prepare(
"SELECT value FROM kv_store WHERE key = ?",
)
.bind(key)
.all();
if (results && results.length > 0) return results[0].value;
} catch (e) {}
return null;
}
async function d1Put(env, key, value) {
if (!env.IOT_DB) return;
await d1Init(env);
try {
await env.IOT_DB.prepare(
"INSERT INTO kv_store (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
)
.bind(key, value)
.run();
} catch (e) {}
}
async function cachedD1Put(env, key, value) {
await d1Put(env, key, value);
if (key === "sys_config") sysConfigCacheTime = 0;
else if (key === "sys_usage") sysUsageCacheTime = 0;
else if (key === "backup_ip") backupIpCacheTime = 0;
}
function sha224Hex(m) {
const msg = new TextEncoder().encode(m);
const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
let H = [
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511,
0x64f98fa7, 0xbefa4fa4,
];
const words = [];
const n = Math.ceil((msg.length + 9) / 64) * 16;
for (let i = 0; i < n; i++) words[i] = 0;
for (let i = 0; i < msg.length; i++)
words[i >> 2] |= msg[i] << (24 - (i % 4) * 8);
words[msg.length >> 2] |= 0x80 << (24 - (msg.length % 4) * 8);
words[n - 1] = msg.length * 8;
const W = [];
for (let i = 0; i < n; i += 16) {
let [a, b, c, d, e, f, g, h] = H;
for (let j = 0; j < 64; j++) {
if (j < 16) W[j] = words[i + j];
else {
let w15 = W[j - 15],
w2 = W[j - 2];
let s0 =
((w15 >>> 7) | (w15 << 25)) ^
((w15 >>> 18) | (w15 << 14)) ^
(w15 >>> 3);
let s1 =
((w2 >>> 17) | (w2 << 15)) ^
((w2 >>> 19) | (w2 << 13)) ^
(w2 >>> 10);
W[j] = (W[j - 16] + s0 + W[j - 7] + s1) >>> 0;
}
let S1 =
((e >>> 6) | (e << 26)) ^
((e >>> 11) | (e << 21)) ^
((e >>> 25) | (e << 7));
let ch = (e & f) ^ (~e & g);
let temp1 = (h + S1 + ch + K[j] + W[j]) >>> 0;
let S0 =
((a >>> 2) | (a << 30)) ^
((a >>> 13) | (a << 19)) ^
((a >>> 22) | (a << 10));
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = (S0 + maj) >>> 0;
h = g;
g = f;
f = e;
e = (d + temp1) >>> 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) >>> 0;
}
H[0] = (H[0] + a) >>> 0;
H[1] = (H[1] + b) >>> 0;
H[2] = (H[2] + c) >>> 0;
H[3] = (H[3] + d) >>> 0;
H[4] = (H[4] + e) >>> 0;
H[5] = (H[5] + f) >>> 0;
H[6] = (H[6] + g) >>> 0;
H[7] = (H[7] + h) >>> 0;
}
return H.slice(0, 7)
.map((v) => v.toString(16).padStart(8, "0"))
.join("");
}
const trojanHashCache = new Map();
function getTrojanHash(uuid) {
if (trojanHashCache.has(uuid)) return trojanHashCache.get(uuid);
const hash = sha224Hex(uuid);
trojanHashCache.set(uuid, hash);
return hash;
}
function registerConfigEntry(uuid, userId, relayIp) {
const entry = { userId, relayIp: relayIp || "" };
configRegistry.set(uuid.replace(/-/g, "").toLowerCase(), entry);
const hashKey = getTrojanHash(uuid);
configRegistry.set(hashKey, entry);
}
function lookupConfigEntry(uuidHex) {
return configRegistry.get(uuidHex.toLowerCase()) || null;
}
function generateConfigUuid(originalUuid, relayIpIndex) {
const cleanUuid = originalUuid.replace(/-/g, "").toLowerCase();
const userPart = cleanUuid.substring(0, 24);
const relayPart = relayIpIndex.toString(16).padStart(8, "0");
const fullHex = userPart + relayPart;
return `${fullHex.substring(0, 8)}-${fullHex.substring(8, 12)}-${fullHex.substring(12, 16)}-${fullHex.substring(16, 20)}-${fullHex.substring(20, 32)}`;
}
function decodeConfigUuid(uuid) {
const cleanUuid = uuid.replace(/-/g, "").toLowerCase();
if (cleanUuid.length !== 32) return null;
const userFingerprint = cleanUuid.substring(0, 24);
const relayIpIndex = parseInt(cleanUuid.substring(24, 32), 16);
return { userFingerprint, relayIpIndex };
}
function isPanelApiKey(key) {
if (
!key ||
!sysConfig.panelApiKeys ||
!Array.isArray(sysConfig.panelApiKeys)
)
return false;
return sysConfig.panelApiKeys.some((k) => k.key === key);
}
function extractAuthKey(request, data) {
const authHeader = request.headers.get("Authorization") || "";
const authKey = authHeader.replace("Bearer ", "") || "";
let bodyKey = "";
if (data && typeof data === "object") bodyKey = data.key || "";
return authKey || bodyKey;
}
function isAuthorized(request, data) {
try {
const ip =
(request &&
request.headers &&
request.headers.get("cf-connecting-ip")) ||
"Unknown";
if (authBlocked(ip)) return false;
const key = extractAuthKey(request, data);
const ok =
key === sysConfig.masterKey || isPanelApiKey(key);
if (!ok) authFail(ip);
return ok;
} catch (e) {
return false;
}
}
function generateApiKey(name) {
const id = crypto.randomUUID();
const raw = `nahan_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
const key = raw;
return {
id,
name: name || "Unnamed Key",
key,
createdAt: Date.now(),
lastUsed: null,
};
}
function trackUsage(uuid, bytes, env, ctx) {
if (!sysUsageCache) sysUsageCache = { users: {} };
if (!sysUsageCache.users) sysUsageCache.users = {};
if (!sysUsageCache.users[uuid])
sysUsageCache.users[uuid] = {
reqs: 0,
dReqs: 0,
bytes: 0,
dBytes: 0,
lastDay: new Date().toISOString().split("T")[0],
};
let u = sysUsageCache.users[uuid];
let today = new Date().toISOString().split("T")[0];
if (u.lastDay !== today) {
u.dReqs = 0;
u.dBytes = 0;
u.lastDay = today;
}
if (u.reqs === undefined) u.reqs = 0;
if (u.dReqs === undefined) u.dReqs = 0;
// One-time migration for rows written before byte accounting existed.
if (typeof u.bytes !== "number" || u.bytes < 0)
u.bytes = Math.floor((u.reqs || 0) * REQ_BYTES_EST);
if (typeof u.dBytes !== "number" || u.dBytes < 0)
u.dBytes =
u.lastDay === today
? Math.floor((u.dReqs || 0) * REQ_BYTES_EST)
: 0;
if (bytes === 0) {
u.reqs += 1;
u.dReqs += 1;
} else if (typeof bytes === "number" && bytes > 0) {
u.bytes += Math.floor(bytes);
u.dBytes += Math.floor(bytes);
}
const now = Date.now();
if (now - lastSysUsageSync > 30000) {
lastSysUsageSync = now;
if (env && env.IOT_DB) {
let changedConfig = false;
if (sysConfig.users && sysConfig.users.length > 0) {
sysConfig.users.forEach((u) => {
let uId = u.id.replace(/-/g, "").toLowerCase();
let sysU = sysUsageCache.users[uId];
if (!u.isPaused) {
let reason = null;
if (u.expiryMs && Date.now() > u.expiryMs) {
reason = `Expiration date reached (${new Date(u.expiryMs).toLocaleDateString()})`;
} else if (
sysU &&
u.limitTotalReq &&
usageTotalBytes(sysU) >=
limitReqToBytes(u.limitTotalReq)
) {
let usedGB = (
usageTotalBytes(sysU) / 1073741824
).toFixed(2);
let limitGB = (
limitReqToBytes(u.limitTotalReq) /
1073741824
).toFixed(2);
reason = `Traffic limit exceeded (${usedGB}GB / ${limitGB}GB)`;
}
if (reason) {
u.isPaused = true;
u.disabledReason = reason;
u.disabledAt = Date.now();
changedConfig = true;
ctx?.waitUntil(
logActivity(
env,
"User Auto-Disabled",
`User "${u.name}" (${u.id}) disabled: ${reason}`,
).catch(() => {}),
);
if (
sysConfig.tgToken &&
(sysConfig.tgAdminId || sysConfig.tgChatId)
) {
const tgMsg = `⚠️ <b>User Auto-Disabled</b>\n\n👤 <b>User:</b> ${u.name}\n🆔 <b>ID:</b> <code>${u.id}</code>\n📝 <b>Reason:</b> ${reason}`;
const notifyChatId =
sysConfig.tgAdminId || sysConfig.tgChatId;
ctx?.waitUntil(
fetchT(
`https://api.telegram.org/bot${sysConfig.tgToken}/sendMessage`,
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
chat_id: notifyChatId,
text: tgMsg,
parse_mode: "HTML",
}),
},
).catch(() => {}),
);
}
}
}
});
}
if (changedConfig) {
ctx?.waitUntil(
cachedD1Put(
env,
"sys_config",
JSON.stringify(sysConfig),
).catch(() => {}),
);
}
ctx?.waitUntil(
cachedD1Put(
env,
"sys_usage",
JSON.stringify(sysUsageCache),
).catch(() => {}),
);
}
}
}
export default {
async fetch(request, env, ctx) {
try {
if (!isolateStartTime) isolateStartTime = Date.now();
try {
INFLIGHT_HTTP++;
} catch (e) {}
try {
if (ctx && typeof ctx.waitUntil === "function") {
ctx.waitUntil(
Promise.resolve().then(() => {
try {
INFLIGHT_HTTP = Math.max(
0,
INFLIGHT_HTTP - 1,
);
} catch (e) {}
}),
);
}
} catch (e) {}
if (configRegistry.size > 10000) { configRegistry.clear(); trojanHashCache.clear(); }
await loadSysConfig(env, ctx);
// Background self-healing sweep (throttled): dead-relay probes
// + graveyard re-probes run in waitUntil, never blocking responses.
try {
const nowRs = Date.now();
if (nowRs - lastRelaySweep > 60000) {
lastRelaySweep = nowRs;
if (ctx && typeof ctx.waitUntil === "function") {
ctx.waitUntil(
(async () => {
try {
await probeDeadRelays(env);
} catch (e) {}
try {
await probeGraveyard(env);
} catch (e) {}
})(),
);
}
}
} catch (e) {}
activeDeviceId =
sysConfig.deviceId || generateHardwareId(sysConfig.apiRoute);
const url = new URL(request.url);
const upgradeHeader = request.headers.get("Upgrade");
const isTelemetryStream =
upgradeHeader && upgradeHeader.toLowerCase() === "websocket";
let reqPath = url.pathname;
if (reqPath.endsWith("/") && reqPath.length > 1)
reqPath = reqPath.slice(0, -1);
const routes = {
data: `/${encodeURI(sysConfig.apiRoute)}`,
dash: `/${encodeURI(sysConfig.apiRoute)}/dash`,
auth: `/${encodeURI(sysConfig.apiRoute)}/api/auth`,
sync: `/${encodeURI(sysConfig.apiRoute)}/api/sync`,
tg: `/${encodeURI(sysConfig.apiRoute)}/tg`,
syncPanel: `/${encodeURI(sysConfig.apiRoute)}/tg/sync_panel`,
logs: `/${encodeURI(sysConfig.apiRoute)}/api/logs`,
users: `/${encodeURI(sysConfig.apiRoute)}/api/users`,
stats: `/${encodeURI(sysConfig.apiRoute)}/api/stats`,
update: `/${encodeURI(sysConfig.apiRoute)}/api/update`,
apiKeys: `/${encodeURI(sysConfig.apiRoute)}/api/keys`,
};
const isSyncRoute = reqPath.endsWith("/api/sync");
const isUsersRoute =
reqPath === routes.users || reqPath.endsWith("/api/users");
const isStatsRoute =
reqPath === routes.stats || reqPath.endsWith("/api/stats");
const isUpdateRoute =
reqPath === routes.update || reqPath.endsWith("/api/update");
const isApiKeysRoute =
reqPath === routes.apiKeys || reqPath.endsWith("/api/keys");
const isAuthorizedRoute =
reqPath === routes.data ||
reqPath === routes.dash ||
reqPath === routes.auth ||
reqPath === routes.sync ||
reqPath === routes.tg ||
reqPath === routes.syncPanel ||
reqPath === routes.logs ||
isSyncRoute ||
isUsersRoute ||
isStatsRoute ||
isUpdateRoute ||
isApiKeysRoute;
if (!isTelemetryStream && !isAuthorizedRoute) {
return serveMaintenancePage(request, url);
}
// Maintenance mode (sysConfig.maintenanceMode): admin APIs stay
// open, already-open tunnels are unaffected (they are upgraded),
// but new tunnels and sub refreshes get a polite 503.
// Toggle by POSTing {"key":...,"config":{"maintenanceMode":true}}
// to /<apiRoute>/api/sync (merged, survives dashboard syncs).
if (
sysConfig.maintenanceMode &&
(isTelemetryStream || reqPath === routes.data)
) {
if (isTelemetryStream)
return new Response(null, { status: 503 });
return new Response(
"Maintenance in progress, retry later",
{
status: 503,
headers: { "Retry-After": "120" },
},
);
}
if (!isTelemetryStream) {
if (reqPath === routes.dash) {
const dashboardUrl = env.DASHBOARD_URL || 'https://raw.githubusercontent.com/itsyebekhe/nahan/main/dashboard.html';
try {
const resp = await fetchT(dashboardUrl);
let html = await resp.text();
html = html.replace(/__CURRENT_VERSION__/g, CURRENT_VERSION);
if (env.IOT_DB !== undefined) {
html = html.replace('__HAS_DB_WARNING__', '');
} else {
html = html.replace('__HAS_DB_WARNING__', '<div class="mb-5 p-4 rounded-2xl flex items-start gap-3" style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.2);"><span style="color:#f87171;">⚠️</span><span class="text-sm" style="color:#fca5a5;" data-i18n="missing_db">Database not connected. Settings won\'t be saved.</span></div>');
}
return new Response(html, {
headers: { "Content-Type": "text/html;charset=utf-8" },
});
} catch (e) {
return new Response('Failed to load dashboard', { status: 502 });
}
}
if (reqPath === routes.auth) {
if (request.method !== "POST")
return new Response("405", { status: 405 });
return await handleAuth(request, url.hostname, ctx, env);
}
if (reqPath === routes.sync || isSyncRoute) {
if (request.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers":
"Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
},
});
}
if (request.method !== "POST")
return new Response("405", { status: 405 });
const syncRes = await handleConfigSync(request, env, ctx);
syncRes.headers.set("Access-Control-Allow-Origin", "*");
syncRes.headers.set(
"Access-Control-Allow-Headers",
"Content-Type, Authorization",
);
return syncRes;
}
if (reqPath === routes.logs) {
if (request.method !== "POST" && request.method !== "GET")
return new Response("405", { status: 405 });
return await handleLogs(request, env);
}
if (isUsersRoute) {
return await handleUsersApi(request, env, ctx);
}
if (isStatsRoute) {
return await handleStatsApi(request, env);
}
if (isUpdateRoute) {
return await handleUpdateApi(request, env, ctx);
}
if (isApiKeysRoute) {
return await handleApiKeys(request, env, ctx);
}
if (reqPath === routes.syncPanel) {
if (request.method !== "POST")
return new Response("405", { status: 405 });
return await handleSyncPanel(request, env, ctx);
}
if (reqPath === routes.tg) {
if (request.method !== "POST")
return new Response("405", { status: 405 });
return await handleTelegramWebhook(
request,
env,
url.hostname,
ctx,
);
}
if (reqPath === routes.data) {
const ua = (
request.headers.get("User-Agent") || ""
).toLowerCase();
const isCustomUaAllowed =
sysConfig.subUserAgent &&
sysConfig.subUserAgent.trim().length > 0 &&
ua.includes(
sysConfig.subUserAgent.trim().toLowerCase(),
);
const clientHost =
request.headers.get("Host") || url.hostname;
let targetSub = url.searchParams.get("sub");
let hasMultiUser =
sysConfig.users && sysConfig.users.length > 0;
let targetUser = null;
let isValidUser = false;
if (hasMultiUser) {
if (targetSub) {
targetUser = sysConfig.users.find(
(u) =>
u.name.toLowerCase() ===
targetSub.toLowerCase() ||
u.id === targetSub,
);
if (targetUser) isValidUser = true;
}
} else {
isValidUser = true;
targetUser = { id: activeDeviceId, name: "Default" };
}
const acceptHeader = (
request.headers.get("Accept") || ""
).toLowerCase();
const secFetchDest = (
request.headers.get("Sec-Fetch-Dest") || ""
).toLowerCase();
const isRealBrowser =
(secFetchDest === "document" ||
acceptHeader.includes("text/html")) &&
(ua.includes("mozilla") ||
ua.includes("chrome") ||
ua.includes("safari") ||
ua.includes("applewebkit") ||
ua.includes("gecko") ||
ua.includes("opera") ||
ua.includes("edge")) &&
!ua.includes("cla" + "sh") &&
!ua.includes("si" + "ng-box") &&
!ua.includes("v" + "2r" + "ay") &&
!ua.includes("shadow" + "rocket") &&
!ua.includes("quantum" + "ult") &&
!ua.includes("surf" + "board") &&
!ua.includes("sta" + "sh");
if (isRealBrowser && !isCustomUaAllowed) {
if (isValidUser) {
const subscriptionUrl = env.SUBSCRIPTION_URL || 'https://raw.githubusercontent.com/itsyebekhe/nahan/main/subscription.html';
try {
const resp = await fetchT(subscriptionUrl);
let html = await resp.text();
// Compute dynamic values
const idClean = targetUser.id.replace(/-/g, '').toLowerCase();
const sysU = sysUsageCache?.users?.[idClean] || { reqs: 0, dReqs: 0, lastDay: '' };
const totalReqs = sysU.reqs || 0;
const todayDate = new Date().toISOString().split('T')[0];
const dailyReqs = sysU.lastDay === todayDate ? (sysU.dReqs || 0) : 0;
const limitTotal = targetUser.limitTotalReq || 0;
const limitDaily = targetUser.limitDailyReq || 0;
const totalBytesUsed = usageTotalBytes(sysU);
const dailyBytesUsed = usageDailyBytes(sysU, todayDate);
const limitTotalBytes = limitReqToBytes(limitTotal);
const limitDailyBytes = limitReqToBytes(limitDaily);
const totalGb = (totalBytesUsed / 1073741824).toFixed(2);
const limitTotalGb = limitTotal ? (limitTotalBytes / 1073741824).toFixed(2) : '9999';
const dailyGb = (dailyBytesUsed / 1073741824).toFixed(2);
const limitDailyGb = limitDaily ? (limitDailyBytes / 1073741824).toFixed(2) : '9999';
const totalPercent = limitTotal ? Math.min(100, (totalBytesUsed / limitTotalBytes) * 100).toFixed(1) : '0';
const dailyPercent = limitDaily ? Math.min(100, (dailyBytesUsed / limitDailyBytes) * 100).toFixed(1) : '0';
let expiryDateTxt = '2099-01-01';
let isExpired = false;
if (targetUser.expiryMs) {
expiryDateTxt = new Date(targetUser.expiryMs).toISOString().split('T')[0];
if (Date.now() > targetUser.expiryMs) isExpired = true;
}
let statusCode = 'active';
if (targetUser.isPaused) statusCode = 'paused';
else if (isExpired) statusCode = 'expired';
else if (limitTotal && totalBytesUsed >= limitTotalBytes) statusCode = 'limit';
else if (limitDaily && dailyBytesUsed >= limitDailyBytes) statusCode = 'dailyLimit';
let cleanUrl = new URL(url.href);
let panelUrlToUse = sysConfig.customPanelUrl;
if (targetUser.userPanelUrl && targetUser.userPanelUrl.trim()) panelUrlToUse = targetUser.userPanelUrl.trim();
if (panelUrlToUse) {
let customUrlStr = panelUrlToUse;
if (!customUrlStr.startsWith('http://') && !customUrlStr.startsWith('https://')) customUrlStr = 'https://' + customUrlStr;
try { const customUrl = new URL(customUrlStr); cleanUrl.protocol = customUrl.protocol; cleanUrl.host = customUrl.host; } catch(e) {}
}
cleanUrl.searchParams.delete('flag'); cleanUrl.searchParams.delete('format');
cleanUrl.searchParams.delete('type'); cleanUrl.searchParams.delete('output'); cleanUrl.searchParams.delete('raw');
const syncNormal = cleanUrl.href;
const syncRaw = cleanUrl.href + (cleanUrl.href.includes('?') ? '&flag=a' : '?flag=a');
// Total progress bar
let totalProgress = '';
if (limitTotal) {
totalProgress = `<div class="w-full rounded-full h-1.5 mt-3 overflow-hidden progress-bar-bg"><div class="h-1.5 rounded-full" style="background: var(--accent); width: ${totalPercent}%;"></div></div><p class="text-[10px] text-muted text-right mt-1.5" data-i18n="used">${totalPercent}% Used</p>`;
} else {
totalProgress = '<p class="text-[10px] text-muted mt-2" data-i18n="unlimitedPlan">Unlimited Plan</p>';
}
// Daily progress bar
let dailyProgress = '';
if (limitDaily) {
dailyProgress = `<div class="w-full rounded-full h-1.5 mt-3 overflow-hidden progress-bar-bg"><div class="h-1.5 rounded-full" style="background: var(--amber-text); width: ${dailyPercent}%;"></div></div><p class="text-[10px] text-muted text-right mt-1.5" data-i18n="used">${dailyPercent}% Used</p>`;
} else {
dailyProgress = '<p class="text-[10px] text-muted mt-2" data-i18n="noDailyLimit">No Daily Limit</p>';
}
// Replace placeholders
html = html.replace(/__USER_NAME__/g, targetUser.name);
html = html.replace(/__USER_ID__/g, targetUser.id);
html = html.replace(/__STATUS_CODE__/g, statusCode);
html = html.replace(/__TOTAL_GB__/g, totalGb);
html = html.replace(/__LIMIT_TOTAL_GB__/g, limitTotalGb);
html = html.replace(/__TOTAL_PERCENT__/g, totalPercent);
html = html.replace(/__DAILY_GB__/g, dailyGb);
html = html.replace(/__LIMIT_DAILY_GB__/g, limitDailyGb);
html = html.replace(/__DAILY_PERCENT__/g, dailyPercent);
html = html.replace(/__EXPIRY_DATE__/g, expiryDateTxt);
html = html.replace(/__SYNC_NORMAL__/g, syncNormal);
html = html.replace(/__SYNC_RAW__/g, syncRaw);
html = html.replace(/__TOTAL_PROGRESS__/g, totalProgress);
html = html.replace(/__DAILY_PROGRESS__/g, dailyProgress);
return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
} catch (e) {
return new Response('Failed to load subscription page', { status: 502 });
}
} else {
return serveMaintenancePage(request, url);
}
}
if (hasMultiUser && !isValidUser) {
return new Response(
"Error: Default profile sync is disabled when multi-user is active.",
{ status: 403 },
);
}
// Breaker L2: shed client sub refreshes under extreme
// load (browsers still get the info page above, open
// tunnels are unaffected).
try {
if (breakerLevel() >= 2 && !isRealBrowser) {
return new Response(
"Server busy, retry later",
{
status: 429,
headers: { "Retry-After": "60" },
},
);
}
} catch (e) {}
const allowInsecure =
url.searchParams.get("insecure") === "true" ||
url.searchParams.get("allowInsecure") === "true" ||
url.searchParams.get("allow_insecure") === "1" ||
url.searchParams.get("allowInsecure") === "1";
const resHeaders = new Headers();
resHeaders.set("Cache-Control", "no-store");
resHeaders.set("Access-Control-Allow-Origin", "*");
let flag = (
url.searchParams.get("flag") ||
url.searchParams.get("format") ||
url.searchParams.get("type") ||
url.searchParams.get("output") ||
""
).toLowerCase();
if (isValidUser && targetUser) {
let idClean = targetUser.id
.replace(/-/g, "")
.toLowerCase();
let sysU = sysUsageCache?.users?.[idClean] || {
reqs: 0,
dReqs: 0,
};
let totalReqs = sysU.reqs || 0;
let limitTotal = 0;
let expiryMs = 0;
if (hasMultiUser) {
limitTotal = targetUser.limitTotalReq || 0;
expiryMs = targetUser.expiryMs || 0;
} else {
limitTotal = sysConfig.limitTotalReq || 0;
expiryMs = sysConfig.expiryMs || 0;
}
let usedBytes = usageTotalBytes(sysU);
let limitBytes = limitReqToBytes(limitTotal);
let expireSec = expiryMs
? Math.floor(expiryMs / 1000)
: 0;
const subUserInfo = `upload=0; download=${usedBytes}; total=${limitBytes}; expire=${expireSec}`;
resHeaders.set("Subscription-UserInfo", subUserInfo);
resHeaders.set("subscription-userinfo", subUserInfo);
resHeaders.set("Profile-Update-Interval", "12");
resHeaders.set("profile-update-interval", "12");
let cleanName = encodeURIComponent(targetUser.name);
resHeaders.set(
"Content-Disposition",
`attachment; filename="${cleanName}"; filename*=UTF-8''${cleanName}`,
);
}
// Determine subscription format
let isClashYaml = false;
let isSingboxJson = false;
let isClashJson = false;
let isVJson = false;
// If flag is explicitly set, we respect it
if (
flag === "clash" ||
flag === "yaml" ||
flag === "meta" ||
flag === "stash" ||
flag === "clash-meta" ||
flag === "y"