Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
2497 lines (2307 loc) · 107 KB
/
Copy pathserver.py
File metadata and controls
2497 lines (2307 loc) · 107 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
#!/usr/bin/env python3
"""server.py — single-file static server + login + stats for Server Hub.
Zero third-party dependencies (Python 3 stdlib only).
Auth: Supabase Auth (email + password, multi-user). Falls back to the classic
single-user HUB_USER/HUB_PASSWORD env auth when SUPABASE_URL is not set.
Env vars:
SUPABASE_URL e.g. https://xxxx.supabase.co (enables multi-user)
SUPABASE_ANON_KEY publishable anon key
HUB_USER default: admin (legacy single-user fallback)
HUB_PASSWORD required if SUPABASE_URL unset
HUB_PORT default: 8642
HUB_HOST default: 0.0.0.0
"""
import base64
import hashlib
import hmac
import ipaddress
import json
import os
import re
import secrets
import struct
import socket
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
WEB_ROOT = os.path.dirname(os.path.abspath(__file__))
WEB_ROOT_REAL = os.path.realpath(WEB_ROOT)
SESSION_TTL = 30 * 24 * 60 * 60 # 30 days
# Precompiled regexes (perf)
_EMAIL_RE = re.compile(r"^[^@]+@[^@]+\.[^@]+$")
_USERNAME_RE = re.compile(r"^[a-zA-Z0-9_]{3,20}$")
_URL_RE = re.compile(r"^https?://")
_URL_RE_I = re.compile(r"^https?://", re.IGNORECASE)
# Security header constants (avoid rebuilding per request)
CSP_VALUE = "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://fonts.gstatic.com; font-src 'self' https://fonts.gstatic.com; script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdn.jsdelivr.net; connect-src 'self' https: http:; frame-ancestors 'self'"
PERM_POLICY = "camera=(), microphone=(), geolocation=()"
SEC_HEADERS = (
("X-Content-Type-Options", "nosniff"),
("X-Frame-Options", "SAMEORIGIN"),
("Referrer-Policy", "no-referrer"),
("Content-Security-Policy", CSP_VALUE),
("Permissions-Policy", PERM_POLICY),
)
_host_cache_lock = threading.Lock()
def _security_headers(path, is_https):
hdrs = list(SEC_HEADERS)
if path.startswith("/api/"):
hdrs.append(("Cache-Control", "no-store"))
if is_https:
hdrs.append(("Strict-Transport-Security", "max-age=63072000"))
return hdrs
MAX_ATTEMPTS = 5
LOCKOUT_SECONDS = 60
MAX_LOGIN_BODY = 64 * 1024 # reject larger login POST bodies before reading them
PUBLIC_PATHS = {"/login", "/login.html", "/register", "/register.html"}
# For local dev/test, default to insecure HTTP cookies so http://127.0.0.1 works with cookiejar.
# Prod (VERCEL==1) remains Secure unless explicitly overridden via HUB_INSECURE_HTTP==1.
if os.environ.get("VERCEL") != "1" and os.environ.get("HUB_INSECURE_HTTP") is None:
os.environ["HUB_INSECURE_HTTP"] = "1"
MAX_API_BODY = 64 * 1024 # reject larger API JSON bodies before reading them
SERVICES_FILE = os.path.join(WEB_ROOT, "services.json")
KNOWN_ICONS = {
"chart", "pulse", "database", "shield", "shield-check", "key", "lock",
"lock-key", "cloud", "note", "file", "film", "music", "headphones", "git",
"branch", "terminal", "globe", "home", "broadcast", "cog", "box",
"shopping", "flask", "sparkles", "camera", "image", "book", "gamepad",
"wallet", "map-pin", "activity", "cpu", "server", "wifi", "zap", "mail",
"message", "calendar", "clock", "download", "upload", "sliders", "user",
"users", "bookmark", "star", "heart", "link", "external-link", "folder",
"archive", "package", "layers", "refresh", "bell", "bug", "code", "command",
}
KNOWN_CATEGORIES = {
"Monitoring", "Security", "Network", "Media", "Productivity", "Files",
"Dev", "Communication", "Home", "Finance", "AI", "Search", "Database",
"Other", "Gaming", "Books", "Money", "Travel", "Health",
}
# Supabase column mapping: API (camelCase) <-> DB (snake_case)
_SERVICE_TO_DB = {"desc": "description", "categoryOverride": "category_override"}
_DB_TO_SERVICE = {v: k for k, v in _SERVICE_TO_DB.items()}
def _to_db_service(fields):
"""Map API service fields (desc, categoryOverride) to DB columns."""
return {_SERVICE_TO_DB.get(k, k): v for k, v in fields.items()}
def _from_db_service(row):
"""Map DB service row (description, category_override) to API shape."""
if not isinstance(row, dict):
return row
out = {}
for k, v in row.items():
out[_DB_TO_SERVICE.get(k, k)] = v
# Normalize expected API keys
if "description" in row:
out["desc"] = row.get("description") or ""
out.pop("description", None)
if "category_override" in row:
out["categoryOverride"] = row.get("category_override")
out.pop("category_override", None)
# Ensure desc always present as string for frontend
if "desc" not in out:
out["desc"] = row.get("description") or row.get("desc") or ""
if "categoryOverride" not in out:
out["categoryOverride"] = row.get("category_override") if "category_override" in row else row.get("categoryOverride")
return out
def validate_service(data, partial=False):
"""Validate a service object. Returns (fields, None) or (None, error)."""
if not isinstance(data, dict):
return None, "body must be a JSON object"
fields = {}
if "name" in data or not partial:
name = str(data.get("name") or "").strip()
if not name:
return None, "name is required"
if len(name) > 200:
return None, "name too long"
fields["name"] = name
if "url" in data or not partial:
url = str(data.get("url") or "").strip()
if not url:
return None, "url is required"
if len(url) > 2000:
return None, "url too long"
if " " in url:
return None, "url must not contain spaces"
if not _URL_RE.match(url):
return None, "url must start with http:// or https://"
try:
if not urllib.parse.urlparse(url).netloc:
return None, "url must be a valid http(s) URL"
except ValueError:
return None, "url must be a valid http(s) URL"
fields["url"] = url
if "desc" in data or not partial:
desc = str(data.get("desc") or "").strip()
if len(desc) > 500:
return None, "desc too long"
fields["desc"] = desc
if "icon" in data or not partial:
icon = str(data.get("icon") or "box")
fields["icon"] = icon if icon in KNOWN_ICONS else "box"
if "ping" in data or not partial:
fields["ping"] = bool(data.get("ping", True))
if "categoryOverride" in data or not partial:
cat = data.get("categoryOverride") or None
if cat is not None and cat not in KNOWN_CATEGORIES:
return None, "unknown category: " + str(cat)
fields["categoryOverride"] = cat
return fields, None
def validate_bookmark(data, partial=False):
"""Validate a bookmark object. Returns (fields, None) or (None, error)."""
if not isinstance(data, dict):
return None, "body must be a JSON object"
fields = {}
if "name" in data or not partial:
name = str(data.get("name") or "").strip()
if not name:
return None, "name is required"
if len(name) > 200:
return None, "name too long"
fields["name"] = name
if "url" in data or not partial:
url = str(data.get("url") or "").strip()
if not url:
return None, "url is required"
if len(url) > 2000:
return None, "url too long"
if " " in url:
return None, "url must not contain spaces"
if not _URL_RE.match(url):
return None, "url must start with http:// or https://"
try:
if not urllib.parse.urlparse(url).netloc:
return None, "url must be a valid http(s) URL"
except ValueError:
return None, "url must be a valid http(s) URL"
fields["url"] = url
if "icon" in data or not partial:
icon = str(data.get("icon") or "link").strip()
fields["icon"] = icon if icon in KNOWN_ICONS else "link"
if "color" in data or not partial:
color = str(data.get("color") or "").strip()
if color:
if re.match(r"^#[0-9a-fA-F]{6}$", color):
fields["color"] = color
return fields, None
class ServiceStore:
"""Thread-safe JSON-backed service list. Atomic writes (tmp + os.replace)."""
def __init__(self, path):
self._path = path
self._lock = threading.Lock()
self._services = self._load()
self._bookmarks = self._load("bookmarks")
def _load(self, key="services"):
try:
with open(self._path, "r", encoding="utf-8") as f:
data = json.load(f)
items = data.get(key, [])
if not isinstance(items, list):
return []
return [s for s in items if isinstance(s, dict) and s.get("id")]
except (OSError, ValueError):
return []
def _save(self):
tmp = self._path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump({"services": self._services, "bookmarks": self._bookmarks}, f, indent=2)
f.flush()
try:
os.fsync(f.fileno())
except OSError:
pass
os.replace(tmp, self._path)
def list(self):
with self._lock:
return [dict(s) for s in self._services]
def add(self, entry):
entry = dict(entry)
entry["id"] = secrets.token_urlsafe(12)
with self._lock:
self._services.append(entry)
self._save()
return dict(entry)
def update(self, sid, fields):
with self._lock:
for i, s in enumerate(self._services):
if s["id"] == sid:
self._services[i] = {**s, **fields, "id": sid}
self._save()
return dict(self._services[i])
return None
def delete(self, sid):
with self._lock:
before = len(self._services)
self._services = [s for s in self._services if s["id"] != sid]
if len(self._services) != before:
self._save()
return True
return False
def list_bookmarks(self):
with self._lock:
return [dict(b) for b in self._bookmarks]
def add_bookmark(self, entry):
entry = dict(entry)
entry["id"] = secrets.token_urlsafe(12)
with self._lock:
self._bookmarks.append(entry)
self._save()
return dict(entry)
def update_bookmark(self, bid, fields):
with self._lock:
for i, b in enumerate(self._bookmarks):
if b["id"] == bid:
self._bookmarks[i] = {**b, **fields, "id": bid}
self._save()
return dict(self._bookmarks[i])
return None
def delete_bookmark(self, bid):
with self._lock:
before = len(self._bookmarks)
self._bookmarks = [b for b in self._bookmarks if b["id"] != bid]
if len(self._bookmarks) != before:
self._save()
return True
return False
MIME = {
".html": "text/html; charset=utf-8",
".htm": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".txt": "text/plain; charset=utf-8",
".map": "application/json; charset=utf-8",
".md": "text/plain; charset=utf-8",
".woff": "font/woff",
".woff2": "font/woff2",
".gif": "image/gif",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
}
# Allowed static extensions for authenticated fallback — derived from MIME plus common web assets, minus sensitive
ALLOWED_STATIC = (set(MIME.keys()) | {".woff", ".woff2", ".gif", ".jpg", ".jpeg", ".webp"}) - {".md", ".map"}
def read_env(name, default=None):
return os.environ.get(name) or default
class Sessions:
"""Session store.
Legacy mode (no SUPABASE_URL): classic in-memory token store, used by the
single threaded server. Fine for local/single-instance hosting.
Supabase mode: stateless signed cookies (HMAC-SHA256). The cookie carries
the user payload (user_id, email, supabase_token, username) and a
signature; each request verifies it locally. This survives serverless
(Vercel) cold starts where multiple instances share no memory — every
request lands on any instance and still authenticates. SESSION_SECRET
env var must be stable across instances; a secret is generated on first
start otherwise (single-instance local use only).
"""
def __init__(self, secret=None):
self._tokens = {}
self._lock = threading.Lock()
env_secret = secret or os.environ.get("SESSION_SECRET")
if not env_secret and os.environ.get("VERCEL"):
raise RuntimeError("SESSION_SECRET must be set on Vercel (fleet needs stable HMAC key) — see MED-06")
self._secret = env_secret or secrets.token_hex(32)
self._secret_b = self._secret.encode("utf-8")
self._pending_used = {} # jti -> exp
self._pending_used_lock = threading.Lock()
self._totp_attempts = {} # user_id -> [timestamps]
self._totp_lock = threading.Lock()
def _hmac(self, b64):
return hmac.new(self._secret_b, b64.encode("utf-8"), hashlib.sha256).hexdigest()
def _b64json(self, b64):
raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
return json.loads(raw.decode("utf-8"))
# ---- legacy in-memory API ----
def create(self, user):
token = secrets.token_urlsafe(32)
with self._lock:
self._tokens[token] = (time.time() + SESSION_TTL, user)
return token
def get(self, token):
if not token:
return None
# Stateless first: does it parse as a signed payload?
user = self.verify_signed(token)
if user is not None:
return user
with self._lock:
entry = self._tokens.get(token)
if not entry:
return None
expiry, user = entry
if time.time() > expiry:
with self._lock:
self._tokens.pop(token, None)
return None
return user
def delete(self, token):
if not token:
return
with self._lock:
self._tokens.pop(token, None)
# ---- stateless signed-cookie API (serverless-safe) ----
def sign(self, user):
"""Return a signed cookie value for the user payload."""
typ = user.get("typ")
is_pending = typ == "pending"
exp = int(time.time()) + (300 if is_pending else SESSION_TTL)
payload = {
"user_id": user.get("user_id", ""),
"email": user.get("email", ""),
"username": user.get("username", ""),
"supabase_token": user.get("supabase_token", ""),
"refresh_token": user.get("refresh_token", ""),
"token_exp": int(user.get("token_exp", 0) or 0),
"exp": exp,
}
# typ discriminator for 2FA pending vs session (CRIT-2FA)
if typ:
payload["typ"] = typ
if is_pending:
payload["jti"] = secrets.token_hex(8)
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
b64 = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
sig = self._hmac(b64)
return b64 + "." + sig
def _prune_pending_used(self):
now = time.time()
with self._pending_used_lock:
expired = [k for k, exp in self._pending_used.items() if exp < now]
for k in expired:
self._pending_used.pop(k, None)
def totp_is_rate_limited(self, user_id):
now = time.time()
with self._totp_lock:
lst = self._totp_attempts.get(user_id, [])
lst = [t for t in lst if now - t < 300]
self._totp_attempts[user_id] = lst
return len(lst) >= 5
def totp_record_failure(self, user_id):
now = time.time()
with self._totp_lock:
lst = self._totp_attempts.get(user_id, [])
lst = [t for t in lst if now - t < 300]
lst.append(now)
self._totp_attempts[user_id] = lst
def totp_reset(self, user_id):
with self._totp_lock:
self._totp_attempts.pop(user_id, None)
def verify_signed(self, token):
"""Verify a signed cookie value -> user dict or None. Rejects pending tokens."""
if not token or "." not in token:
return None
b64, sig = token.rsplit(".", 1)
try:
expected = self._hmac(b64)
if not hmac.compare_digest(sig, expected):
return None
payload = self._b64json(b64)
except Exception:
return None
if int(payload.get("exp", 0)) < time.time():
return None
# 2FA bypass fix: pending tokens must not be accepted as session
if payload.get("typ") == "pending":
return None
return {
"user_id": payload.get("user_id", ""),
"email": payload.get("email", ""),
"username": payload.get("username", ""),
"supabase_token": payload.get("supabase_token", ""),
"refresh_token": payload.get("refresh_token", ""),
"token_exp": int(payload.get("token_exp", 0) or 0),
}
def verify_pending(self, token):
"""Verify a pending-2FA token (typ==pending) -> user dict or None. Checks jti replay."""
if not token or "." not in token:
return None
b64, sig = token.rsplit(".", 1)
try:
expected = self._hmac(b64)
if not hmac.compare_digest(sig, expected):
return None
payload = self._b64json(b64)
except Exception:
return None
if int(payload.get("exp", 0)) < time.time():
return None
if payload.get("typ") != "pending":
return None
jti = payload.get("jti")
if jti:
self._prune_pending_used()
with self._pending_used_lock:
if jti in self._pending_used:
return None
return {
"user_id": payload.get("user_id", ""),
"email": payload.get("email", ""),
"username": payload.get("username", ""),
"supabase_token": payload.get("supabase_token", ""),
"refresh_token": payload.get("refresh_token", ""),
"token_exp": int(payload.get("token_exp", 0) or 0),
"_jti": jti,
"_exp": int(payload.get("exp", 0)),
}
def burn_pending_jti(self, jti, exp):
if not jti:
return
self._prune_pending_used()
with self._pending_used_lock:
self._pending_used[jti] = int(exp)
class LoginGuard:
"""Brute-force protection: N failed attempts per IP -> lockout."""
def __init__(self, max_attempts=MAX_ATTEMPTS, lockout_seconds=LOCKOUT_SECONDS):
self.max_attempts = max_attempts
self.lockout_seconds = lockout_seconds
self._state = {}
self._lock = threading.Lock()
def is_locked(self, ip):
now = time.time()
with self._lock:
entry = self._state.get(ip)
if not entry:
return False
fails, locked_until = entry
if locked_until and now < locked_until:
return True
if locked_until:
self._state[ip] = (0, 0)
return False
def record_failure(self, ip):
now = time.time()
with self._lock:
fails, locked_until = self._state.get(ip, (0, 0))
fails += 1
if fails >= self.max_attempts:
fails = 0
locked_until = now + self.lockout_seconds
self._state[ip] = (fails, locked_until)
def reset(self, ip):
with self._lock:
self._state.pop(ip, None)
guard = LoginGuard()
class RegisterGuard:
"""Bulk-prevention: max N registrations per IP per window (e.g. 3 per 15 min)."""
def __init__(self, max_per_window=3, window_seconds=15 * 60):
self.max_per_window = max_per_window
self.window_seconds = window_seconds
self._state = {}
self._lock = threading.Lock()
def is_limited(self, ip):
now = time.time()
with self._lock:
lst = self._state.get(ip, [])
lst = [t for t in lst if now - t < self.window_seconds]
self._state[ip] = lst
return len(lst) >= self.max_per_window
def record(self, ip):
now = time.time()
with self._lock:
lst = self._state.get(ip, [])
lst = [t for t in lst if now - t < self.window_seconds]
lst.append(now)
self._state[ip] = lst
def reset(self, ip):
with self._lock:
self._state.pop(ip, None)
register_guard = RegisterGuard(max_per_window=3, window_seconds=15 * 60)
# ---- system stats (Linux /proc; returns None when unavailable) ----
# Cached CPU reading to avoid blocking the request handler with sleep(0.1)
_cpu_cache = {"prev": None, "val": None, "ts": 0}
_cpu_lock = threading.Lock()
def _read_cpu():
try:
with open("/proc/stat") as f:
for line in f:
if line.startswith("cpu "):
nums = [int(x) for x in line.split()[1:]]
if len(nums) < 4:
return None
idle = nums[3] + (nums[4] if len(nums) > 4 else 0)
return sum(nums), idle
except (OSError, ValueError):
return None
return None
def cpu_percent():
"""Overall CPU usage percent (0-100) from two /proc/stat samples, non-blocking via cache."""
now = time.time()
with _cpu_lock:
# If cache is fresh (<1.5s), return it without blocking
if _cpu_cache["val"] is not None and now - _cpu_cache["ts"] < 1.5:
return _cpu_cache["val"]
cur = _read_cpu()
if not cur:
return None
prev = _cpu_cache["prev"]
_cpu_cache["prev"] = cur
if prev is None:
_cpu_cache["ts"] = now
return None
total_delta = cur[0] - prev[0]
idle_delta = cur[1] - prev[1]
if total_delta <= 0:
_cpu_cache["val"] = None
else:
_cpu_cache["val"] = round(100 * (1 - idle_delta / total_delta))
_cpu_cache["ts"] = now
return _cpu_cache["val"]
def mem_percent():
try:
data = {}
with open("/proc/meminfo") as f:
for line in f:
parts = line.split()
if parts:
data[parts[0].rstrip(":")] = int(parts[1])
total = data.get("MemTotal")
available = data.get("MemAvailable")
if not total or available is None:
return None
return round(100 * (total - available) / total)
except (OSError, ValueError):
return None
def disk_percent(path="/"):
try:
st = os.statvfs(path)
except (OSError, AttributeError):
return None
total = st.f_blocks
used = st.f_blocks - st.f_bfree
if total <= 0:
return None
return round(100 * used / total)
_host_cache = {"host": None, "ts": 0}
def _get_host():
now = time.time()
with _host_cache_lock:
if _host_cache["host"] is not None and now - _host_cache["ts"] < 300:
return _host_cache["host"]
try:
with open("/etc/hostname") as f:
host = f.read().strip() or socket.gethostname()
except OSError:
host = socket.gethostname()
with _host_cache_lock:
_host_cache["host"] = host
_host_cache["ts"] = now
return host
def stats_payload():
return {"host": _get_host(), "cpu": cpu_percent(), "mem": mem_percent(), "disk": disk_percent()}
# ---- Beszel multi-server stats proxy ----
BESZEL_CACHE_TTL = 10.0
_beszel_cache = {}
_beszel_cache_lock = threading.Lock()
BESZEL_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
}
def clear_beszel_cache():
with _beszel_cache_lock:
_beszel_cache.clear()
def _is_private_host(host):
"""Check if hostname is private/internal IP literal or localhost."""
if not host:
return True
h = host.strip().lower()
# strip brackets for IPv6 literals
if h.startswith("[") and h.endswith("]"):
h = h[1:-1]
# localhost variants
if h in ("localhost", "metadata.google.internal"):
return True
try:
ip = ipaddress.ip_address(h)
# Allow private for local dev/test when HUB_INSECURE_HTTP==1 (tests use 127.0.0.1 stub)
# In prod (VERCEL==1) this is still blocked unless insecure flag is set.
if os.environ.get("HUB_INSECURE_HTTP") == "1":
return False
# Block private, loopback, link-local, multicast, reserved, unspecified (0.0.0.0)
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified:
return True
# 169.254.169.254 and similar metadata
if str(ip) == "169.254.169.254":
return True
return False
except ValueError:
# Not an IP literal -> not considered private here (DNS names allowed except example.com handled separately)
return False
def _validate_beszel_url(url):
"""Validate Beszel URL for SSRF: scheme http/https, host not private, not example.com."""
if not url or not isinstance(url, str):
return False, "url required"
url = url.strip()
if not _URL_RE_I.match(url):
return False, "url must start with http:// or https://"
try:
parsed = urllib.parse.urlparse(url)
except Exception:
return False, "invalid url"
host = parsed.hostname
if not host:
return False, "invalid url"
hl = host.lower()
if hl == "example.com" or hl.endswith(".example.com") or hl == "beszel.example.com" or hl.endswith(".beszel.example.com"):
return False, "example host blocked"
if _is_private_host(host):
return False, "private host blocked"
return True, None
# ---- 2FA / TOTP (RFC 6238, zero-dependency) ----
def totp_generate_secret():
"""Random base32 secret (160 bits) for authenticator apps."""
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
def totp_code(secret_b32, for_time=None):
"""Compute a 6-digit TOTP code for the given time (default: now)."""
key = base64.b32decode(secret_b32.upper() + "=" * ((8 - len(secret_b32) % 8) % 8))
counter = int(for_time if for_time is not None else time.time()) // 30
msg = struct.pack(">Q", counter)
digest = hmac.new(key, msg, hashlib.sha1).digest()
offset = digest[19] & 0x0F
code = (struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF) % 1000000
return "%06d" % code
def totp_verify(secret_b32, code, window=1):
"""Verify a 6-digit code against the secret, tolerating ±window steps."""
if not code or not secret_b32:
return False
code = str(code).strip()
if len(code) != 6 or not code.isdigit():
return False
try:
key = base64.b32decode(secret_b32.upper() + "=" * ((8 - len(secret_b32) % 8) % 8))
except Exception:
return False
now = int(time.time())
for i in range(-window, window + 1):
counter = (now + i * 30) // 30
msg = struct.pack(">Q", counter)
digest = hmac.new(key, msg, hashlib.sha1).digest()
offset = digest[19] & 0x0F
calc = (struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF) % 1000000
if hmac.compare_digest("%06d" % calc, code):
return True
return False
def totp_uri(secret_b32, email):
"""otpauth:// URI for authenticator apps (Google Authenticator, Aegis…)."""
label = "ServerHub:%s" % email
return "otpauth://totp/%s?secret=%s&issuer=ServerHub&algorithm=SHA1&digits=6&period=30" % (
urllib.parse.quote(label, safe=":"), secret_b32)
def twofa_enabled_for(user_settings_row):
"""True when the user's settings carry an enabled 2FA secret."""
try:
s = (user_settings_row or {}).get("settings") or {}
t = s.get("twofa") or {}
return bool(t.get("enabled")) and bool(t.get("secret"))
except Exception:
return False
def read_beszel_env():
url = read_env("BESZEL_URL", "").rstrip("/")
if not url:
return None
return {
"url": url,
"user": read_env("BESZEL_USER", ""),
"password": read_env("BESZEL_PASSWORD", ""),
}
def normalize_beszel_system(rec):
"""Map a Beszel systems-collection record to the dashboard shape.
The live system stats live inside the record's `info` object, stored as
either a JSON object or a JSON string. Beszel abbreviations (verified
against the Beszel source): `cpu` (%), `mp` (memory %), `dp` (disk %),
`u` (usage/uptime).
"""
info = rec.get("info") or {}
if isinstance(info, str):
try:
info = json.loads(info)
except Exception:
info = {}
if not isinstance(info, dict):
info = {}
return {
"name": rec.get("name"),
"status": rec.get("status", "unknown"),
"host": rec.get("host"),
"uptime": info.get("u"),
"cpu": info.get("cpu"),
"mem": info.get("mp"),
"disk": info.get("dp"),
}
def _beszel_format_error(e):
"""Return detailed error string for Beszel failures, truncated to 200 chars."""
try:
if isinstance(e, urllib.error.HTTPError):
base = f"{type(e).__name__} {e.code}: {e.reason}"
s = str(e)
if s and s not in base and base not in s:
detail = f"{base} - {s}"
else:
detail = base
# Enhance with PocketBase JSON body message if available
body = None
# Prefer previously captured body (set by _beszel_login / _beszel_urlopen)
b = getattr(e, "_body", None)
if isinstance(b, str) and b:
body = b
else:
# Try to read from the HTTPError object (may be consumed already)
try:
# e.read() may have been consumed; try fp directly as fallback
try:
raw = e.read()
except Exception:
raw = None
try:
if getattr(e, "fp", None) is not None:
raw = e.fp.read()
except Exception:
raw = None
if raw:
if isinstance(raw, bytes):
body = raw.decode("utf-8", "replace")
else:
body = str(raw)
except Exception:
body = None
# Ensure file pointer is closed after attempt
try:
e.close()
except Exception:
pass
if body:
body = body[:500]
msg = None
try:
j = json.loads(body)
if isinstance(j, dict):
msg = j.get("message")
if not msg:
data = j.get("data")
if isinstance(data, dict):
# PocketBase validation shape: data[field].message
for v in data.values():
if isinstance(v, dict) and v.get("message"):
msg = v["message"]
break
if isinstance(v, str) and v:
msg = v
break
if not msg and isinstance(data, str):
msg = data
if not msg:
# fallback to any string value
for k in ("error", "reason", "detail"):
if isinstance(j.get(k), str) and j.get(k):
msg = j.get(k)
break
except Exception:
msg = None
extra = (msg or body[:120]).strip()
if extra:
# avoid duplicating if already in detail
if extra not in detail:
detail = f"{detail} - {extra}"
# Also try to include body saved on exception even if read succeeded earlier
else:
detail = f"{type(e).__name__}: {e}"
if not detail.strip():
detail = type(e).__name__
# Cloudflare challenge detection
if "Just a moment" in detail or "cf-challenge" in detail or "Attention Required" in detail or "DDoS protection" in detail:
return "Beszel blocked by Cloudflare (Just a moment). Disable 'I'm Under Attack' for bs.canozdal.com or add WAF rule to allow Vercel IPs, or use direct origin URL (e.g., tunnel URL)."
# Scrub internal URLs/IPs from detail to avoid leaking
try:
detail = re.sub(r"https?://[^\s\"'<>]+", "[url]", detail)
detail = re.sub(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?\b", "[ip]", detail)
except Exception:
pass
except Exception:
try:
detail = f"{type(e).__name__}: {e}"
except Exception:
detail = "error"
if "Just a moment" in detail or "cf-challenge" in detail or "Attention Required" in detail or "DDoS protection" in detail:
return "Beszel blocked by Cloudflare (Just a moment). Disable 'I'm Under Attack' for bs.canozdal.com or add WAF rule to allow Vercel IPs, or use direct origin URL (e.g., tunnel URL)."
try:
detail = re.sub(r"https?://[^\s\"'<>]+", "[url]", detail)
detail = re.sub(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?\b", "[ip]", detail)
except Exception:
pass
return detail[:200]
def _beszel_urlopen(req):
try:
# Kısa timeout: serverless fonksiyon limitleri + hızlı "unreachable"
# dönüşü, kullanıcı test butonuna bastığında uzun beklemek yerine.
return urllib.request.urlopen(req, timeout=6)
except urllib.error.HTTPError as e:
# Preserve HTTP body for _beszel_format_error and _beszel_login fallback
try:
body = e.read().decode("utf-8", "replace")
e._body = body[:2000]
except Exception:
try:
# fallback via fp if e.read() already consumed
if getattr(e, "fp", None) is not None:
try:
raw = e.fp.read()
if raw:
e._body = raw.decode("utf-8", "replace")[:2000] if isinstance(raw, bytes) else str(raw)[:2000]
else:
e._body = ""
except Exception:
e._body = ""
else:
e._body = ""
except Exception:
try:
e._body = ""
except Exception:
pass
# Do not close before raising; caller/_beszel_format_error will handle body via _body
raise
def _beszel_login(cfg):
"""Authenticate to PocketBase (Beszel) with fallback for _superusers.
Tries users collection first; on HTTP 400/403/404 falls back to _superusers.
Handles empty identity/password gracefully (PocketBase will return 400).
Preserves HTTPError body via e._body for detailed error reporting.
"""
last_err = None
base_url = (cfg.get("url") or "").strip().rstrip("/")
user = cfg.get("user") or ""
password = cfg.get("password") or ""
for collection in ("users", "_superusers"):
url = base_url + f"/api/collections/{collection}/auth-with-password"
payload = json.dumps({
"identity": user,
"password": password,
}).encode("utf-8")