aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/src/meshbay_node/ui/app.py
blob: 28654dfb35dbe539a2dabe3bc3fb8fc8aa71f5dc (plain) (blame)
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
"""
MeshBay Node — local administration web UI (localhost:18000).

FastAPI app providing:
  - Dashboard: node status, connected peers, group overview
  - Groups: file listing, shared directory info
  - Peers: connected WebRTC/QUIC clients
  - Audit log: IP + action log for legal compliance
  - API endpoints for all data (JSON)

Served only on 127.0.0.1 — not exposed to the network.
Gated by a per-run session token (11.5.3) — printed at daemon startup.
"""

import base64
import json
import logging
import time
from html import escape
from pathlib import Path

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query
from fastapi.responses import HTMLResponse, JSONResponse

from meshbay_node import __version__
from meshbay_common.crypto import generate_gek, wrap_gek_aes
from meshbay_common.join import ROLE_MEMBER, ROLE_OPERATOR

log = logging.getLogger(__name__)


def create_ui_app(state: dict) -> FastAPI:
    app = FastAPI(
        title="MeshBay Node Admin",
        version=__version__,
        docs_url=None,
        redoc_url=None,
    )

    @app.middleware("http")
    async def _require_session_token(request, call_next):
        """
        Gate the admin UI behind a per-run token (11.5.3).

        "localhost only" is weaker than it sounds: any process on the machine can
        reach it, and a page in the operator's browser can reach it too via DNS
        rebinding. Since this API can re-initialise a group's GEK and read the
        audit log, an unauthenticated loopback service is a privilege boundary
        waiting to be crossed. The token is printed at startup and accepted as
        ?t= or the X-MeshBay-Token header.
        """
        from fastapi.responses import PlainTextResponse

        token = state.get("ui_token")
        if token:
            supplied = (request.query_params.get("t")
                        or request.headers.get("X-MeshBay-Token"))
            if supplied != token:
                return PlainTextResponse("Forbidden", status_code=403)
        return await call_next(request)

    @app.middleware("http")
    async def _security_headers(request, call_next):
        """
        Defence in depth behind the escaping fixes for H2. This UI is unauthenticated
        on loopback, so script execution here equals full control of the node admin API.

        Note what this does and does not do: the page relies on inline <script>, so
        script-src must allow 'unsafe-inline' and CSP therefore does NOT prevent an
        injected script from running. Escaping is the actual fix. What CSP buys is
        containment — connect-src/img-src/form-action 'self'|'none' stop an injected
        script from exfiltrating the audit log or config to an external host.
        """
        response = await call_next(request)
        response.headers["Content-Security-Policy"] = (
            "default-src 'none'; "
            "style-src 'unsafe-inline'; "
            "script-src 'unsafe-inline'; "
            "connect-src 'self'; "
            "img-src 'self' data:; "
            "form-action 'none'; "
            "frame-ancestors 'none'; "
            "base-uri 'none'"
        )
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["Referrer-Policy"] = "no-referrer"
        return response

    # ── JSON API ─────────────────────────────────────────────────────────────

    @app.get("/api/status")
    async def api_status():
        indexes = state.get("indexes", {})
        total_files = sum(idx.count for idx in indexes.values())
        groups_ctx = state.get("groups_ctx", {})
        webrtc = state.get("webrtc")
        return {
            "version": __version__,
            "status": state.get("status", "starting"),
            "hub_url": state.get("hub_url", ""),
            "username": state.get("username", ""),
            "quic_port": state.get("quic_port", 0),
            "endpoint_hint": state.get("endpoint_hint"),
            "group_count": len(groups_ctx),
            "total_files": total_files,
            "webrtc_peers": webrtc.active_peers if webrtc else 0,
            "pk_node_ed25519": state.get("pk_node_ed25519", ""),
        }

    @app.get("/api/groups")
    async def api_groups():
        groups_ctx = state.get("groups_ctx", {})
        config = state.get("config")
        result = []
        for gid, ctx in groups_ctx.items():
            cfg = None
            if config:
                cfg = next((g for g in config.groups if g.id == gid), None)
            idx = ctx.get("index")
            result.append({
                "id": gid,
                "name": cfg.name if cfg else gid[:8],
                "shared_dir": str(ctx.get("shared_root", "")),
                "visibility": cfg.visibility if cfg else "private",
                "file_count": idx.count if idx else 0,
                "index_version": idx.version if idx else 0,
            })
        return {"groups": result}

    @app.get("/api/groups/{group_id}/files")
    async def api_group_files(group_id: str):
        groups_ctx = state.get("groups_ctx", {})
        ctx = groups_ctx.get(group_id)
        if not ctx:
            return {"files": []}
        idx = ctx.get("index")
        if not idx:
            return {"files": []}
        return {
            "files": [
                {
                    "id": e.id,
                    "name": e.name,
                    "path": e.path,
                    "size": e.size,
                    "type": e.type,
                    "added_at": e.added_at,
                }
                for e in idx.entries
            ]
        }

    @app.get("/api/peers")
    async def api_peers():
        webrtc = state.get("webrtc")
        if not webrtc:
            return {"peers": []}
        peers = []
        for pid, session in list(webrtc._sessions.items()):
            from meshbay_node.transport.webrtc_server import _get_remote_ip
            peers.append({
                "peer_id": pid,
                "user_id": session._user_id or "",
                "username": session._username or "",
                "group_id": session._group_id or "",
                "remote_ip": session._remote_ip or _get_remote_ip(session._pc),
                "state": session._pc.connectionState,
            })
        return {"peers": peers}

    @app.get("/api/audit")
    async def api_audit(
        since: float = 0,
        limit: int = 200,
        user_id: str | None = Query(default=None),
        event: str | None = Query(default=None),
    ):
        audit = state.get("audit_store")
        if not audit:
            return {"entries": []}
        entries = await audit.get_entries(
            since=since, limit=limit, user_id=user_id, event=event)
        return {
            "entries": [
                {
                    "id": e.id,
                    "timestamp": e.timestamp,
                    "user_id": e.user_id,
                    "username": e.username,
                    "ip": e.ip,
                    "event": e.event,
                    "group_id": e.group_id,
                    "detail": e.detail,
                }
                for e in entries
            ]
        }

    @app.get("/api/config")
    async def api_config():
        config = state.get("config")
        if not config:
            return {}
        return {
            "hub_url": config.hub.url,
            "username": config.hub.username,
            "quic_port": config.node.quic_port,
            "ui_port": config.node.ui_port,
            "data_dir": str(config.data_dir),
            "groups": [
                {
                    "id": g.id,
                    "name": g.name,
                    "shared_dir": g.shared_dir,
                    "visibility": g.visibility,
                }
                for g in config.groups
            ],
        }

    # ── Operator pairing (localhost only) ──────────────────────────────────

    @app.post("/api/operator/pair")
    async def operator_pair():
        """
        Issue a one-time code that pairs a browser as this node's operator.

        The code is the whole point: it binds the operator's browser identity key
        to their account without asking the hub, which is what stops a hub from
        naming itself node administrator (M3, and the same substitution as H3).
        It is returned once and stored only as a hash.
        """
        roster = state.get("roster")
        user_id = state.get("node_user_id")
        if not roster or not user_id:
            return JSONResponse({"error": "Node not connected to hub yet"}, 503)

        config = state.get("config")
        ttl = (config.node.pair_ttl_hours if config else 24) * 3600
        code = await roster.create_invite(
            group_id="",                 # operator authority is node-wide
            user_id=user_id,
            role=ROLE_OPERATOR,
            created_by="local-cli",
            ttl=ttl,
            username=(config.hub.username if config else ""),
        )
        invites = await roster.list_invites()
        expires = next((i["expires_at"] for i in invites
                        if i["user_id"] == user_id and i["role"] == ROLE_OPERATOR), "")
        return {"code": code, "expires_at": expires, "user_id": user_id}

    @app.get("/api/roster")
    async def api_roster(group_id: str = ""):
        roster = state.get("roster")
        if not roster:
            return {"identities": [], "members": [], "invites": []}
        return {
            "identities": await roster.list_identities(),
            "members": await roster.list_members(group_id or None),
            "invites": await roster.list_invites(),
        }

    @app.post("/api/groups/{group_id}/invites")
    async def create_invite(group_id: str, username: str):
        """
        Issue an invitation code from the CLI, without a browser.

        The hub is asked for the account id and nothing else — never for a key.
        A hub that answered with the wrong account would produce an invite whose
        code it never learns, since the code goes to a human out of band.
        """
        roster = state.get("roster")
        groups_ctx = state.get("groups_ctx", {})
        if not roster:
            return JSONResponse({"error": "Roster not available"}, 503)
        if group_id not in groups_ctx:
            return JSONResponse({"error": "Group not hosted on this node"}, 404)

        hub = state.get("hub")
        if not hub or not hub._session:
            return JSONResponse({"error": "Hub not connected"}, 503)
        try:
            account = await hub.get_user_pubkeys(username)
        except Exception as e:
            return JSONResponse({"error": f"Unknown user {username!r}: {e}"}, 404)

        config = state.get("config")
        ttl = (config.node.invite_ttl_hours if config else 168) * 3600
        code = await roster.create_invite(
            group_id=group_id,
            user_id=account["user_id"],
            role=ROLE_MEMBER,
            created_by="local-cli",
            ttl=ttl,
            username=username,
        )
        invites = await roster.list_invites()
        expires = next((i["expires_at"] for i in invites
                        if i["user_id"] == account["user_id"]
                        and i["group_id"] == group_id), "")
        return {"code": code, "expires_at": expires,
                "username": username, "user_id": account["user_id"]}

    @app.get("/api/resolve")
    async def resolve_user(username: str):
        """
        Map a username to an account id for the CLI.

        The roster answers first — it is the node's own record. The hub is the
        fallback for identities pinned before invitations carried a name, and for
        people admitted through an open-join group. Only an account id comes back;
        no key is ever taken from here.
        """
        roster = state.get("roster")
        if roster:
            for ident in await roster.list_identities():
                if ident["username"] == username:
                    return {"user_id": ident["user_id"], "source": "roster"}
        hub = state.get("hub")
        if hub and hub._session:
            try:
                account = await hub.get_user_pubkeys(username)
                return {"user_id": account["user_id"], "source": "hub"}
            except Exception:
                pass
        return JSONResponse({"error": f"Unknown user {username!r}"}, 404)

    @app.post("/api/members/{user_id}/revoke")
    async def revoke_member(user_id: str, group_id: str):
        """
        Stop serving the group key to someone.

        Takes effect on their next connection: the key is wrapped on demand, so
        there is no stored bundle left behind that would outlive this. Rotating
        the group key is still required — they hold the current one.
        """
        roster = state.get("roster")
        if not roster:
            return JSONResponse({"error": "Roster not available"}, 503)
        if not await roster.set_status(group_id, user_id, "revoked"):
            return JSONResponse({"error": "No such member in that group"}, 404)
        log.info("Member revoked: user=%s group=%s", user_id[:8], group_id[:8])
        return {"status": "revoked", "user_id": user_id, "group_id": group_id,
                "reminder": "rotate the group key: meshbay-node gek-init"}

    @app.post("/api/members/{user_id}/unpin")
    async def unpin_member(user_id: str):
        """Forget a pinned identity, so the person can pair again with a new key."""
        roster = state.get("roster")
        if not roster:
            return JSONResponse({"error": "Roster not available"}, 503)
        if not await roster.unpin(user_id):
            return JSONResponse({"error": "No such pinned identity"}, 404)
        log.info("Identity unpinned: user=%s", user_id[:8])
        return {"status": "unpinned", "user_id": user_id}

    # ── GEK initialization (operator only, localhost) ──────────────────────

    @app.post("/api/groups/{group_id}/gek")
    async def init_gek(group_id: str):
        """
        Generate the group key and activate it.

        It used to be wrapped here for every member, using public keys fetched from
        the hub — which is H3 with the node as the victim instead of the inviter: a
        hub answering with its own key was handed the group key by the node itself.

        Nothing is pre-wrapped for members now. Each member's copy is produced when
        they connect, for a key they proved they hold (`join_request`). Only the
        node's own copy is stored, so the daemon can reload the key across restarts
        without the operator's browser.
        """
        groups_ctx = state.get("groups_ctx", {})
        if group_id not in groups_ctx:
            return JSONResponse({"error": "Group not hosted on this node"}, 404)

        hub = state.get("hub")
        if not hub or not hub._session:
            return JSONResponse({"error": "Hub not connected"}, 503)

        bundle_store = state.get("bundle_store")
        if not bundle_store:
            return JSONResponse({"error": "Bundle store not available"}, 503)

        existing_gek = groups_ctx[group_id].get("gek")
        gek = existing_gek or generate_gek()
        errors: list[str] = []

        roster = state.get("roster")
        authorized = len(await roster.list_members(group_id)) if roster else 0

        # Store a copy wrapped for the node keystore X25519 key so the daemon can
        # reload the GEK on restart without the operator's browser keys.
        node_user_id = hub._session.user_id if hub._session else None
        pk_x_node_raw = state.get("pk_x25519_raw")
        if pk_x_node_raw and node_user_id:
            try:
                node_bundle = wrap_gek_aes(gek, pk_x_node_raw)
                await bundle_store.store(
                    group_id, f"_node_{node_user_id}",
                    node_bundle["pk_eph_b64"], node_bundle["nonce_b64"],
                    node_bundle["wrapped_b64"],
                )
                log.info("GEK wrapped for node keystore (daemon reload)")
            except Exception as e:
                errors.append(f"node keystore: {e}")
                log.warning("Failed to wrap GEK for node keystore: %s", e)

        groups_ctx[group_id]["gek"] = gek
        log.info("GEK initialized for group %s — %d authorized member(s) will "
                 "receive it on connect", group_id[:8], authorized)

        webrtc = state.get("webrtc")
        if webrtc and "groups" in webrtc._ctx and group_id in webrtc._ctx["groups"]:
            webrtc._ctx["groups"][group_id]["gek"] = gek

        return {
            "status": "ok",
            "group_id": group_id,
            "authorized_members": authorized,
            "errors": errors,
        }

    # ── Chat endpoints ───────────────────────────────────────────────────────

    _chat_subscribers: list[WebSocket] = []

    @app.get("/api/chat/history")
    async def chat_history(since: float = 0, limit: int = 100):
        chat_store = state.get("chat_store")
        if not chat_store:
            return {"messages": []}
        msgs = await chat_store.get_messages(since=since, limit=limit)
        return {
            "messages": [
                {
                    "id": m.id,
                    "sender_id": m.sender_id,
                    "iteration": m.iteration,
                    "timestamp": m.timestamp,
                    "thread_id": m.thread_id,
                }
                for m in msgs
            ]
        }

    @app.websocket("/ws/chat")
    async def chat_websocket(ws: WebSocket):
        await ws.accept()
        _chat_subscribers.append(ws)
        try:
            while True:
                await ws.receive_text()
        except WebSocketDisconnect:
            pass
        finally:
            _chat_subscribers.remove(ws)

    async def broadcast_chat_to_ui(msg: dict) -> None:
        payload = json.dumps(msg)
        dead = []
        for ws in _chat_subscribers:
            try:
                await ws.send_text(payload)
            except Exception:
                dead.append(ws)
        for ws in dead:
            _chat_subscribers.remove(ws)

    app.broadcast_chat = broadcast_chat_to_ui

    # ── HTML UI ──────────────────────────────────────────────────────────────

    @app.get("/", response_class=HTMLResponse)
    async def root():
        # Roster reads are async and the page renderer is not, so gather here.
        roster = state.get("roster")
        roster_view = None
        if roster:
            identities = {i["user_id"]: i for i in await roster.list_identities()}
            roster_view = {
                "identities": identities,
                "members": await roster.list_members(),
                "invites": await roster.list_invites(),
            }
        return _render_page(state, roster_view)

    @app.get("/audit", response_class=HTMLResponse)
    async def audit_page():
        return _render_audit_page(state.get("ui_token", ""))

    return app


