-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcodec_dashboard.py
More file actions
2631 lines (2342 loc) · 109 KB
/
codec_dashboard.py
File metadata and controls
2631 lines (2342 loc) · 109 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
"""CODEC v1.2 — Phone Dashboard & PWA"""
import os, json, sqlite3, time, logging, secrets, subprocess, hmac, threading, uuid, asyncio
from datetime import datetime, timedelta
log = logging.getLogger("codec_dashboard")
from pathlib import Path
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse as StarletteJSONResponse
import uvicorn
app = FastAPI(title="CODEC Dashboard")
app.add_middleware(CORSMiddleware, allow_origins=["http://localhost:8090", "http://127.0.0.1:8090", "https://codec.lucyvpa.com"], allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], allow_headers=["*"])
class AuthMiddleware(BaseHTTPMiddleware):
"""Combined auth: bearer token (API) + biometric Touch ID sessions (dashboard)."""
# Routes that never require authentication
PUBLIC_ROUTES = {"/", "/chat", "/vibe", "/voice", "/auth", "/health", "/favicon.ico", "/manifest.json"}
PUBLIC_PREFIXES = ("/api/auth/", "/static")
# CSRF-exempt paths (auth endpoints handle their own protection)
CSRF_EXEMPT = {"/api/auth/verify", "/api/auth/pin", "/api/auth/logout",
"/api/auth/totp/setup", "/api/auth/totp/confirm", "/api/auth/totp/verify",
"/api/auth/totp/enable", "/api/auth/keyexchange"}
async def dispatch(self, request, call_next):
from codec_config import DASHBOARD_TOKEN
path = request.url.path
# Always allow public routes
if path in self.PUBLIC_ROUTES:
return await call_next(request)
if any(path.startswith(p) for p in self.PUBLIC_PREFIXES):
return await call_next(request)
# Allow static assets
if path.endswith(('.css', '.js', '.png', '.ico', '.svg', '.woff2', '.woff', '.ttf')):
return await call_next(request)
# ── CSRF check for state-changing requests ──
if request.method in ("POST", "PUT", "DELETE") and path not in self.CSRF_EXEMPT:
csrf_cookie = request.cookies.get("codec_csrf", "")
csrf_header = request.headers.get("x-csrf-token", "")
# Only enforce if auth is enabled (local no-auth mode skips CSRF)
if (DASHBOARD_TOKEN or AUTH_ENABLED) and csrf_cookie:
if not csrf_header or not hmac.compare_digest(csrf_cookie, csrf_header):
return StarletteJSONResponse(
{"error": "CSRF token mismatch. Refresh the page."},
status_code=403
)
# ── Layer 0: No auth configured → allow all ──
if not DASHBOARD_TOKEN and (not AUTH_ENABLED or not _auth_available()):
return await call_next(request)
# ── Layer 1: Token check (API key — works as standalone auth for API) ──
if DASHBOARD_TOKEN and path.startswith("/api/"):
auth = request.headers.get("Authorization", "")
if auth and hmac.compare_digest(auth, f"Bearer {DASHBOARD_TOKEN}"):
return await call_next(request)
token = request.query_params.get("token", "")
if token and hmac.compare_digest(token, DASHBOARD_TOKEN):
return await call_next(request)
# ── Layer 2: Biometric / PIN session check ──
if AUTH_ENABLED and _auth_available():
if _verify_biometric_session(request):
return await call_next(request)
# Biometric failed — reject
cookie_val = request.cookies.get(AUTH_COOKIE_NAME, "<missing>")
log.warning("AUTH REJECTED: path=%s method=%s ip=%s cookie=%s...",
path, request.method, request.client.host if request.client else "?",
cookie_val[:12] if cookie_val else "<empty>")
if path.startswith("/api/") or path.startswith("/ws"):
return StarletteJSONResponse({"error": "Not authenticated"}, status_code=401)
from starlette.responses import RedirectResponse
return RedirectResponse(url="/auth")
# ── Layer 3: No biometric available — token-only mode ──
if DASHBOARD_TOKEN and path.startswith("/api/"):
# Token was already checked above and didn't match
return StarletteJSONResponse(
{"error": "Unauthorized. Set dashboard_token in config.json or pass ?token=YOUR_TOKEN"},
status_code=401
)
return await call_next(request)
class CSPMiddleware(BaseHTTPMiddleware):
"""Add Content-Security-Policy header to all HTML responses."""
CSP = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com; "
"font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; "
"img-src 'self' data: https:; "
"connect-src 'self' ws: wss: http://localhost:* http://127.0.0.1:*; "
"worker-src 'self' blob:"
)
async def dispatch(self, request, call_next):
response = await call_next(request)
content_type = response.headers.get("content-type", "")
if "text/html" in content_type:
response.headers["Content-Security-Policy"] = self.CSP
return response
app.add_middleware(CSPMiddleware)
app.add_middleware(AuthMiddleware)
DB_PATH = os.path.expanduser("~/.q_memory.db")
AUDIT_LOG = os.path.expanduser("~/.codec/audit.log")
CONFIG_PATH = os.path.expanduser("~/.codec/config.json")
TASK_QUEUE = os.path.expanduser("~/.codec/task_queue.txt")
DASHBOARD_DIR = os.path.dirname(os.path.abspath(__file__))
NOTIFICATIONS_PATH = os.path.expanduser("~/.codec/notifications.json")
SCHEDULE_RUNS_LOG = os.path.expanduser("~/.codec/schedule_runs.log")
# ── Notification helpers ──
_notif_lock = threading.Lock()
def _load_notifications():
"""Load notifications from disk, seeding sample data on first access."""
try:
with open(NOTIFICATIONS_PATH) as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
# Seed with sample past notifications so the list isn't empty
samples = [
{
"id": f"notif_{uuid.uuid4().hex[:10]}",
"type": "task_report",
"title": "Daily Morning Briefing",
"body": "Completed successfully. 5 action items identified, market overview compiled, calendar conflicts flagged.",
"status": "success",
"created": "2026-03-29T08:00:00",
"read": True,
"schedule_id": "daily_briefing"
},
{
"id": f"notif_{uuid.uuid4().hex[:10]}",
"type": "task_report",
"title": "Security Scan",
"body": "No vulnerabilities found. All 142 dependencies are up to date, no CVEs detected.",
"status": "success",
"created": "2026-03-29T12:00:00",
"read": True,
"schedule_id": "security_scan"
},
{
"id": f"notif_{uuid.uuid4().hex[:10]}",
"type": "task_report",
"title": "AI News Digest",
"body": "33 stories collected from 5 sources. Top story: new open-weight model benchmarks released.",
"status": "success",
"created": "2026-03-29T18:30:00",
"read": False,
"schedule_id": "ai_news_digest"
},
{
"id": f"notif_{uuid.uuid4().hex[:10]}",
"type": "task_report",
"title": "Weekly Code Review Summary",
"body": "Analyzed 12 PRs across 3 repos. 2 require attention: stale dependency warnings in codec-core and missing tests in dashboard module.",
"status": "success",
"created": "2026-03-28T09:00:00",
"read": True,
"schedule_id": "weekly_code_review"
}
]
_write_notifications(samples)
return samples
def _write_notifications(notifications):
"""Persist notifications list to disk."""
os.makedirs(os.path.dirname(NOTIFICATIONS_PATH), exist_ok=True)
with open(NOTIFICATIONS_PATH, "w") as f:
json.dump(notifications, f, indent=2)
def _save_notification(title, body, status="success", schedule_id=None):
"""Create and persist a new notification, returning its id."""
notif = {
"id": f"notif_{uuid.uuid4().hex[:10]}",
"type": "task_report",
"title": title,
"body": body,
"status": status,
"created": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
"read": False,
"schedule_id": schedule_id
}
with _notif_lock:
notifications = _load_notifications()
notifications.insert(0, notif)
_write_notifications(notifications)
return notif["id"]
def _append_schedule_run_log(schedule_id, title, status, body_preview=""):
"""Append a run record to the schedule runs log."""
os.makedirs(os.path.dirname(SCHEDULE_RUNS_LOG), exist_ok=True)
entry = {
"timestamp": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
"schedule_id": schedule_id,
"title": title,
"status": status,
"body_preview": body_preview[:200]
}
with open(SCHEDULE_RUNS_LOG, "a") as f:
f.write(json.dumps(entry) + "\n")
# ── Biometric (Touch ID) Auth ──
def _load_cfg():
try:
with open(CONFIG_PATH) as f:
return json.load(f)
except Exception:
return {}
_bio_cfg = _load_cfg()
AUTH_ENABLED = _bio_cfg.get("auth_enabled", False)
AUTH_SESSION_HOURS = _bio_cfg.get("auth_session_hours", 24)
AUTH_BINARY = os.path.join(DASHBOARD_DIR, "codec_auth", "codec_auth")
AUTH_PIN_HASH = _bio_cfg.get("auth_pin_hash", "") # SHA-256 of user's PIN
AUTH_COOKIE_NAME = "codec_session"
# Persistent session store — survives PM2 restarts
_SESSION_FILE = os.path.expanduser("~/.codec/.auth_sessions.json")
_auth_sessions = {} # token -> {created: datetime, ip: str, method: str}
_auth_lock = threading.Lock()
_e2e_keys = {} # session_token -> bytes (AES-256 key)
def _load_sessions():
"""Load sessions from disk on startup. Caller must hold _auth_lock (or be at import time)."""
global _auth_sessions
try:
if os.path.isfile(_SESSION_FILE):
with open(_SESSION_FILE) as f:
raw = json.load(f)
now = datetime.now()
for tok, data in raw.items():
created = datetime.fromisoformat(data["created"])
if now - created < timedelta(hours=AUTH_SESSION_HOURS):
_auth_sessions[tok] = {
"created": created,
"ip": data.get("ip", "unknown"),
"method": data.get("method", "unknown"),
}
log.info("Restored %d auth session(s) from disk", len(_auth_sessions))
except Exception as e:
log.warning("Could not load auth sessions: %s", e)
def _save_sessions():
"""Persist current sessions to disk. Caller must hold _auth_lock."""
try:
os.makedirs(os.path.dirname(_SESSION_FILE), exist_ok=True)
raw = {}
for tok, data in _auth_sessions.items():
raw[tok] = {
"created": data["created"].isoformat(),
"ip": data.get("ip", "unknown"),
"method": data.get("method", "unknown"),
}
with open(_SESSION_FILE, "w") as f:
json.dump(raw, f)
os.chmod(_SESSION_FILE, 0o600)
except Exception as e:
log.warning("Could not save auth sessions: %s", e)
_load_sessions()
def _is_auth_compiled():
return os.path.isfile(AUTH_BINARY) and os.access(AUTH_BINARY, os.X_OK)
def _auth_available():
"""Check if any auth method is available (Touch ID binary or PIN configured)."""
return _is_auth_compiled() or bool(AUTH_PIN_HASH)
def _is_totp_enabled():
"""Check if TOTP 2FA is configured and not disabled."""
try:
with open(CONFIG_PATH) as f:
cfg = json.load(f)
return bool(cfg.get("totp_secret")) and not cfg.get("totp_disabled", False)
except Exception:
return False
def _verify_biometric_session(request):
"""Check if the request has a valid auth session cookie."""
if not AUTH_ENABLED or not _auth_available():
return True
token = request.cookies.get(AUTH_COOKIE_NAME)
with _auth_lock:
if not token or token not in _auth_sessions:
return False
session = _auth_sessions[token]
if datetime.now() - session["created"] > timedelta(hours=AUTH_SESSION_HOURS):
del _auth_sessions[token]
_save_sessions()
return False
# If TOTP is configured, require totp_verified flag
if _is_totp_enabled() and not session.get("totp_verified"):
return False
return True
_db_conn = None
def get_db():
global _db_conn
if _db_conn is None:
_db_conn = sqlite3.connect(DB_PATH, check_same_thread=False)
_db_conn.execute("PRAGMA journal_mode=WAL")
_db_conn.execute("PRAGMA busy_timeout=5000")
_db_conn.row_factory = sqlite3.Row
return _db_conn
_NO_CACHE = {"Cache-Control": "no-store, no-cache, must-revalidate", "Pragma": "no-cache"}
# ═══════════════════════════════════════════════════════════════
# BIOMETRIC AUTH ENDPOINTS
# ═══════════════════════════════════════════════════════════════
@app.get("/auth", response_class=HTMLResponse)
async def auth_page():
"""Serve the biometric authentication page."""
auth_path = os.path.join(DASHBOARD_DIR, "codec_auth.html")
if os.path.exists(auth_path):
with open(auth_path) as f:
return HTMLResponse(f.read(), headers=_NO_CACHE)
return HTMLResponse("<h1>Auth page not found</h1>", status_code=500)
@app.get("/api/auth/check")
async def auth_check():
"""Check which auth methods are available (Touch ID and/or PIN)."""
result = {"touchid_available": False, "pin_available": bool(AUTH_PIN_HASH)}
if _is_auth_compiled():
try:
r = subprocess.run([AUTH_BINARY, "--check"], capture_output=True, text=True, timeout=5)
if r.returncode == 0:
data = json.loads(r.stdout)
result["touchid_available"] = data.get("available", False)
result["method"] = data.get("method", "none")
except Exception:
pass
result["available"] = result["touchid_available"] or result["pin_available"]
if not result["available"]:
result["reason"] = "No auth method configured. Compile Touch ID binary or set auth_pin_hash in config.json."
return result
@app.post("/api/auth/verify")
async def auth_verify(request: Request):
"""Trigger Touch ID verification on the Mac."""
if not _is_auth_compiled():
return JSONResponse({"error": "Auth binary not compiled"}, status_code=500)
try:
r = subprocess.run(
[AUTH_BINARY, "--verify"],
capture_output=True, text=True, timeout=65
)
if r.returncode == 0:
result = json.loads(r.stdout)
client_ip = request.client.host if request.client else "unknown"
# Audit log every attempt
try:
os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
with open(AUDIT_LOG, "a") as f:
if result.get("authenticated"):
f.write(f"[{datetime.now().isoformat()}] AUTH_SUCCESS: method={result.get('method')} ip={client_ip}\n")
else:
f.write(f"[{datetime.now().isoformat()}] AUTH_FAILED: error={result.get('error')} ip={client_ip}\n")
except Exception:
pass
if result.get("authenticated"):
token = result.get("token", secrets.token_hex(32))
with _auth_lock:
_auth_sessions[token] = {
"created": datetime.now(),
"ip": client_ip,
"method": result.get("method", "unknown"),
}
_save_sessions()
return {
"authenticated": True,
"method": result.get("method"),
"token": token,
"expires_hours": AUTH_SESSION_HOURS,
}
else:
return {
"authenticated": False,
"error": result.get("error", "Authentication failed"),
}
return JSONResponse({"error": "Auth binary failed"}, status_code=500)
except subprocess.TimeoutExpired:
return JSONResponse({"error": "Authentication timed out"}, status_code=408)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
# PIN brute-force rate limiting: {ip: {"count": int, "locked_until": float}}
_pin_attempts: dict = {}
@app.post("/api/auth/pin")
async def auth_pin(request: Request):
"""Verify a PIN code."""
import hashlib
if not AUTH_PIN_HASH:
return JSONResponse({"error": "PIN authentication not configured"}, status_code=400)
try:
body = await request.json()
pin = str(body.get("pin", ""))
except Exception:
return JSONResponse({"error": "Missing pin field"}, status_code=400)
pin_hash = hashlib.sha256(pin.encode()).hexdigest()
client_ip = request.client.host if request.client else "unknown"
# ── Brute-force protection ──
attempt = _pin_attempts.get(client_ip, {"count": 0, "locked_until": 0.0})
if time.time() < attempt.get("locked_until", 0.0):
remaining = int(attempt["locked_until"] - time.time())
return JSONResponse({"error": f"Too many failed attempts. Locked out for {remaining}s."}, status_code=429)
# Audit log
try:
os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
with open(AUDIT_LOG, "a") as f:
if pin_hash == AUTH_PIN_HASH:
f.write(f"[{datetime.now().isoformat()}] AUTH_SUCCESS: method=pin ip={client_ip}\n")
else:
f.write(f"[{datetime.now().isoformat()}] AUTH_FAILED: method=pin error=wrong_pin ip={client_ip}\n")
except Exception:
pass
if pin_hash == AUTH_PIN_HASH:
# Reset failed attempts on success
_pin_attempts.pop(client_ip, None)
token = secrets.token_hex(32)
with _auth_lock:
_auth_sessions[token] = {
"created": datetime.now(),
"ip": client_ip,
"method": "pin",
}
_save_sessions()
return {
"authenticated": True,
"method": "pin",
"token": token,
"expires_hours": AUTH_SESSION_HOURS,
}
else:
# Track failed attempt with exponential backoff
attempt = _pin_attempts.get(client_ip, {"count": 0, "locked_until": 0.0})
attempt["count"] = attempt.get("count", 0) + 1
if attempt["count"] >= 5:
attempt["locked_until"] = time.time() + 300 # 5-minute lockout
attempt["count"] = 0 # reset counter for next lockout cycle
_pin_attempts[client_ip] = attempt
return {"authenticated": False, "error": "Incorrect PIN"}
@app.post("/api/auth/totp/setup")
async def totp_setup(request: Request):
"""Generate TOTP secret + QR code for authenticator app setup."""
import pyotp, qrcode, io, base64
# Only allow setup if auth is enabled
if not AUTH_ENABLED:
return JSONResponse({"error": "Auth not enabled"}, status_code=400)
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(name="CODEC", issuer_name="CODEC")
# Generate QR code as base64 PNG
img = qrcode.make(uri)
buf = io.BytesIO()
img.save(buf, format="PNG")
qr_b64 = base64.b64encode(buf.getvalue()).decode()
return {"secret": secret, "qr_code": qr_b64, "uri": uri}
@app.post("/api/auth/totp/confirm")
async def totp_confirm(request: Request):
"""Verify TOTP code and save secret to config if valid (first-time setup)."""
import pyotp
body = await request.json()
code = str(body.get("code", ""))
secret = body.get("secret", "")
if not code or not secret:
return JSONResponse({"error": "Missing code or secret"}, status_code=400)
totp = pyotp.TOTP(secret)
if totp.verify(code, valid_window=1):
# Save secret to config
try:
cfg_data = {}
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH) as f:
cfg_data = json.load(f)
cfg_data["totp_secret"] = secret
cfg_data.pop("totp_disabled", None)
with open(CONFIG_PATH, "w") as f:
json.dump(cfg_data, f, indent=2)
except Exception as e:
return JSONResponse({"error": f"Failed to save config: {e}"}, status_code=500)
with open(AUDIT_LOG, "a") as f:
f.write(f"[{datetime.now().isoformat()}] TOTP_SETUP: 2FA enabled\n")
return {"verified": True, "enabled": True, "message": "2FA enabled successfully"}
return {"verified": False, "error": "Invalid code. Try again."}
@app.post("/api/auth/totp/verify")
async def totp_verify(request: Request):
"""Verify TOTP code during login (after Touch ID/PIN)."""
import pyotp
body = await request.json()
code = str(body.get("code", ""))
pending_token = body.get("token", "")
if not code or not pending_token:
return JSONResponse({"error": "Missing code or token"}, status_code=400)
# Load secret from config
totp_secret = ""
try:
with open(CONFIG_PATH) as f:
totp_secret = json.load(f).get("totp_secret", "")
except Exception:
pass
if not totp_secret:
return JSONResponse({"error": "TOTP not configured"}, status_code=400)
totp = pyotp.TOTP(totp_secret)
client_ip = request.client.host if request.client else "unknown"
if totp.verify(code, valid_window=1):
# Promote pending token to a real session
with _auth_lock:
if pending_token in _auth_sessions:
_auth_sessions[pending_token]["totp_verified"] = True
_save_sessions()
with open(AUDIT_LOG, "a") as f:
f.write(f"[{datetime.now().isoformat()}] TOTP_SUCCESS: ip={client_ip}\n")
return {"verified": True, "token": pending_token}
with open(AUDIT_LOG, "a") as f:
f.write(f"[{datetime.now().isoformat()}] TOTP_FAILED: ip={client_ip}\n")
return {"verified": False, "error": "Invalid code"}
@app.post("/api/auth/totp/disable")
async def totp_disable(request: Request):
"""Disable TOTP 2FA — requires authenticated session + valid TOTP code."""
if not _verify_biometric_session(request):
return JSONResponse({"error": "Authentication required"}, status_code=401)
# Require current TOTP code to disable
import pyotp
try:
body = await request.json()
code = str(body.get("code", ""))
except Exception:
return JSONResponse({"error": "Missing TOTP code"}, status_code=400)
if not code:
return JSONResponse({"error": "Enter your authenticator code to disable 2FA"}, status_code=400)
totp_secret = ""
try:
with open(CONFIG_PATH) as f:
totp_secret = json.load(f).get("totp_secret", "")
except Exception:
pass
if not totp_secret:
return {"disabled": True} # already disabled
totp = pyotp.TOTP(totp_secret)
if not totp.verify(code, valid_window=1):
return JSONResponse({"error": "Invalid code"}, status_code=400)
# Keep the secret but mark TOTP as disabled (allows re-enable without new QR scan)
try:
cfg_data = {}
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH) as f:
cfg_data = json.load(f)
cfg_data["totp_disabled"] = True
with open(CONFIG_PATH, "w") as f:
json.dump(cfg_data, f, indent=2)
except Exception as e:
return JSONResponse({"error": f"Failed to update config: {e}"}, status_code=500)
# Clear totp_verified from all active sessions
with _auth_lock:
for token, session in _auth_sessions.items():
session.pop("totp_verified", None)
_save_sessions()
client_ip = request.client.host if request.client else "unknown"
with open(AUDIT_LOG, "a") as f:
f.write(f"[{datetime.now().isoformat()}] TOTP_DISABLED: 2FA disabled by ip={client_ip}\n")
return {"disabled": True}
@app.post("/api/auth/totp/enable")
async def totp_enable(request: Request):
"""Re-enable TOTP using existing secret."""
if not _verify_biometric_session(request):
return JSONResponse({"error": "Auth required"}, status_code=401)
import pyotp
body = await request.json()
code = str(body.get("code", ""))
if not code:
return JSONResponse({"error": "Enter your authenticator code"}, status_code=400)
try:
with open(CONFIG_PATH) as f:
cfg = json.load(f)
except Exception:
cfg = {}
secret = cfg.get("totp_secret", "")
if not secret:
return JSONResponse({"error": "No TOTP secret found — use Setup 2FA first"}, status_code=400)
totp = pyotp.TOTP(secret)
if not totp.verify(code, valid_window=1):
return JSONResponse({"error": "Invalid code"}, status_code=400)
cfg.pop("totp_disabled", None)
with open(CONFIG_PATH, "w") as f:
json.dump(cfg, f, indent=2)
return {"enabled": True}
@app.post("/api/auth/logout")
async def auth_logout(request: Request):
"""Invalidate the current biometric session."""
token = request.cookies.get(AUTH_COOKIE_NAME)
with _auth_lock:
if token and token in _auth_sessions:
del _auth_sessions[token]
_save_sessions()
_e2e_keys.pop(token, None)
return {"logged_out": True}
@app.get("/api/auth/status")
async def auth_status(request: Request):
"""Check if current session is valid."""
valid = _verify_biometric_session(request)
# Check if a TOTP secret exists (even if disabled)
totp_secret_exists = False
try:
with open(CONFIG_PATH) as f:
cfg = json.load(f)
totp_secret_exists = bool(cfg.get("totp_secret"))
except Exception:
pass
return {
"authenticated": valid,
"auth_enabled": AUTH_ENABLED,
"touchid_compiled": _is_auth_compiled(),
"pin_configured": bool(AUTH_PIN_HASH),
"totp_enabled": _is_totp_enabled(),
"totp_secret_exists": totp_secret_exists,
}
# ═══════════════════════════════════════════════════════════════
# E2E ENCRYPTION — ECDH key exchange + AES-256-GCM middleware
# ═══════════════════════════════════════════════════════════════
@app.post("/api/auth/keyexchange")
async def e2e_keyexchange(request: Request):
"""ECDH P-256 key exchange — derives shared AES-256-GCM key for E2E encryption."""
try:
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, serialization
except ImportError:
return JSONResponse({"error": "cryptography library not available"}, status_code=500)
body = await request.json()
client_pub_b64 = body.get("pub")
if not client_pub_b64:
return JSONResponse({"error": "missing pub"}, status_code=400)
import base64
client_pub_raw = base64.b64decode(client_pub_b64)
client_pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), client_pub_raw)
server_key = ec.generate_private_key(ec.SECP256R1())
shared = server_key.exchange(ec.ECDH(), client_pub)
aes_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b"codec-e2e").derive(shared)
server_pub_raw = server_key.public_key().public_bytes(
serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint
)
token = request.cookies.get(AUTH_COOKIE_NAME, "")
if token:
_e2e_keys[token] = aes_key
return {"pub": base64.b64encode(server_pub_raw).decode()}
class E2EMiddleware(BaseHTTPMiddleware):
"""Transparent AES-256-GCM encryption/decryption for requests with X-E2E: 1 header."""
async def dispatch(self, request, call_next):
if request.headers.get("x-e2e") != "1":
return await call_next(request)
token = request.cookies.get(AUTH_COOKIE_NAME, "")
aes_key = _e2e_keys.get(token) if token else None
if not aes_key:
return await call_next(request)
try:
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
except ImportError:
return await call_next(request)
# Decrypt request body if present
if request.method in ("POST", "PUT", "DELETE"):
raw = await request.body()
if raw:
try:
envelope = json.loads(raw)
if "iv" in envelope and "ct" in envelope:
iv = base64.b64decode(envelope["iv"])
ct = base64.b64decode(envelope["ct"])
plaintext = AESGCM(aes_key).decrypt(iv, ct, None)
# Replace request body with decrypted content
request._body = plaintext
except Exception:
pass # Not E2E-encrypted or malformed — pass through
response = await call_next(request)
# Encrypt response body
if response.headers.get("content-type", "").startswith("application/json"):
body_parts = []
async for chunk in response.body_iterator:
body_parts.append(chunk if isinstance(chunk, bytes) else chunk.encode())
resp_body = b"".join(body_parts)
iv = os.urandom(12)
ct = AESGCM(aes_key).encrypt(iv, resp_body, None)
enc = json.dumps({"iv": base64.b64encode(iv).decode(), "ct": base64.b64encode(ct).decode()})
return StarletteJSONResponse(
content=json.loads(enc),
status_code=response.status_code,
headers={"x-e2e": "1"}
)
return response
app.add_middleware(E2EMiddleware)
# ═══════════════════════════════════════════════════════════════
# DASHBOARD ROUTES
# ═══════════════════════════════════════════════════════════════
@app.get("/", response_class=HTMLResponse)
async def index():
html_path = os.path.join(DASHBOARD_DIR, "codec_dashboard.html")
with open(html_path) as f:
return HTMLResponse(f.read(), headers=_NO_CACHE)
@app.get("/manifest.json")
async def manifest():
return JSONResponse({
"name": "CODEC",
"short_name": "CODEC",
"description": "CODEC — Your Open-Source Intelligent Command Layer",
"start_url": "/",
"display": "standalone",
"background_color": "#0a0a0a",
"theme_color": "#E8711A",
"icons": [
{"src": "https://i.imgur.com/RbrQ7Bt.png", "sizes": "280x280", "type": "image/png"}
]
})
@app.get("/api/status")
async def status():
"""Check if CODEC is running and return config"""
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception as e:
log.warning(f"Non-critical error: {e}")
# Check if CODEC process is alive
import subprocess
try:
r = subprocess.run(["pgrep", "-f", "codec.py"], capture_output=True, text=True, timeout=3)
alive = bool(r.stdout.strip())
except Exception as e:
log.warning(f"Non-critical error: {e}")
alive = False
return {
"alive": alive,
"config": {
"llm_provider": config.get("llm_provider", "unknown"),
"llm_model": config.get("llm_model", "unknown"),
"tts_engine": config.get("tts_engine", "unknown"),
"tts_voice": config.get("tts_voice", "unknown"),
"key_toggle": config.get("key_toggle", "f13"),
"key_voice": config.get("key_voice", "f18"),
"key_text": config.get("key_text", "f16"),
"wake_word_enabled": config.get("wake_word_enabled", False),
"streaming": config.get("streaming", True),
}
}
def _mask_sensitive(value: str) -> str:
"""Mask sensitive field values, showing only last 4 characters."""
if not value or not isinstance(value, str):
return ""
if len(value) <= 4:
return "****"
return "*" * (len(value) - 4) + value[-4:]
# Fields that contain secrets and must be masked in GET responses
_SENSITIVE_FIELDS = {"llm_api_key", "dashboard_token", "auth_pin_hash"}
# Validation rules: field -> (type, required, extra_checks)
# extra_checks is a callable returning (ok, error_msg)
_VALIDATION_RULES = {
"agent_name": (str, True, lambda v: (len(v.strip()) > 0, "agent_name cannot be empty")),
"llm_provider": (str, True, lambda v: (len(v.strip()) > 0, "llm_provider cannot be empty")),
"llm_model": (str, False, None),
"llm_base_url": (str, False, lambda v: (v == "" or v.startswith("http"), "llm_base_url must be a valid URL")),
"llm_api_key": (str, False, None),
"streaming": (bool, False, None),
"vision_base_url": (str, False, lambda v: (v == "" or v.startswith("http"), "vision_base_url must be a valid URL")),
"vision_model": (str, False, None),
"tts_engine": (str, False, None),
"tts_url": (str, False, lambda v: (v == "" or v.startswith("http"), "tts_url must be a valid URL")),
"tts_model": (str, False, None),
"tts_voice": (str, False, None),
"stt_engine": (str, False, None),
"stt_url": (str, False, lambda v: (v == "" or v.startswith("http"), "stt_url must be a valid URL")),
"key_toggle": (str, True, lambda v: (len(v.strip()) > 0, "key_toggle cannot be empty")),
"key_voice": (str, True, lambda v: (len(v.strip()) > 0, "key_voice cannot be empty")),
"key_text": (str, True, lambda v: (len(v.strip()) > 0, "key_text cannot be empty")),
"wake_word_enabled": (bool, False, None),
"wake_phrases": (list, False, None),
"wake_energy": ((int, float), False, lambda v: (v >= 0, "wake_energy cannot be negative")),
"auth_enabled": (bool, False, None),
"auth_session_hours": ((int, float), False, lambda v: (v > 0, "auth_session_hours must be positive")),
"dashboard_token": (str, False, None),
}
def _validate_config_updates(flat: dict) -> list:
"""Validate flattened config values. Returns list of error strings."""
errors = []
for key, value in flat.items():
rule = _VALIDATION_RULES.get(key)
if not rule:
continue # allow unknown keys through (forward compat)
expected_type, required, check_fn = rule
# Skip masked sensitive values (client didn't change them)
if key in _SENSITIVE_FIELDS and isinstance(value, str) and value.startswith("*"):
continue
if not isinstance(value, expected_type):
errors.append(f"{key}: expected {expected_type.__name__ if isinstance(expected_type, type) else 'number'}, got {type(value).__name__}")
continue
if check_fn:
ok, msg = check_fn(value)
if not ok:
errors.append(msg)
return errors
@app.get("/api/config")
async def get_config():
"""Return full editable config for Settings UI (sensitive fields masked)."""
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception:
pass
# Group into sections for the UI
result = {
"llm": {
"llm_provider": config.get("llm_provider", "mlx"),
"llm_model": config.get("llm_model", ""),
"llm_base_url": config.get("llm_base_url", "http://localhost:8081/v1"),
"llm_api_key": config.get("llm_api_key", ""),
"streaming": config.get("streaming", True),
},
"vision": {
"vision_base_url": config.get("vision_base_url", "http://localhost:8082/v1"),
"vision_model": config.get("vision_model", ""),
},
"tts": {
"tts_engine": config.get("tts_engine", "kokoro"),
"tts_url": config.get("tts_url", "http://localhost:8085/v1/audio/speech"),
"tts_model": config.get("tts_model", ""),
"tts_voice": config.get("tts_voice", "am_adam"),
},
"stt": {
"stt_engine": config.get("stt_engine", "whisper_http"),
"stt_url": config.get("stt_url", "http://localhost:8084/v1/audio/transcriptions"),
},
"keys": {
"key_toggle": config.get("key_toggle", "f13"),
"key_voice": config.get("key_voice", "f18"),
"key_text": config.get("key_text", "f16"),
},
"wake": {
"wake_word_enabled": config.get("wake_word_enabled", True),
"wake_phrases": config.get("wake_phrases", []),
"wake_energy": config.get("wake_energy", 200),
},
"auth": {
"auth_enabled": config.get("auth_enabled", False),
"auth_session_hours": config.get("auth_session_hours", 24),
"dashboard_token": config.get("dashboard_token", ""),
},
"identity": {
"agent_name": config.get("agent_name", "C"),
},
}
# Mask sensitive fields before sending to the client
for section in result.values():
if isinstance(section, dict):
for key in section:
if key in _SENSITIVE_FIELDS:
section[key] = _mask_sensitive(section[key])
return result
@app.put("/api/config")
async def update_config(request: Request):
"""Update config.json from Settings UI with input validation."""
try:
updates = await request.json()
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception:
pass
# Flatten sections for validation and merge
flat = {}
for section_vals in updates.values():
if isinstance(section_vals, dict):
for k, v in section_vals.items():
flat[k] = v
# Validate all incoming values
errors = _validate_config_updates(flat)
if errors:
return JSONResponse({"error": "Validation failed", "details": errors}, status_code=422)
# Merge validated values, skipping masked sensitive fields
changed_keys = []
for k, v in flat.items():
# If a sensitive field is still masked, the user did not change it — skip
if k in _SENSITIVE_FIELDS and isinstance(v, str) and v.startswith("*"):
continue
config[k] = v
changed_keys.append(k)
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent=2)
return {
"saved": True,
"message": f"Configuration saved successfully ({len(changed_keys)} field(s) updated).",
"updated_fields": changed_keys,
}
except json.JSONDecodeError:
return JSONResponse({"error": "Invalid JSON in request body"}, status_code=400)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/history")
async def history(limit: int = 50):
"""Get recent task history"""
try:
c = get_db()
rows = c.execute(
"SELECT id, timestamp, task, app, response FROM sessions ORDER BY id DESC LIMIT ?",
(limit,)
).fetchall()
return [{"id": r[0], "timestamp": r[1], "task": r[2], "app": r[3], "response": r[4]} for r in rows]
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/conversations")
async def conversations(limit: int = 100):
"""Get recent conversations"""
try:
c = get_db()
rows = c.execute(
"SELECT id, session_id, timestamp, role, content FROM conversations ORDER BY id DESC LIMIT ?",
(limit,)
).fetchall()
return [{"id": r[0], "session_id": r[1], "timestamp": r[2], "role": r[3], "content": r[4]} for r in rows]