-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
6664 lines (5660 loc) · 221 KB
/
app.py
File metadata and controls
6664 lines (5660 loc) · 221 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 os, glob, subprocess, time, shlex, logging, ipaddress, psutil, requests, json, tempfile, sys, zipfile, datetime as dt, ipaddress, platform, re, qrcode, multiprocessing, threading
from io import BytesIO
from logging.handlers import RotatingFileHandler
from datetime import datetime, timedelta
from flask import (
Flask, render_template, redirect, url_for, flash, request,
jsonify, abort, current_app, make_response, send_file, session, g
)
from sqlalchemy.exc import OperationalError
from cryptography.fernet import Fernet, InvalidToken
from pathlib import Path
from functools import wraps
import zipfile, socket
from flask_login import (
LoginManager, UserMixin, login_user, login_required, logout_user, current_user
)
from dotenv import load_dotenv
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INSTANCE_DIR = os.path.join(BASE_DIR, "instance")
DB_PATH = os.path.join(INSTANCE_DIR, "wg_panel.db")
load_dotenv(os.path.join(BASE_DIR, '.env'))
from config import Config
from models import db, InterfaceConfig, Peer, PeerEvent, Node, Admin2FA, AdminAccount
from forms import PeerForm
from auth import require_api_key, admin_required, require_api_key_or_login
from sqlalchemy import or_, and_, text, inspect, func
from flask_wtf.csrf import CSRFProtect, generate_csrf
from urllib.parse import urlparse, urljoin
import secrets, hashlib, string, pyotp
from werkzeug.exceptions import HTTPException
from werkzeug.middleware.proxy_fix import ProxyFix
def hash_recovery(code: str) -> str:
return "sha256$" + hashlib.sha256(code.encode("utf-8")).hexdigest()
def verify_recovery(code: str, stored: str) -> bool:
if not stored:
return False
if stored.startswith("sha256$"):
return stored == hash_recovery(code)
try:
import bcrypt as pybcrypt
if stored.startswith("$2") or stored.startswith("$bcrypt$"):
return pybcrypt.checkpw(code.encode("utf-8"), stored.encode("utf-8"))
except Exception:
pass
return False
def _gen_recovery(n=10, length=10):
alphabet = string.ascii_uppercase + string.digits
return [''.join(secrets.choice(alphabet) for _ in range(length)) for _ in range(n)]
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
def _ssl_context():
import ssl, os
s = _load_panel_settings() or {}
cert = (s.get('tls_cert_path') or '').strip()
key = (s.get('tls_key_path') or '').strip()
if cert and key and os.path.isfile(cert) and os.path.isfile(key):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(certfile=cert, keyfile=key)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
return ctx
return None
# ==================================================================
def _admin_columns():
insp = inspect(db.engine)
if not insp.has_table('admin_account'):
db.create_all()
return
cols = {c['name'] for c in insp.get_columns('admin_account')}
to_add = []
if 'totp_secret' not in cols:
to_add.append(("totp_secret", "TEXT"))
if 'recovery_codes' not in cols:
to_add.append(("recovery_codes", "TEXT"))
if 'twofa_enabled' not in cols:
to_add.append(("twofa_enabled", "INTEGER DEFAULT 0"))
if 'last_totp_counter' not in cols:
to_add.append(("last_totp_counter", "INTEGER DEFAULT 0"))
if to_add:
with db.engine.begin() as conn:
for name, typ in to_add:
conn.execute(text(f'ALTER TABLE admin_account ADD COLUMN {name} {typ}'))
app.config.from_object(Config)
os.makedirs(app.instance_path, exist_ok=True)
db.init_app(app)
PEER_PROFILE_FILE = os.path.join(app.instance_path, 'peer_profile.json')
PEER_PROFILES_FILE = os.path.join(app.instance_path, 'peer_profiles.json')
_DEF_PROFILE = {
'dns': '1.1.1.1, 1.0.0.1',
'allowed_ips': '0.0.0.0/0, ::/0',
'persistent_keepalive': None,
'mtu': None,
'endpoint': '',
'data_limit_value': 0,
'data_limit_unit': 'Gi',
'start_on_first_use': False,
'unlimited': False,
'time_limit_days': 0,
'time_limit_hours': 0,
}
def _migrate_single_profile():
os.makedirs(app.instance_path, exist_ok=True)
if not os.path.exists(PEER_PROFILES_FILE) and os.path.exists(PEER_PROFILE_FILE):
try:
with open(PEER_PROFILE_FILE, 'r') as f:
single = json.load(f)
except Exception:
single = {}
base = dict(_DEF_PROFILE); base.update({k: single.get(k, base[k]) for k in base.keys()})
data = {"active": "Default", "profiles": {"Default": base}}
with open(PEER_PROFILES_FILE, 'w') as f:
json.dump(data, f, indent=2)
# try: os.remove(PEER_PROFILE_FILE)
# except Exception: pass
def _load_profiles():
os.makedirs(app.instance_path, exist_ok=True)
_migrate_single_profile()
try:
with open(PEER_PROFILES_FILE, 'r') as f:
d = json.load(f)
except Exception:
d = {}
if 'profiles' not in d or not isinstance(d['profiles'], dict):
d['profiles'] = {}
d.setdefault('active', 'Default')
if 'Default' not in d['profiles']:
d['profiles']['Default'] = dict(_DEF_PROFILE)
return d
def _save_profiles(d):
os.makedirs(app.instance_path, exist_ok=True)
with open(PEER_PROFILES_FILE, 'w') as f:
json.dump(d, f, indent=2)
def _get_profile(name: str | None):
d = _load_profiles()
name = (name or d.get('active') or 'Default')
prof = dict(_DEF_PROFILE)
prof.update(d['profiles'].get(name, {}))
return prof
def _set_profile(name: str, data: dict):
d = _load_profiles()
base = dict(_DEF_PROFILE)
for k in base.keys():
if k in data:
base[k] = data[k]
d['profiles'][name] = base
_save_profiles(d)
def _set_active_profile(name: str):
d = _load_profiles()
if name in d['profiles']:
d['active'] = name
_save_profiles(d)
def _panel_default_dns():
return (_get_profile(None).get('dns') or '1.1.1.1, 1.0.0.1').strip()
# ___ API (multi)___
@app.route('/api/peer_profile', methods=['DELETE'])
@login_required
def delete_apipeer_profile():
name = (request.args.get('name') or '').strip()
if not name:
return jsonify(error="name_required"), 400
d = _load_profiles()
if name == 'Default':
return jsonify(error="cannot_delete_default"), 400
if name not in d['profiles']:
return jsonify(error="not_found"), 404
if d.get('active') == name:
d['active'] = 'Default'
d['profiles'].pop(name, None)
_save_profiles(d)
return jsonify(ok=True, profiles=sorted(d['profiles'].keys()), active=d['active'])
@app.get('/api/peer_profiles')
@login_required
def list_apipeer_profiles():
d = _load_profiles()
names = sorted((d.get('profiles') or {}).keys())
return jsonify(profiles=names, active=d.get('active') or 'Default')
@app.route('/api/peer_profile/rename', methods=['POST'])
@login_required
def rename_apipeer_profile():
data = request.get_json(force=True, silent=True) or {}
old = (data.get('old') or '').strip()
new = (data.get('new') or '').strip()
if not old or not new:
return jsonify(error="old_and_new_required"), 400
d = _load_profiles()
if old not in d['profiles']:
return jsonify(error="not_found"), 404
if new in d['profiles']:
return jsonify(error="exists"), 409
d['profiles'][new] = d['profiles'].pop(old)
if d.get('active') == old:
d['active'] = new
_save_profiles(d)
return jsonify(ok=True, active=d['active'])
@app.route('/api/peer_profile', methods=['GET'])
@login_required
def get_apipeer_profile():
name = (request.args.get('name') or '').strip() or None
return jsonify(_get_profile(name))
@app.route('/api/peer_profile', methods=['POST'])
@login_required
def save_apipeer_profile():
data = request.get_json(force=True, silent=True) or {}
name = (data.get('name') or 'Default').strip() or 'Default'
payload = {k: v for k, v in data.items() if k != 'name'}
_set_profile(name, payload)
return jsonify(ok=True, saved_name=name, saved=_get_profile(name))
@app.route('/api/peer_profile/activate', methods=['POST'])
@login_required
def activate_apipeer_profile():
data = request.get_json(force=True, silent=True) or {}
name = (data.get('name') or 'Default').strip() or 'Default'
_set_active_profile(name)
return jsonify(ok=True, active=name)
def _effective_dns(peer):
return (peer.dns or getattr(peer.iface, 'dns', None) or _panel_default_dns())
#---------------
# logging
#_______________
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
os.makedirs(app.instance_path, exist_ok=True)
APP_LOG_FILE = os.path.join(app.instance_path, 'app.log')
if not app.logger.handlers:
handler = RotatingFileHandler(APP_LOG_FILE, maxBytes=1_000_000, backupCount=3, encoding='utf-8')
handler.setLevel(logging.INFO)
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
handler.setFormatter(fmt)
app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)
app.config["PROPAGATE_EXCEPTIONS"] = True
@app.errorhandler(Exception)
def _unhandled(e):
if isinstance(e, HTTPException):
return e
app.logger.exception("Unhandled exception")
return "Internal Server Error", 500
_formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s')
_file = RotatingFileHandler(APP_LOG_FILE, maxBytes=2_000_000, backupCount=5, encoding='utf-8')
_file.setLevel(LOG_LEVEL)
_file.setFormatter(_formatter)
root = logging.getLogger()
root.setLevel(LOG_LEVEL)
if not any(isinstance(h, RotatingFileHandler) for h in root.handlers):
root.addHandler(_file)
if not any(isinstance(h, logging.StreamHandler) for h in root.handlers):
sh = logging.StreamHandler(sys.stderr)
sh.setFormatter(_formatter)
sh.setLevel(LOG_LEVEL)
root.addHandler(sh)
for name in ('werkzeug', 'gunicorn.error', 'gunicorn.access', 'urllib3', 'requests', 'sqlalchemy.engine'):
lg = logging.getLogger(name)
lg.setLevel(LOG_LEVEL)
lg.propagate = True
#-----------------
# Secure cookie
#__________________
logging.captureWarnings(True)
app.config["WTF_CSRF_CHECK_DEFAULT"] = False
csrf = CSRFProtect(app)
@app.before_request
def _csrf_protect_ui():
if request.method in ("POST", "PUT", "PATCH", "DELETE"):
if request.path.startswith("/api/"):
return
csrf.protect()
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_SECURE=False,
)
@app.context_processor
def inject_nav_flags():
v = set(current_app.view_functions.keys())
return {'HAS_NODES': 'nodes' in v, 'HAS_SETTINGS': 'settings_page' in v}
#--------------------------
# Allow Plain Http
#_________________________
@app.before_request
def _dev_cookie():
current_app.config['SESSION_COOKIE_SECURE'] = bool(_is_https())
@app.after_request
def _log_request(resp):
try:
app.logger.info('HTTP %s %s %s', request.method, request.path, resp.status_code)
except Exception:
pass
return resp
@app.after_request
def cache_headers(resp):
if request.path.startswith('/static/') and (request.path.endswith('.css') or request.path.endswith('.js')):
resp.headers['Cache-Control'] = 'no-cache, must-revalidate'
return resp
#------------------
# CSRF Injection
#__________________
@app.after_request
def inject_sec_headers(resp):
secure_now = _is_https()
try:
secure_flag = bool(secure_now)
resp.set_cookie(
"csrf_token",
generate_csrf(),
samesite="Lax",
secure=secure_flag,
httponly=False,
)
except Exception as e:
app.logger.debug("inject_sec_headers: failed to set csrf_token cookie: %s", e)
resp.headers.setdefault('X-Frame-Options', 'DENY')
try:
s = _load_panel_settings()
if s.get('hsts') and secure_now:
resp.headers.setdefault(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
)
except Exception:
pass
try:
if _is_https():
ct = (resp.headers.get("Content-Type") or "").lower()
if "text/html" in ct:
add = "upgrade-insecure-requests; block-all-mixed-content"
cur = (resp.headers.get("Content-Security-Policy") or "").strip()
if cur:
if "upgrade-insecure-requests" not in cur:
resp.headers["Content-Security-Policy"] = cur.rstrip("; ") + "; " + add
else:
resp.headers["Content-Security-Policy"] = add
except Exception:
pass
return resp
@app.before_request
def _https_redirect():
try:
s = _load_panel_settings() or {}
if not s.get("force_https_redirect"):
return
xf_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip().lower()
if request.is_secure or xf_proto == "https":
return
if not bool(getattr(app, "_tls_enabled_effective", False)):
return
if (request.path or "").startswith("/api/"):
return
host = (s.get("domain") or "").strip() or request.host.split(":", 1)[0]
https_port = s.get("https_port")
try:
https_port = int(https_port) if https_port else 443
except Exception:
https_port = 443
netloc = f"{host}:{https_port}" if https_port and https_port != 443 else host
full = request.full_path
if full.endswith("?"):
full = full[:-1]
return redirect(f"https://{netloc}{full}", code=301)
except Exception as e:
current_app.logger.warning("HTTPS redirect skipped: %s", e)
return
#@app.before_request
#def maybe_force_https():
# Force redirect only when: toggle ON, certs loaded, and current request is NOT secure
# try:
# s = _load_panel_settings()
# except Exception:
# s = {}
# if s.get('force_https_redirect') and getattr(app, '_tls_enabled_effective', False) and not request.is_secure:
# Preserve host/path/query and switch to https
# url = request.url.replace('http://', 'https://', 1)
# return redirect(url, code=301)
@app.after_request
def _maybe_hsts(resp):
try:
s = _load_panel_settings()
if s.get('hsts') and request.is_secure:
resp.headers.setdefault('Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload')
except Exception:
pass
return resp
@app.after_request
def security_headers(resp):
p = (request.path or '').lower()
resp.headers['X-Frame-Options'] = 'DENY'
if p.startswith('/preview/'):
resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
resp.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"style-src-elem 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"font-src 'self' data:; "
"connect-src 'self'; "
"object-src 'none'; base-uri 'none'; "
"form-action 'none'; "
"frame-ancestors 'self'"
)
if (
p.endswith(('.woff2','.woff','.ttf','.otf')) or
p.startswith('/static/fonts/') or
p.startswith('/static/vendor/fa/webfonts/')
):
resp.headers.setdefault('Access-Control-Allow-Origin', '*')
if p.endswith('.woff2'): resp.headers.setdefault('Content-Type','font/woff2')
elif p.endswith('.woff'): resp.headers.setdefault('Content-Type','font/woff')
elif p.endswith('.ttf'): resp.headers.setdefault('Content-Type','font/ttf')
elif p.endswith('.otf'): resp.headers.setdefault('Content-Type','font/otf')
return resp
def _http_url(u: str) -> bool:
try:
p = urlparse((u or '').strip())
return p.scheme in ('http', 'https') and bool(p.netloc)
except Exception:
return False
def _safe_url(target: str) -> bool:
ref = urlparse(request.host_url)
test = urlparse(urljoin(request.host_url, target or ''))
return (test.scheme in ('http','https')) and (ref.netloc == test.netloc)
def _norm_base_url(u: str) -> str:
u = (u or '').strip()
return u[:-1] if u.endswith('/') else u
def _validate_node_base_url(base_url: str) -> tuple[bool, str]:
"""Validate a node base_url to reduce SSRF risk.
Rules:
- must be a valid URL
- HTTPS only
- must not resolve to loopback/private/link-local/reserved/multicast/unspecified
"""
base_url = (base_url or '').strip().rstrip('/')
if not _http_url(base_url):
return False, 'invalid base_url'
try:
p = urlparse(base_url)
if (p.scheme or '').lower() != 'https':
return False, 'nodes must use https'
host = (p.hostname or '').strip()
if not host:
return False, 'invalid host'
if host in ('localhost', '127.0.0.1', '::1'):
return False, 'loopback hosts are not allowed'
infos = []
try:
infos = socket.getaddrinfo(host, p.port or 443, type=socket.SOCK_STREAM)
except Exception:
infos = []
for info in infos:
addr = info[4][0]
try:
ip = ipaddress.ip_address(addr)
except Exception:
continue
if (
ip.is_loopback or ip.is_private or ip.is_link_local or ip.is_multicast or
ip.is_reserved or ip.is_unspecified
):
return False, f'host resolves to non-public IP ({ip})'
if host == '169.254.169.254':
return False, 'metadata IP is not allowed'
except Exception:
return False, 'invalid base_url'
return True, ''
#--------------------------------
# Fernet encryption at rest
#_______________________________
_fernet = None
try:
from cryptography.fernet import Fernet
key = os.environ.get('FERNET_KEY')
if key:
_fernet = Fernet(key)
except Exception:
_fernet = None
FERNET_KEY = os.environ.get('FERNET_KEY')
if not FERNET_KEY:
raise RuntimeError("FERNET_KEY is not set. Generate one and export it before starting the app.")
fernet = Fernet(FERNET_KEY.encode())
def _probably_encrypt(s: str) -> str:
if _fernet and s:
return _fernet.encrypt(s.encode()).decode()
return s
def _probably_decrypt(s: str) -> str:
if _fernet and s:
try:
return _fernet.decrypt(s.encode()).decode()
except Exception:
return s
return s
def _read_api_key(n):
k = (n.api_key or '').strip()
if k.startswith('enc$') and _FERNET:
try:
return _FERNET.decrypt(k[4:].encode()).decode()
except Exception:
current_app.logger.warning("Failed to decrypt node api_key (id=%s)", n.id)
return ''
return k
def _read_api_key(node) -> str:
return _probably_decrypt(node.api_key or '')
#-------------------------------------------------
# Time helpers (no timezones; epoch)
#_________________________________________________
TELEGRAM_ADMINS_FILE = os.path.join(app.instance_path, 'telegram_admins.json')
TELEGRAM_SETTINGS_FILE = os.path.join(app.instance_path, 'telegram_settings.json')
TELEGRAM_LOG_FILE = os.path.join(app.instance_path, 'telegram.log')
TELEGRAM_ADMIN_LOG_FILE = os.path.join(app.instance_path, 'telegram_admin_log.jsonl')
ADMIN_LOG_FILE = os.path.join(app.instance_path, 'admin_logs.jsonl')
TELEGRAM_HB_FILE = os.path.join(app.instance_path, 'telegram_heartbeat.json')
LOGS_SETTINGS_FILE = Path(app.instance_path) / "logs_settings.json"
LOGS_SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
LOGS_SETTINGS_FILE = Path(app.instance_path) / 'logs_settings.json'
#------------------------------
# Admin logs, IP, Whose
#______________________________
def _read_admin_logs(max_lines=2000):
rows = []
try:
with open(ADMIN_LOG_FILE, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rows.append(json.loads(line))
except Exception:
pass
except FileNotFoundError:
pass
return rows[-max_lines:]
def _whoami_logs() -> tuple[str, str]:
try:
from flask_login import current_user as cu
if cu and getattr(cu, "is_authenticated", False):
aid = str(getattr(cu, "id", "") or getattr(cu, "username", "") or "")
uname = getattr(cu, "username", None) or ""
return aid, uname
except Exception:
pass
try:
from flask import session
aid = str(session.get("user_id") or session.get("username") or "")
uname = str(session.get("username") or "")
return aid, uname
except Exception:
return "", ""
#----------------------------------
# Accept several common formats
#__________________________________
def _app_log_line(s: str):
s = (s or '').rstrip('\n')
m = re.match(r'^(\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d(?:,\d{3})?)\s+([A-Z]+)\s+([^:]+):\s*(.*)$', s)
if m:
ts, level, _name, msg = m.groups()
else:
m = re.match(r'^(\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d(?:,\d{3})?)\s+([A-Z]+)\s+(.*)$', s)
if m:
ts, level, msg = m.group(1), m.group(2), m.group(3)
else:
m = re.search(r'\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b', s)
level = (m.group(1) if m else 'INFO').upper()
ts = ''
msg = s
if ts:
ts = ts.replace(' ', 'T').split(',')[0] + 'Z'
return {'ts': ts, 'level': level.lower(), 'msg': msg}
def _load_log_settings():
try:
with open(LOGS_SETTINGS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def _save_log_settings(data: dict):
LOGS_SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(LOGS_SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def _src_defaults(d=None):
d = d or {}
return {
"max_mb": int(d.get("max_mb") or 0),
"max_age_days": int(d.get("max_age_days") or 0),
"daily_clear": bool(d.get("daily_clear") or False),
"last_daily_utc": d.get("last_daily_utc") or "",
"last_cleared_utc": d.get("last_cleared_utc") or "",
}
def _load_retention():
settings = _load_log_settings()
r = settings.get("retention") or {}
return {
"app": _src_defaults(r.get("app")),
"tg_app": _src_defaults(r.get("tg_app")),
"tg_admin": _src_defaults(r.get("tg_admin")),
"iface": _src_defaults(r.get("iface")),
}
def _save_retention(ret: dict):
settings = _load_log_settings()
settings["retention"] = ret
_save_log_settings(settings)
def _last_cleared(persist_key: str | None):
if not persist_key:
return
try:
cur = _load_retention()
group = persist_key.split(":", 1)[0]
if group not in cur:
cur[group] = _src_defaults()
cur[group]["last_cleared_utc"] = datetime.utcnow().isoformat(
timespec="seconds"
) + "Z"
_save_retention(cur)
except Exception:
pass
@app.get("/api/logs/retention")
@login_required
def logs_retention():
return jsonify(retention=_load_retention())
@app.post("/api/logs/retention")
@login_required
def logs_retention_post():
data = request.get_json(silent=True) or {}
incoming = data.get("retention") or {}
cur = _load_retention()
for key in ("app", "tg_app", "tg_admin", "iface"):
v = incoming.get(key)
if isinstance(v, dict):
cur[key]["max_mb"] = int(v.get("max_mb") or 0)
cur[key]["max_age_days"] = int(v.get("max_age_days") or 0)
cur[key]["daily_clear"] = bool(v.get("daily_clear") or False)
_save_retention(cur)
return jsonify(ok=True)
def run_log():
"""
One-shot retention sweep.
Applies retention rules from logs_settings.json to all log sources.
.
"""
try:
cfg = _load_retention()
except Exception:
cfg = {}
def conf(key):
return cfg.get(key) or {}
try:
_may_autoclear(Path(APP_LOG_FILE), conf("app"), persist_key="app")
except Exception:
pass
try:
_may_autoclear(Path(TELEGRAM_LOG_FILE), conf("tg_app"), persist_key="tg_app")
except Exception:
pass
try:
_may_autoclear(Path(TELEGRAM_ADMIN_LOG_FILE), conf("tg_admin"), persist_key="tg_admin")
except Exception:
pass
try:
iface_dir = Path(INSTANCE_DIR) / "iface_logs"
if iface_dir.is_dir():
for p in iface_dir.glob("*.log"):
key = f"iface:{p.stem}"
_may_autoclear(p, conf("iface"), persist_key=key)
except Exception:
pass
_RETENTION_THREAD_STARTED = False
_RETENTION_INTERVAL_SEC = 1 * 60
def _retention_loop():
while True:
try:
run_log()
except Exception as exc:
try:
app.logger.exception("Log retention sweep failed: %s", exc)
except Exception:
pass
time.sleep(_RETENTION_INTERVAL_SEC)
def _start_retention():
"""
Start the background log-retention thread once per process.
"""
global _RETENTION_THREAD_STARTED
if _RETENTION_THREAD_STARTED:
return
_RETENTION_THREAD_STARTED = True
t = threading.Thread(
target=_retention_loop,
name="log-retention",
daemon=True,
)
t.start()
def _may_autoclear(path: Path, rules: dict, persist_key: str | None = None):
"""
Apply retention rules [Truncate] to a single log file.
- max_mb: when file exceeds size
- max_age_days: when file too old
- daily_clear: once per day between 03:00–03:59 UTC
"""
try:
p = Path(path)
if not p.exists():
return
max_mb = int(rules.get("max_mb") or 0)
if max_mb > 0 and p.stat().st_size > (max_mb * 1024 * 1024):
open(p, "w").close()
_last_cleared(persist_key)
return
max_days = int(rules.get("max_age_days") or 0)
if max_days > 0:
import time
age_days = (time.time() - p.stat().st_mtime) / 86400.0
if age_days > max_days:
open(p, "w").close()
_last_cleared(persist_key)
return
if rules.get("daily_clear"):
now = datetime.utcnow()
today = now.strftime("%Y-%m-%d")
last = rules.get("last_daily_utc") or ""
if last != today and 3 <= now.hour < 4:
open(p, "w").close()
if persist_key:
try:
cur = _load_retention()
group = persist_key.split(":", 1)[0]
if group not in cur:
cur[group] = _src_defaults()
cur[group]["last_daily_utc"] = today
cur[group]["last_cleared_utc"] = now.isoformat(timespec="seconds") + "Z"
_save_retention(cur)
except Exception:
pass
else:
_last_cleared(persist_key)
except Exception:
pass
ret = _load_retention()["app"]
_may_autoclear(Path(APP_LOG_FILE), ret, persist_key="app")
def _read_tail(path: str, max_bytes: int = 50000) -> str:
try:
with open(path, 'rb') as f:
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(max(0, size - max_bytes), os.SEEK_SET)
data = f.read().decode('utf-8', errors='replace')
return data
except Exception:
return ""
@app.get('/logs')
@login_required
def logs_page():
return render_template('logs.html')
@app.get('/api/logs/settings')
@login_required
def logs_settings_get():
if LOGS_SETTINGS_FILE.exists():
with open(LOGS_SETTINGS_FILE, 'r') as f:
try:
cfg = json.load(f)
except Exception:
cfg = {}
else:
cfg = {}
cfg.setdefault('enabled', True)
cfg.setdefault('include_debug', False)
cfg.setdefault('persist', True)
cfg.setdefault('telegram_notify', False)
cfg.setdefault('retention_days', 7)
cfg.setdefault('max_file_mb', 10)
cfg.setdefault('rotate_files', 5)
cfg.setdefault('mutes', [])
cfg.setdefault('sources', {'app': True, 'admin': True, 'telegram': True, 'iface': True})
cfg.setdefault('mute_save', False)
cfg.setdefault('keep_last_lines', 0)
return jsonify(cfg)
@app.post('/api/logs/settings')
@login_required
def logs_settings_post():
payload = request.get_json(force=True, silent=True) or {}
LOGS_SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(LOGS_SETTINGS_FILE, 'w') as f:
json.dump(payload, f, indent=2)
_applymute_log()
return jsonify(ok=True)
@app.get('/api/logs/backup')
@login_required
def logs_backup():
source = request.args.get('source','app')
iface = request.args.get('iface','')
files = []
if source == 'app':
files = [Path(app.instance_path) / 'app.log']
elif source == 'admin':
files = [Path(app.instance_path) / 'admin.log']
elif source == 'telegram':
files = [Path(app.instance_path) / 'telegram.log']
elif source == 'iface' and iface:
files = [Path(app.instance_path) / f'iface_{iface}.log']
mem = BytesIO()
with zipfile.ZipFile(mem, 'w', zipfile.ZIP_DEFLATED) as z:
for p in files:
if p.exists():
z.write(p, arcname=p.name)
mem.seek(0)
ts = dt.datetime.utcnow().strftime('%Y%m%d_%H%M%S')
return send_file(mem, mimetype='application/zip',
as_attachment=True, download_name=f'logs_backup_{source}_{ts}.zip')
@app.get('/api/app_status')
@login_required
def app_status():
started = globals().get('APP_START_TS', int(time.time()))
uptime = now_ts() - int(started)
hb = _json_load(TELEGRAM_HB_FILE, {})
last = int(hb.get('ts') or 0)
sec = int(current_app.config.get('TG_HEARTBEAT_SEC', 60) or 60)
bot_online = (now_ts() - last) <= max(120, sec * 2)
return jsonify({
'app': {
'online': True,
'since': isoz(from_ts(started)),
'uptime': uptime
},
'telegram': {
'online': bool(bot_online),
'last_seen': isoz(from_ts(last)) if last else None
}
})
@app.route('/api/app_logs', methods=['GET','DELETE'])
@login_required
def app_logs():
if request.method == 'DELETE':
try:
open(APP_LOG_FILE, 'w').close()
_last_cleared("app")
except Exception:
pass
return jsonify(ok=True)
q = (request.args.get('q') or '').lower().strip()
level = (request.args.get('level') or '').lower().strip()
limit = max(10, min(int(request.args.get('limit') or 500), 2000))
text = _read_tail(APP_LOG_FILE, 200_000)
out = []
for line in text.splitlines():
rec = _app_log_line(line)
if not rec:
continue
if level and rec['level'] != level:
continue
if q and q not in (rec['msg'] or '').lower():
continue
out.append(rec)
return jsonify(logs=out[-limit:])
def _norm_adminlog(entry: dict):
channel = (entry.get("channel") or
("web" if (hasattr(current_app, "login_manager") and
hasattr(sys.modules.get(__name__), "login") and