def _fmt_size(n: int) -> str:
    if n < 1024:
        return f"{n} B"
    if n < 1024 * 1024:
        return f"{n / 1024:.1f} KB"
    if n < 1024 * 1024 * 1024:
        return f"{n / (1024 * 1024):.1f} MB"
    return f"{n / (1024 * 1024 * 1024):.2f} GB"


def _render_roster(roster_view: dict | None) -> str:
    """
    Who this node recognises, and which keys are theirs.

    Every value here is escaped: usernames come from the hub and pass through the
    roster, so they are attacker-influenced text on the operator's own admin page
    (the H2 rule applies to them exactly as it does to filenames).
    """
    if roster_view is None:
        return '<p class="muted">Roster unavailable</p>'

    identities = roster_view["identities"]
    rows = ""
    for m in roster_view["members"]:
        ident = identities.get(m["user_id"], {})
        scope = escape(m["group_id"][:8]) if m["group_id"] else "node-wide"
        status_color = "#22c55e" if m["status"] == "active" else "#ef4444"
        rows += (
            f"<tr><td>{escape(str(ident.get('username') or m['user_id']))}</td>"
            f"<td>{escape(str(m['role']))}</td>"
            f"<td><span class='badge' style='background:{status_color}'>"
            f"{escape(str(m['status']))}</span></td>"
            f"<td>{scope}</td>"
            f"<td><code>{escape(str(ident.get('pk_ed25519', ''))[:16])}…</code></td>"
            f"<td>{escape(str(ident.get('pinned_at', '?')))} "
            f"({escape(str(ident.get('pinned_via', '?')))})</td></tr>"
        )
    if not rows:
        rows = ('<tr><td colspan="6" class="muted">Nobody admitted yet — '
                'run <code>meshbay-node member invite &lt;username&gt;</code></td></tr>')

    invite_rows = ""
    for i in roster_view["invites"]:
        invite_rows += (
            f"<tr><td><code>{escape(str(i['user_id'])[:16])}</code></td>"
            f"<td>{escape(str(i['group_id'][:8] or 'node-wide'))}</td>"
            f"<td>{escape(str(i['role']))}</td>"
            f"<td>{escape(str(i['expires_at']))}</td></tr>"
        )
    invites_html = ""
    if invite_rows:
        invites_html = f"""
        <details style="margin-top:10px"><summary>Pending invitations</summary>
        <table>
          <thead><tr><th>Account</th><th>Group</th><th>Role</th><th>Expires</th></tr></thead>
          <tbody>{invite_rows}</tbody>
        </table>
        </details>"""

    return f"""
    <table>
      <thead><tr><th>User</th><th>Role</th><th>Status</th><th>Scope</th>
                 <th>Identity key</th><th>Pinned</th></tr></thead>
      <tbody>{rows}</tbody>
    </table>
    {invites_html}
    <p class="muted" style="margin-top:8px">
      Codes are issued from the CLI: <code>meshbay-node operator pair</code>,
      <code>meshbay-node member invite &lt;username&gt;</code>. They never pass
      through the hub.
    </p>"""


