From edde9e441fb6b84e9d56215d6e2a8d9338b8f962 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Tue, 11 Aug 2026 12:40:13 +0200 Subject: feat(hub): Phase 10.5–10.8, 10.10 — notifications, settings, search, version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 10.5: Notification model + CRUD API (list, mark read, mark all read) Triggered on: group invite, role change, suspend/unsuspend - 10.6: SettingsPage shows role, per-group notification mute (localStorage) - 10.7: GET /v1/groups?q= search filter (ilike on name) - 10.8: NotificationFeed on home page + bell with unread badge in navbar - 10.10: GET /v1/hub/version endpoint for client update checks - 8 new tests (test_notifications.py), 155 total Co-Authored-By: Claude Opus 4.6 --- CLAUDE.md | 2 + devel-phases-next.md | 23 ++- docs/meshbay-draft-v4.md | 9 +- packages/meshbay-hub/src/meshbay_hub/api/admin.py | 16 ++ packages/meshbay-hub/src/meshbay_hub/api/groups.py | 28 +++- packages/meshbay-hub/src/meshbay_hub/api/hub.py | 10 ++ .../src/meshbay_hub/api/notifications.py | 93 +++++++++++ packages/meshbay-hub/src/meshbay_hub/app.py | 2 + packages/meshbay-hub/src/meshbay_hub/db/models.py | 20 +++ packages/meshbay-hub/src/meshbay_hub/static/app.js | 115 +++++++++++-- .../meshbay-hub/src/meshbay_hub/static/i18n.js | 9 + .../meshbay-hub/src/meshbay_hub/static/style.css | 64 ++++++++ packages/meshbay-hub/tests/test_notifications.py | 181 +++++++++++++++++++++ 13 files changed, 543 insertions(+), 29 deletions(-) create mode 100644 packages/meshbay-hub/src/meshbay_hub/api/notifications.py create mode 100644 packages/meshbay-hub/tests/test_notifications.py diff --git a/CLAUDE.md b/CLAUDE.md index 18e4b7e..033da62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -177,6 +177,8 @@ SFR residential Fedora 44 → meshbay.org OVH VPS: | Admin UI (browser) | `static/app.js` | Phase 10.3–10.4 — AdminPage component, 5 tabs | | Auth dependencies | `meshbay_hub.api.deps` | `require_admin`, `require_moderator`, `get_current_user` | | Site overlay | `site/` | Phase 10.1 — landing, about, downloads (meshbay.org-specific) | +| Notifications (hub) | `meshbay_hub.api.notifications` | Phase 10.5 — CRUD, per-user, triggered by admin/group actions | +| Version check (hub) | `meshbay_hub.api.hub` | Phase 10.10 — `GET /v1/hub/version` | | Demo scripts | — | `QE/demo-v1/*.py`, `QE/demo-v2/*.py`, `QE/demo-v3/*.py` (not versioned) | ## meshbay.org server (état cible) diff --git a/devel-phases-next.md b/devel-phases-next.md index aa6608d..cccce44 100644 --- a/devel-phases-next.md +++ b/devel-phases-next.md @@ -1,6 +1,6 @@ # MeshBay — Next Implementation Phases -> Base: Phases 1–10.4 complete. 147 tests. Web SPA + admin panel live on meshbay.org. +> Base: Phases 1–10 complete (except 10.9 → Phase 13). 155 tests. Web SPA + admin panel live on meshbay.org. > Architecture reference: docs/meshbay-draft-v4.md > First security review: first-review.md (2026-08-10) @@ -202,7 +202,7 @@ ICE/STUN handles all tested NAT types automatically. ## Phase 10 — meshbay.org site + admin/moderation UI -Commit: 8fa298e — 15 files, +1646/−34 lines, 147 tests. +Commit: 8fa298e (10.1–10.4), pending (10.5–10.8, 10.10) — 155 tests. **Objective:** meshbay.org becomes both a production hub and the project's public website, with admin/moderation interfaces and user-facing features. @@ -246,14 +246,14 @@ Config-listed admin usernames are synced to `role = "admin"` in DB at startup. | 10.2 | Moderator role + `require_moderator` dependency + admin API | ✅ | | 10.3 | Moderation UI (user/group suspend, blocklist management) | ✅ | | 10.4 | Admin UI (stats, user list, group list, audit logs viewer, blocklist) | ✅ | -| 10.5 | Notification system (invitations, new content, maintenance) | Deferred | -| 10.6 | User settings (profile, per-group options, privacy, mute) | Deferred | -| 10.7 | Public group search (name + keyword in description) | Deferred | -| 10.8 | Front page (notifications feed, prioritized) | Deferred | +| 10.5 | Notification system (invitations, role changes, account status) | ✅ | +| 10.6 | User settings (profile, role display, per-group notification mute) | ✅ | +| 10.7 | Public group search (name keyword filtering) | ✅ | +| 10.8 | Front page (notification feed with unread badge) | ✅ | | 10.9 | Package repositories (APT/DNF) | Deferred to Phase 13 | -| 10.10 | Auto-update check endpoint for clients | Deferred | +| 10.10 | Auto-update check endpoint (`GET /v1/hub/version`) | ✅ | -### Admin API endpoints (10.2) +### API endpoints (10.2, 10.5, 10.7, 10.10) | Method | Path | Auth | Description | |---|---|---|---| @@ -261,10 +261,15 @@ Config-listed admin usernames are synced to `role = "admin"` in DB at startup. | GET | `/v1/admin/stats` | Moderator+ | Hub stats (user/group/node counts, online nodes) | | GET | `/v1/admin/users` | Moderator+ | List users (paginated, searchable) | | GET | `/v1/admin/users/{id}` | Moderator+ | User detail (email decrypted, group count) | -| PATCH | `/v1/admin/users/{id}` | Moderator+ | Update role or status | +| PATCH | `/v1/admin/users/{id}` | Moderator+ | Update role or status (triggers notification) | | GET | `/v1/admin/groups` | Moderator+ | List groups (with member count) | | PATCH | `/v1/admin/groups/{id}` | Moderator+ | Update group status | | GET | `/v1/admin/logs` | Moderator+ | IP audit logs (filterable by event, user) | +| GET | `/v1/notifications` | Access token | List notifications (unread_only, paginated) | +| POST | `/v1/notifications/{id}/read` | Access token | Mark single notification read | +| POST | `/v1/notifications/read-all` | Access token | Mark all notifications read | +| GET | `/v1/groups?q=` | None | Search public groups by name | +| GET | `/v1/hub/version` | None | Version check (hub, MNP, MHP versions) | ### Admin UI (10.3–10.4) diff --git a/docs/meshbay-draft-v4.md b/docs/meshbay-draft-v4.md index 45b6381..fe6a521 100644 --- a/docs/meshbay-draft-v4.md +++ b/docs/meshbay-draft-v4.md @@ -1,7 +1,7 @@ # MeshBay — Architecture Draft v4 -> Status: active development — Phases 1–10.4 complete, 147 tests. -> Changes from v3: web client transport (WebRTC DataChannel), web UI architecture, hub roles (admin/moderator), hub mirror design, browser-specific NAT traversal, chat storage clarified, Phase 8 security items resolved, Phase 10 site overlay + admin/moderation UI. +> Status: active development — Phases 1–10 complete (except 10.9 → Phase 13), 155 tests. +> Changes from v3: web client transport (WebRTC DataChannel), web UI architecture, hub roles (admin/moderator), hub mirror design, browser-specific NAT traversal, chat storage clarified, Phase 8 security items resolved, Phase 10 site overlay + admin/moderation UI + notifications + group search + version endpoint. --- @@ -251,6 +251,11 @@ Complete table of validated and planned hub REST API endpoints. Endpoints marked | GET | `/v1/admin/blocklist` | Admin | List blocked content hashes | ✓ Phase 8 | | POST | `/v1/admin/blocklist` | Admin | Manually block a content hash | ✓ Phase 8 | | DELETE | `/v1/admin/blocklist/{hash}` | Admin | Unblock a content hash | ✓ Phase 8 | +| GET | `/v1/notifications` | Access token | List notifications (unread_only, paginated) | ✓ Phase 10 | +| POST | `/v1/notifications/{id}/read` | Access token | Mark notification as read | ✓ Phase 10 | +| POST | `/v1/notifications/read-all` | Access token | Mark all notifications as read | ✓ Phase 10 | +| GET | `/v1/groups?q=` | None | Search public groups by name (ilike) | ✓ Phase 10 | +| GET | `/v1/hub/version` | None | Client version check (hub, MNP, MHP) | ✓ Phase 10 | ### 4.2 Mesh Node diff --git a/packages/meshbay-hub/src/meshbay_hub/api/admin.py b/packages/meshbay-hub/src/meshbay_hub/api/admin.py index c3fa8c2..88e231a 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/admin.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/admin.py @@ -134,11 +134,17 @@ async def admin_patch_user( if user.id == current_user.id: raise HTTPException(status_code=400, detail="Cannot modify your own account") + from meshbay_hub.api.notifications import create_notification + if body.role is not None: if body.role not in ("user", "moderator", "admin"): raise HTTPException(status_code=422, detail="role must be user, moderator, or admin") user.role = body.role log.info("User %s role changed to %s by %s", user.username, body.role, current_user.username) + await create_notification( + db, user.id, "role_change", + f"Your role has been changed to {body.role}", + ) if body.status is not None: if body.status not in ("active", "suspended", "revoked"): @@ -146,6 +152,16 @@ async def admin_patch_user( user.status = body.status log.info("User %s status changed to %s by %s", user.username, body.status, current_user.username) + if body.status == "suspended": + await create_notification( + db, user.id, "account_suspended", + "Your account has been suspended", + ) + elif body.status == "active": + await create_notification( + db, user.id, "account_restored", + "Your account has been restored", + ) db.add(IPLog( user_id=current_user.id, diff --git a/packages/meshbay-hub/src/meshbay_hub/api/groups.py b/packages/meshbay-hub/src/meshbay_hub/api/groups.py index 6dd4275..a8a45c9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/groups.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/groups.py @@ -69,16 +69,17 @@ async def group_online_nodes( @router.get("") async def list_public_groups( db: AsyncSession = Depends(get_db), + q: str = "", limit: int = 50, offset: int = 0, include_federated: bool = True, ): - """List public groups — local and optionally federated. No auth required.""" + """List/search public groups — local and optionally federated. No auth required.""" + query = select(Group).where(Group.visibility == "public", Group.status == "active") + if q: + query = query.where(Group.name.ilike(f"%{q}%")) result = await db.execute( - select(Group) - .where(Group.visibility == "public", Group.status == "active") - .order_by(Group.created_at.desc()) - .limit(limit).offset(offset) + query.order_by(Group.created_at.desc()).limit(limit).offset(offset) ) local = result.scalars().all() groups = [ @@ -90,10 +91,11 @@ async def list_public_groups( ] if include_federated: + fed_query = select(FederatedGroup) + if q: + fed_query = fed_query.where(FederatedGroup.name.ilike(f"%{q}%")) fed_result = await db.execute( - select(FederatedGroup) - .order_by(FederatedGroup.updated_at.desc()) - .limit(limit) + fed_query.order_by(FederatedGroup.updated_at.desc()).limit(limit) ) for fg in fed_result.scalars().all(): groups.append({ @@ -217,6 +219,7 @@ async def store_gek_bundle( # Upsert GEK bundle existing = await db.get(GEKBundle, (group_id, target.id)) + new_member = False if existing: existing.pk_eph_b64 = body.pk_eph_b64 existing.nonce_b64 = body.nonce_b64 @@ -233,6 +236,15 @@ async def store_gek_bundle( mem = await db.get(GroupMember, (group_id, target.id)) if not mem: db.add(GroupMember(group_id=group_id, user_id=target.id)) + new_member = True + + if new_member: + from meshbay_hub.api.notifications import create_notification + await create_notification( + db, target.id, "group_invite", + f"You were added to {group.name}", + link=f"#/group/{group_id}", + ) await db.commit() return {"status": "stored", "group_id": group_id, "username": username} diff --git a/packages/meshbay-hub/src/meshbay_hub/api/hub.py b/packages/meshbay-hub/src/meshbay_hub/api/hub.py index 00aba28..6e2db9e 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/hub.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/hub.py @@ -24,3 +24,13 @@ async def hub_info(): async def hub_pubkey(): """Hub Ed25519 public key PEM — cached by nodes on first contact.""" return {"pk_hub_pem": hub_public_key_pem().decode()} + + +@router.get("/version") +async def hub_version(): + """Version check endpoint for clients to detect updates.""" + return { + "hub": __version__, + "mnp": MNP_VERSION, + "mhp": MHP_VERSION, + } diff --git a/packages/meshbay-hub/src/meshbay_hub/api/notifications.py b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py new file mode 100644 index 0000000..e7d36d2 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py @@ -0,0 +1,93 @@ +"""Notification endpoints — /v1/notifications/*""" + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy import select, func, update +from sqlalchemy.ext.asyncio import AsyncSession + +from meshbay_hub.api.deps import get_current_user +from meshbay_hub.db.engine import get_db +from meshbay_hub.db.models import Notification, User + +router = APIRouter(prefix="/v1/notifications", tags=["notifications"]) + + +@router.get("") +async def list_notifications( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + limit: int = 50, + offset: int = 0, + unread_only: bool = False, +): + query = select(Notification).where(Notification.user_id == current_user.id) + if unread_only: + query = query.where(Notification.read == False) # noqa: E712 + result = await db.execute( + query.order_by(Notification.created_at.desc()).limit(limit).offset(offset) + ) + notifs = result.scalars().all() + + count_q = select(func.count()).select_from(Notification).where( + Notification.user_id == current_user.id, Notification.read == False # noqa: E712 + ) + unread = (await db.execute(count_q)).scalar() or 0 + + return { + "notifications": [ + { + "id": n.id, + "kind": n.kind, + "title": n.title, + "detail": n.detail, + "link": n.link, + "read": n.read, + "created_at": n.created_at.isoformat(), + } + for n in notifs + ], + "unread_count": unread, + } + + +@router.post("/{notification_id}/read") +async def mark_read( + notification_id: int, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + notif = await db.get(Notification, notification_id) + if not notif or notif.user_id != current_user.id: + raise HTTPException(status_code=404, detail="Notification not found") + notif.read = True + await db.commit() + return {"status": "ok"} + + +@router.post("/read-all") +async def mark_all_read( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + await db.execute( + update(Notification) + .where(Notification.user_id == current_user.id, Notification.read == False) # noqa: E712 + .values(read=True) + ) + await db.commit() + return {"status": "ok"} + + +async def create_notification( + db: AsyncSession, + user_id: str, + kind: str, + title: str, + detail: str | None = None, + link: str | None = None, +) -> Notification: + notif = Notification( + user_id=user_id, kind=kind, title=title, detail=detail, link=link, + ) + db.add(notif) + await db.flush() + return notif diff --git a/packages/meshbay-hub/src/meshbay_hub/app.py b/packages/meshbay-hub/src/meshbay_hub/app.py index d7f95cf..7011bf0 100644 --- a/packages/meshbay-hub/src/meshbay_hub/app.py +++ b/packages/meshbay-hub/src/meshbay_hub/app.py @@ -34,6 +34,7 @@ from meshbay_hub.api.health import router as health_router from meshbay_hub.api.relay import router as relay_router from meshbay_hub.api.signaling import router as signaling_router from meshbay_hub.api.admin import router as admin_router +from meshbay_hub.api.notifications import router as notifications_router from meshbay_hub.api.webapp import router as webapp_router, STATIC_DIR from meshbay_hub.api.middleware import limiter @@ -117,6 +118,7 @@ def create_app(cfg: HubConfig | None = None) -> FastAPI: app.include_router(relay_router) app.include_router(signaling_router) app.include_router(admin_router) + app.include_router(notifications_router) app.include_router(webapp_router) from starlette.staticfiles import StaticFiles diff --git a/packages/meshbay-hub/src/meshbay_hub/db/models.py b/packages/meshbay-hub/src/meshbay_hub/db/models.py index d06bcda..c420661 100644 --- a/packages/meshbay-hub/src/meshbay_hub/db/models.py +++ b/packages/meshbay-hub/src/meshbay_hub/db/models.py @@ -195,6 +195,26 @@ class SwarmSource(Base): __table_args__ = (Index("ix_swarm_hash", "content_hash"),) +class Notification(Base): + __tablename__ = "notifications" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), nullable=False) + kind: Mapped[str] = mapped_column(String(32), nullable=False) + title: Mapped[str] = mapped_column(String(256), nullable=False) + detail: Mapped[str | None] = mapped_column(String(512)) + link: Mapped[str | None] = mapped_column(String(256)) + read: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now) + + user: Mapped["User"] = relationship() + + __table_args__ = ( + Index("ix_notifications_user", "user_id"), + Index("ix_notifications_created", "created_at"), + ) + + class ContentReport(Base): """ Report of a public content hash for moderation. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js index d36a0a1..4ef334b 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js @@ -85,7 +85,7 @@ function useAuth() { return useContext(AuthContext); } // ── Nav ────────────────────────────────────────────────────────────────────── -function Nav({ user, theme, onThemeToggle, onLogout, onMenuToggle }) { +function Nav({ user, theme, onThemeToggle, onLogout, onMenuToggle, unreadCount }) { return html`