def _render_page(state: dict, roster_view: dict | None = None) -> str:
    token_js = json.dumps(state.get("ui_token", ""))
    status = state.get("status", "starting")
    indexes = state.get("indexes", {})
    groups_ctx = state.get("groups_ctx", {})
    config = state.get("config")
    webrtc = state.get("webrtc")
    total_files = sum(idx.count for idx in indexes.values())
    peer_count = webrtc.active_peers if webrtc else 0
    status_color = {
        "running": "#22c55e", "error": "#ef4444",
        "waiting_for_node_key": "#f97316",
    }.get(status, "#f59e0b")

    # Groups section
    groups_html = ""
    for gid, ctx in groups_ctx.items():
        cfg = None
        if config:
            cfg = next((g for g in config.groups if g.id == gid), None)
        idx = ctx.get("index")
        name = cfg.name if cfg else gid[:8]
        shared = ctx.get("shared_root", "")
        vis = cfg.visibility if cfg else "private"
        fcount = idx.count if idx else 0
        total_size = sum(e.size for e in idx.entries) if idx else 0

        # Everything interpolated below is attacker-controlled: filenames come from
        # uploads by any group member. Rendering them raw was a stored XSS into the
        # unauthenticated localhost admin UI, i.e. full control of the node admin API
        # from the operator's browser (finding H2).
        file_rows = ""
        if idx:
            for e in sorted(idx.entries, key=lambda x: x.name):
                file_rows += (
                    f"<tr><td>{escape(e.name)}</td><td>{escape(e.type)}</td>"
                    f"<td>{_fmt_size(e.size)}</td><td>{escape(e.path or '/')}</td></tr>"
                )

        has_gek = bool(ctx.get("gek"))
        gek_badge = (
            '<span class="badge" style="background:#22c55e">GEK active</span>'
            if has_gek
            else '<span class="badge" style="background:#ef4444">No GEK</span>'
        )
        gek_label = "Re-wrap GEK for all members" if has_gek else "Initialize GEK"
        gek_color = "#3b82f6" if has_gek else "#22c55e"
        gek_action = f"""
            <div style="margin:10px 0">
              <button onclick="initGEK('{gid}')"
                id="gek-btn-{gid[:8]}"
                style="padding:8px 16px;background:{gek_color};color:#fff;border:none;
                border-radius:6px;cursor:pointer;font-size:0.85em">
                {gek_label}
              </button>
              <span id="gek-status-{gid[:8]}" class="muted" style="margin-left:8px"></span>
            </div>"""

        groups_html += f"""
        <div class="card">
          <h3>{escape(str(name))}
            <span class="badge" style="background:#6366f1">{escape(str(vis))}</span>
            {gek_badge}
          </h3>
          <p><b>Directory:</b> <code>{escape(str(shared))}</code></p>
          <p><b>Files:</b> {fcount} &mdash; <b>Total:</b> {_fmt_size(total_size)}</p>
          {gek_action}
          <p class="muted">ID: {escape(gid)}</p>
          <details><summary>File list</summary>
          <table>
            <thead><tr><th>Name</th><th>Type</th><th>Size</th><th>Path</th></tr></thead>
            <tbody>{file_rows}</tbody>
          </table>
          </details>
        </div>"""

    # Peers section
    peers_html = ""
    if webrtc:
        for pid, session in list(webrtc._sessions.items()):
            from meshbay_node.transport.webrtc_server import _get_remote_ip
            ip = session._remote_ip or _get_remote_ip(session._pc)
            peers_html += (
                f"<tr><td>{escape(session._username or session._user_id or '—')}</td>"
                f"<td>{escape(ip or '—')}</td>"
                f"<td>{escape(session._group_id[:8] if session._group_id else '—')}</td>"
                f"<td>{escape(session._pc.connectionState)}</td></tr>"
            )
    if not peers_html:
        peers_html = '<tr><td colspan="4" class="muted">No connected peers</td></tr>'

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MeshBay Node Admin</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  :root {{
    --bg: #0f172a; --surface: #1e293b; --border: #334155;
    --text: #e2e8f0; --muted: #94a3b8; --accent: #3b82f6;
    --green: #22c55e; --red: #ef4444; --yellow: #f59e0b;
  }}
  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
  body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
          background: var(--bg); color: var(--text); }}
  .container {{ max-width: 1000px; margin: 0 auto; padding: 20px; }}
  h1 {{ font-size: 1.5em; margin-bottom: 20px; }}
  h2 {{ font-size: 1.2em; margin: 24px 0 12px; border-bottom: 1px solid var(--border); padding-bottom: 6px; }}
  h3 {{ font-size: 1em; margin-bottom: 8px; }}
  .badge {{ display: inline-block; padding: 2px 8px; border-radius: 4px;
            color: #fff; font-size: 0.8em; font-weight: 600; vertical-align: middle; }}
  .stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 12px; margin-bottom: 20px; }}
  .stat {{ background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
           padding: 16px; text-align: center; }}
  .stat .value {{ font-size: 1.8em; font-weight: 700; color: var(--accent); }}
  .stat .label {{ font-size: 0.8em; color: var(--muted); margin-top: 4px; }}
  .card {{ background: var(--surface); border: 1px solid var(--border);
           border-radius: 8px; padding: 16px; margin-bottom: 12px; }}
  table {{ width: 100%; border-collapse: collapse; font-size: 0.85em; margin-top: 8px; }}
  th, td {{ padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--border); }}
  th {{ color: var(--muted); font-weight: 600; font-size: 0.75em; text-transform: uppercase; }}
  code {{ background: var(--border); padding: 2px 6px; border-radius: 3px; font-size: 0.85em; }}
  .muted {{ color: var(--muted); font-size: 0.85em; }}
  details summary {{ cursor: pointer; color: var(--accent); font-size: 0.85em; margin-top: 8px; }}
  a {{ color: var(--accent); text-decoration: none; }}
  a:hover {{ text-decoration: underline; }}
  nav {{ display: flex; gap: 16px; margin-bottom: 20px; }}
  nav a {{ padding: 6px 12px; border-radius: 6px; background: var(--surface);
           border: 1px solid var(--border); }}
  nav a:hover {{ background: var(--border); text-decoration: none; }}
  .footer {{ margin-top: 32px; padding-top: 12px; border-top: 1px solid var(--border);
             font-size: 0.8em; color: var(--muted); }}
</style>
</head>
<body>
<div class="container">
  <h1>MeshBay Node <span class="badge" style="background:{status_color}">{status}</span></h1>

  <nav>
    <a href="/">Dashboard</a>
    <a href="/audit">Audit Log</a>
    <a href="/api/status">API</a>
  </nav>

  <div class="stats">
    <div class="stat"><div class="value">{len(groups_ctx)}</div><div class="label">Groups</div></div>
    <div class="stat"><div class="value">{total_files}</div><div class="label">Files</div></div>
    <div class="stat"><div class="value">{peer_count}</div><div class="label">Connected Peers</div></div>
    <div class="stat">
      <div class="value" style="font-size:1em;word-break:break-all">{state.get("username", "—")}</div>
      <div class="label">User</div>
    </div>
  </div>

  <h2>Connected Peers</h2>
  <table>
    <thead><tr><th>User</th><th>IP</th><th>Group</th><th>State</th></tr></thead>
    <tbody>{peers_html}</tbody>
  </table>

  <h2>Roster</h2>
  {_render_roster(roster_view)}

  <h2>Groups</h2>
  {groups_html or '<p class="muted">No groups configured</p>'}

  <h2>Node Configuration</h2>
  <div class="card">
    <p><b>Hub:</b> {state.get("hub_url", "—")}</p>
    <p><b>QUIC port:</b> {state.get("quic_port", "—")}</p>
    <p><b>Node ID:</b> <code>{state.get("endpoint_hint") or "—"}</code></p>
  </div>

  <h2>Link Node to Hub Account</h2>
  <div class="card">
    <p>To connect to your group from a browser, link this node to your hub account.
       Copy the key below and paste it in <b>Settings &gt; Link Node</b> on the hub.</p>
    <div style="margin:12px 0;display:flex;align-items:center;gap:8px">
      <code id="nodeKey" style="flex:1;padding:8px;word-break:break-all;background:var(--border);
        border-radius:4px;font-size:0.9em;user-select:all">{state.get("pk_node_ed25519", "—")}</code>
      <button onclick="navigator.clipboard.writeText(document.getElementById('nodeKey').textContent).then(()=>{{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy',2000)}})"
        style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:6px;
        cursor:pointer;font-size:0.85em;white-space:nowrap">Copy</button>
    </div>
    <p class="muted">This is the node's Ed25519 public key. It's safe to share — it identifies
       this node but cannot be used to impersonate it.</p>
  </div>

  <div class="footer">
    MeshBay Node v{__version__} &mdash; localhost only &mdash;
    <a href="/api/status">status</a> &middot;
    <a href="/api/groups">groups</a> &middot;
    <a href="/api/peers">peers</a> &middot;
    <a href="/api/audit">audit</a> &middot;
    <a href="/api/config">config</a>
    &mdash; auto-refresh 10s
  </div>
</div>
<script>
const TOKEN = {token_js};
async function initGEK(groupId) {{
  const btn = document.getElementById('gek-btn-' + groupId.slice(0,8));
  const status = document.getElementById('gek-status-' + groupId.slice(0,8));
  if (btn) btn.disabled = true;
  if (status) status.textContent = 'Initializing...';
  try {{
    const resp = await fetch('/api/groups/' + groupId + '/gek?t=' + TOKEN, {{ method: 'POST' }});
    const data = await resp.json();
    if (resp.ok) {{
      if (status) status.textContent = 'GEK initialized — '
        + data.authorized_members + ' authorized member(s) get it on connect';
      if (status) status.style.color = '#22c55e';
      setTimeout(() => location.reload(), 2000);
    }} else {{
      if (status) status.textContent = data.error || 'Failed';
      if (status) status.style.color = '#ef4444';
      if (btn) btn.disabled = false;
    }}
  }} catch (e) {{
    if (status) status.textContent = 'Error: ' + e.message;
    if (status) status.style.color = '#ef4444';
    if (btn) btn.disabled = false;
  }}
}}
setTimeout(()=>location.reload(), 10000);
</script>
</body>
</html>"""


def _render_audit_page(token: str = "") -> str:
    return _AUDIT_HTML.replace("__TOKEN__", json.dumps(token))


_AUDIT_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MeshBay Node — Audit Log</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  :root {
    --bg: #0f172a; --surface: #1e293b; --border: #334155;
    --text: #e2e8f0; --muted: #94a3b8; --accent: #3b82f6;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
         background: var(--bg); color: var(--text); }
  .container { max-width: 1100px; margin: 0 auto; padding: 20px; }
  h1 { font-size: 1.5em; margin-bottom: 16px; }
  nav { display: flex; gap: 16px; margin-bottom: 20px; }
  nav a { padding: 6px 12px; border-radius: 6px; background: var(--surface);
          border: 1px solid var(--border); color: var(--accent); text-decoration: none; }
  nav a:hover { background: var(--border); }
  .filters { display: flex; gap: 10px; margin-bottom: 16px; flex-wrap: wrap; }
  .filters select, .filters input {
    background: var(--surface); color: var(--text); border: 1px solid var(--border);
    padding: 6px 10px; border-radius: 6px; font-size: 0.85em;
  }
  table { width: 100%; border-collapse: collapse; font-size: 0.82em; }
  th, td { padding: 5px 8px; text-align: left; border-bottom: 1px solid var(--border); }
  th { color: var(--muted); font-weight: 600; font-size: 0.75em; text-transform: uppercase;
       position: sticky; top: 0; background: var(--bg); }
  .muted { color: var(--muted); }
  #count { margin-bottom: 10px; font-size: 0.85em; color: var(--muted); }
</style>
</head>
<body>
<div class="container">
  <h1>Audit Log</h1>
  <nav><a id="navHome" href="/">Dashboard</a><a id="navAudit" href="/audit">Audit Log</a></nav>

  <div class="filters">
    <select id="eventFilter">
      <option value="">All events</option>
      <option value="handshake">handshake</option>
      <option value="file_download">file_download</option>
      <option value="file_upload">file_upload</option>
      <option value="file_delete">file_delete</option>
      <option value="stream_video">stream_video</option>
      <option value="chat_message">chat_message</option>
      <option value="disconnect">disconnect</option>
      <option value="auth_failed">auth_failed</option>
    </select>
    <input id="userFilter" placeholder="Filter by user..." />
    <select id="limitSelect">
      <option value="100">100 entries</option>
      <option value="500">500 entries</option>
      <option value="1000">1000 entries</option>
    </select>
  </div>

  <div id="count"></div>
  <table>
    <thead><tr><th>Time</th><th>Event</th><th>User</th><th>IP</th><th>Group</th><th>Detail</th></tr></thead>
    <tbody id="tbody"></tbody>
  </table>
</div>
<script>
const TOKEN = __TOKEN__;
async function load() {
  const ev = document.getElementById('eventFilter').value;
  const limit = document.getElementById('limitSelect').value;
  let url = '/api/audit?limit=' + limit + (TOKEN ? '&t=' + TOKEN : '');
  if (ev) url += '&event=' + ev;
  const r = await fetch(url);
  const data = await r.json();
  const tbody = document.getElementById('tbody');
  document.getElementById('count').textContent = data.entries.length + ' entries';
  // textContent, not innerHTML: e.detail carries filenames chosen by group members
  // (finding H2). Building this row with string concatenation was a stored XSS.
  tbody.replaceChildren(...data.entries.map(e => {
    const tr = document.createElement('tr');
    const cells = [
      new Date(e.timestamp * 1000).toLocaleString(),
      e.event,
      e.username || (e.user_id || '').slice(0, 8),
      e.ip || '—',
      e.group_id ? e.group_id.slice(0, 8) : '—',
      e.detail || '',
    ];
    for (const value of cells) {
      const td = document.createElement('td');
      td.textContent = value;
      tr.appendChild(td);
    }
    return tr;
  }));
}
for (const [id, href] of [['navHome','/'],['navAudit','/audit']]) {
  const el = document.getElementById(id);
  if (el && TOKEN) el.href = href + '?t=' + TOKEN;
}
document.getElementById('eventFilter').onchange = load;
document.getElementById('limitSelect').onchange = load;
let debounceTimer;
document.getElementById('userFilter').oninput = function() {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    const val = this.value;
    const rows = document.querySelectorAll('#tbody tr');
    rows.forEach(r => {
      r.style.display = r.textContent.toLowerCase().includes(val.toLowerCase()) ? '' : 'none';
    });
  }, 200);
};
load();
setInterval(load, 15000);
</script>
</body>
</html>"""