"""Group endpoints — /v1/groups/*""" import re from datetime import UTC, datetime from fastapi import APIRouter, Depends, HTTPException, Query, Request from pydantic import BaseModel from sqlalchemy import func, or_, select, update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from meshbay_hub import hub_settings, mail from meshbay_hub.api.deps import get_current_user, require_user_scope from meshbay_hub.api.middleware import limiter from meshbay_hub.api.netutil import client_ip from meshbay_hub.auth import decrypt_email from meshbay_hub.db.engine import get_db from meshbay_hub.db.models import ( FederatedGroup, Group, GroupMember, IPLog, SwarmSource, User, ) router = APIRouter(prefix="/v1/groups", tags=["groups"]) # Swarm endpoints live at /v1/swarm/*. They were previously declared on the groups # router with a full path, which mounted them at /v1/groups/v1/swarm/* (H7). swarm_router = APIRouter(prefix="/v1/swarm", tags=["swarm"]) @router.get("/mine") async def my_groups( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """List groups the current user belongs to.""" from meshbay_hub.api.revocation import get_online_nodes_for_group result = await db.execute( select(Group, User.username) .join(GroupMember, Group.id == GroupMember.group_id) .join(User, User.id == Group.admin_id) # the owner, for the @handle .where(GroupMember.user_id == current_user.id, Group.status == "active", # A group nobody hosts yet is the owner's business alone. Someone # added to it before a node exists would see a name they cannot # open and cannot be told why. or_(Group.hosted_at.is_not(None), Group.admin_id == current_user.id)) .order_by(Group.last_activity_at.desc()) ) rows = result.all() groups = [g for g, _ in rows] owner_by_id = {g.id: owner for g, owner in rows} muted_rows = await db.execute( select(GroupMember.group_id, GroupMember.muted) .where(GroupMember.user_id == current_user.id)) muted_map = {gid: bool(m) for gid, m in muted_rows.all()} return { "groups": [ { "id": g.id, "name": g.name, "owner_username": owner_by_id.get(g.id), "visibility": g.visibility, "muted": muted_map.get(g.id, False), "join_policy": g.join_policy, "created_at": g.created_at.isoformat(), "is_admin": g.admin_id == current_user.id, "description": g.description or "", # Presence, from the socket registry the hub already keeps for # signaling — so the sidebar gets it on the request it already # makes, with no poll and no timer. It says a node serving this # group is connected *to the hub*; it does not promise this # browser can reach it, and a hub is free to lie about it. The # client downgrades to offline on its own failed connection, # which is the evidence that actually concerns the user. "node_online": bool(get_online_nodes_for_group(g.id)), "hosted": g.hosted_at is not None, "last_activity_at": g.last_activity_at.isoformat(), } for g in groups ] } @router.post("/{group_id}/activity") async def touch_group_activity( group_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """Bump a group's last_activity_at. Called by the client on chat/file events.""" result = await db.execute( select(GroupMember.group_id).where( GroupMember.group_id == group_id, GroupMember.user_id == current_user.id, )) if not result.first(): raise HTTPException(status_code=403, detail="Not a member") await db.execute( update(Group) .where(Group.id == group_id) .values(last_activity_at=datetime.now(UTC))) await db.commit() return {"ok": True} @router.get("/{group_id}/nodes") async def group_online_nodes( group_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """Return online nodes that serve a group (for WebRTC connection).""" from meshbay_hub.api.revocation import get_online_nodes_for_group from meshbay_hub.db.models import Node group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.status != "active": # Name the real state: "suspended" is reversible, "revoked" is a signed # instruction every node enforces. The client shows this string as-is. raise HTTPException(status_code=403, detail=f"Group is {group.status}") # A public group is normally readable by anyone — that is the point of it. # But when the hub has public groups switched off, an existing one keeps # working only for the people already in it: no non-member gets handed a # node to connect to. Members always have a row here, so they are unaffected. # # A **private** group hands its node list to members and to nobody else. It # used to answer any authenticated account that knew the id — which an # ex-member knows for ever — with the ids and public keys of the machines # hosting it. That is the "registered hub user with no membership" of §2.1 # reaching an endpoint that did not check membership, and §7.4 already # states the property for the public case: a non-member is handed no node. # # Nothing legitimate needs this before joining. An open join writes the # membership row first (`POST /{id}/join`), and an invitation registers the # invitee's membership when the code is created — so by the time either asks # for a node, the row exists. if group.visibility != "public" or not await hub_settings.public_groups_allowed(db): if not await db.get(GroupMember, (group_id, current_user.id)): raise HTTPException(status_code=403, detail="Not a member of this group") node_ids = get_online_nodes_for_group(group_id) nodes = [] for nid in node_ids: node = await db.get(Node, nid) if node: nodes.append({"node_id": nid, "pk_node": node.pk_node}) return {"nodes": nodes} @router.get("") async def list_public_groups( db: AsyncSession = Depends(get_db), q: str = Query(default="", max_length=200), # This one takes no authentication at all, and had no upper bound: any # stranger could ask the hub for the entire public directory in a single # query, repeatedly. Bounded like every list in admin.py. limit: int = Query(default=50, ge=1, le=200), offset: int = Query(default=0, ge=0), include_federated: bool = True, ): """List/search public groups — local and optionally federated. No auth required.""" # The hub admin can switch public groups off for the whole instance. When # they have, there is no directory at all — not the local groups that predate # the switch, and not the federated ones a peer still advertises. The switch # is read live, so flipping it back brings the directory straight back. if not await hub_settings.public_groups_allowed(db): return {"groups": [], "total": 0} # Unhosted groups are absent from the directory: until a node announces it, # a group has no files, no key and nothing to connect to, so listing it only # produces a dead end. Its owner still sees it in /mine while they set it up. query = (select(Group, User.username) .join(User, User.id == Group.admin_id) .where(Group.visibility == "public", Group.status == "active", Group.hosted_at.is_not(None))) if q: query = query.where(Group.name.ilike(f"%{q}%")) result = await db.execute( query.order_by(Group.created_at.desc()).limit(limit).offset(offset) ) local = result.all() groups = [ { "id": g.id, "name": g.name, "join_policy": g.join_policy, "owner_username": owner, "description": g.description or "", "created_at": g.created_at.isoformat(), "source": "local", } for g, owner in local ] if include_federated: fed_query = select(FederatedGroup) if q: fed_query = fed_query.where(FederatedGroup.name.ilike(f"%{q}%")) fed_result = await db.execute( fed_query.order_by(FederatedGroup.updated_at.desc()).limit(limit) ) for fg in fed_result.scalars().all(): groups.append({ "id": fg.id, "name": fg.name, "join_policy": fg.join_policy, "updated_at": fg.updated_at.isoformat(), "source": fg.source_hub, }) return {"groups": groups, "total": len(groups)} # ── Swarm (content replication) ─────────────────────────────────────────────── class SwarmRegisterRequest(BaseModel): content_hash: str # blake3 hex endpoint: str # ":" — a port on the caller, never a host # A transport and a port, and deliberately no host. The field used to be free # text documented as "ip:port", so a caller could name *someone else's* # address as a source; nothing dials a swarm source today, which is the only # reason that was not already a reflection primitive. A reader learns where a # node is from the node record, which is stamped with the address the announce # actually came from — so a host here would be a second, weaker, answer to a # question already settled elsewhere. _SWARM_ENDPOINT = re.compile(r"^(webrtc|quic):([0-9]{1,5})$") # One account, this many public hashes. Rows are keyed (hash, account) with no # cap, so a loop of invented hashes was unbounded storage growth on a hub # shared with everyone else. A public library far larger than this is a real # thing — but it is one a hub operator should be asked about, not something a # client establishes by writing rows. MAX_SWARM_HASHES_PER_ACCOUNT = 10_000 @swarm_router.post("/register", status_code=201) @limiter.limit("120/minute") async def swarm_register( body: SwarmRegisterRequest, request: Request, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """ Node registers itself as a source for a PUBLIC content hash. Finding H7: the node registered hashes for every group it hosted, private ones included, and this route was mounted at /v1/groups/v1/swarm/register — so the node's calls 404'd and the leak was masked by a routing bug rather than prevented. Nodes now filter by group visibility before calling, and the path is correct, so the filter has to be right. Availability: the endpoint is a port, not an address, and the number of hashes one account may claim is bounded. See the two constants above. """ from meshbay_hub.csam import check_content_hash if check_content_hash(body.content_hash): raise HTTPException(status_code=451, detail="Content blocked") m = _SWARM_ENDPOINT.match(body.endpoint or "") if not m or not (0 < int(m.group(2)) < 65536): raise HTTPException( status_code=422, detail="endpoint must be ':' — a port on the " "registering node, not an address") from datetime import datetime existing = await db.get(SwarmSource, (body.content_hash, current_user.id)) now = datetime.now(UTC) if existing: existing.endpoint = body.endpoint existing.last_seen = now else: held = (await db.execute( select(func.count()).select_from(SwarmSource) .where(SwarmSource.node_id == current_user.id))).scalar() or 0 if held >= MAX_SWARM_HASHES_PER_ACCOUNT: raise HTTPException( status_code=429, detail="This account already claims the maximum number of " "public content hashes") db.add(SwarmSource( content_hash=body.content_hash, node_id=current_user.id, endpoint=body.endpoint, )) await db.commit() return {"status": "registered", "hash": body.content_hash} @swarm_router.get("/{content_hash}") async def swarm_sources( content_hash: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """ Return nodes that can serve a content hash. Authenticated (H7): an open endpoint lets anyone probe whether a given file exists anywhere in the network and which node holds it. """ from datetime import datetime, timedelta cutoff = datetime.now(UTC) - timedelta(minutes=30) result = await db.execute( select(SwarmSource) .where( SwarmSource.content_hash == content_hash, SwarmSource.last_seen > cutoff, ) ) sources = result.scalars().all() return { "hash": content_hash, "sources": [{"node_id": s.node_id, "endpoint": s.endpoint} for s in sources], } @router.get("/{group_id}/members") async def group_members( group_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") mem = await db.get(GroupMember, (group_id, current_user.id)) if not mem: raise HTTPException(status_code=403, detail="Not a member") result = await db.execute( select(User.id, User.username) .join(GroupMember, User.id == GroupMember.user_id) .where(GroupMember.group_id == group_id, User.status != "deleted") ) members = [{"user_id": uid, "username": uname} for uid, uname in result.all()] return { "group_id": group_id, "admin_id": group.admin_id, "members": members, } @router.post("/{group_id}/join") async def join_group( group_id: str, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.status != "active": raise HTTPException(status_code=403, detail=f"Group is {group.status}") if group.join_policy != "open": raise HTTPException(status_code=403, detail="Group does not allow open joining") if group.visibility == "public" and not await hub_settings.public_groups_allowed(db): # The group predates the switch; open joining is off with it. Existing # members keep their row and their access. raise HTTPException( status_code=403, detail="This hub does not allow joining public groups.") existing = await db.get(GroupMember, (group_id, current_user.id)) if existing: raise HTTPException(status_code=409, detail="Already a member") db.add(GroupMember(group_id=group_id, user_id=current_user.id)) db.add(IPLog(user_id=current_user.id, event="group_join", ip_address=client_ip(request), detail=group.name)) await db.commit() owner = await db.scalar(select(User.username).where(User.id == group.admin_id)) return {"status": "joined", "group_id": group_id, "name": group.name, "owner_username": owner} class GroupCreateRequest(BaseModel): name: str visibility: str = "private" # public|private join_policy: str = "invite" # open (public groups) | invite (private) description: str | None = None MAX_PUBLIC_GROUPS = 10 async def _check_public_group_quota(db: AsyncSession, user: User) -> None: """Refuse an eleventh live public group from the same owner. Public groups are the ones that cost other people something: they appear in Discover and anyone may join them, so a script that opens hundreds fills the directory for everybody. Private groups are invisible to anyone not invited and are not capped. Counted: public, still active, owned by this user. A group suspended by moderation does not hold a slot — the owner is already being dealt with, and keeping the slot occupied would punish them twice. Deleting one frees a slot, since the row is gone. Creation is the only place this can be checked, and deliberately so: PATCH refuses to change visibility at all, so a private group cannot be flipped public behind the cap. **If visibility ever becomes editable, this check has to move with it.** """ if user.role in ("admin", "moderator"): return # the cap is an anti-spam measure, not a rule about operating an instance count = (await db.execute( select(func.count()) .select_from(Group) .where(Group.admin_id == user.id, Group.visibility == "public", Group.status == "active") )).scalar_one() if count >= MAX_PUBLIC_GROUPS: raise HTTPException( status_code=409, detail=f"You already run {count} public groups, which is the limit of " f"{MAX_PUBLIC_GROUPS}. Delete one you no longer use, or create " f"this one as private — private groups are not limited.") @router.post("", status_code=201) async def create_group( body: GroupCreateRequest, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): # Being listed and being open are one question, not two. # # A public group that admits nobody is a contradiction: it is in the # directory, so people find it and then discover they cannot get in. # Admission by request was considered and dropped — between strangers the # only channel is the hub, so the one-time code would travel through the # very party it exists to keep out, and would protect nothing. # # The other way round was accepted until now and should not have been: a # group anyone may join, that nobody can find, is a listing with the listing # removed. Nothing could reach it but a link, and there is no link — joining # goes through the node. The create form no longer offers either # combination; refusing them here is what makes that true of the API too. if body.visibility == "public" and body.join_policy != "open": raise HTTPException( status_code=422, detail="A public group is open to join. Make it private if you " "want to choose who comes in.") if body.visibility != "public" and body.join_policy == "open": raise HTTPException( status_code=422, detail="A private group is invite-only. Make it public if you want " "anyone to be able to join.") name = body.name.strip() if not name: raise HTTPException(status_code=422, detail="A group needs a name.") # One name per owner, case-insensitively. Two *different* owners may each # have a "photos" — that is why the check is scoped to `admin_id` and why # the group's real identity stays its UUID. The DB has a unique index too # (uq_groups_owner_name); this is the friendly error, that is the race # backstop below. clash = await db.scalar( select(Group.id).where( Group.admin_id == current_user.id, func.lower(Group.name) == name.lower())) if clash: raise HTTPException( status_code=409, detail=f"You already have a group called “{name}”. Pick another name " "— names only have to be unique among your own groups.") if body.visibility == "public": if not await hub_settings.public_groups_allowed(db): # Instance policy, set by a hub admin in the panel. Absolute — staff # included — because the way back is to re-enable it, not to slip # past it. A client that still shows the "open" choice lands here. raise HTTPException( status_code=403, detail="This hub does not allow public groups. Create the group " "as private — you can still invite people to it.") await _check_public_group_quota(db, current_user) desc = (body.description or "")[:512] if body.description else None group = Group( name=name, admin_id=current_user.id, visibility=body.visibility, join_policy=body.join_policy, description=desc, ) db.add(group) await db.flush() # get group.id db.add(GroupMember(group_id=group.id, user_id=current_user.id)) db.add(IPLog(user_id=current_user.id, event="group_create", ip_address=client_ip(request), detail=name)) try: await db.commit() except IntegrityError: # Two creates for the same owner+name raced past the check above. await db.rollback() raise HTTPException( status_code=409, detail=f"You already have a group called “{name}”.") await db.refresh(group) return {"group_id": group.id, "name": group.name, "owner_username": current_user.username} @router.delete("/{group_id}/members/{username}") async def remove_group_member( group_id: str, username: str, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): """ Remove someone from a group. The group's owner only. This is half of removing a member, and the half the hub can do: without a membership row they cannot reach the node through signaling, and their next token will not name this group. What it does not do is make the node forget them — the node's roster decides who it serves, and only a paired operator can change that (`member_revoke` over MNP, or `meshbay-node member revoke`). The browser does both; a caller using this endpoint alone should know it did one. """ group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id != current_user.id: raise HTTPException(status_code=403, detail="Only the group owner can remove members") target = (await db.execute( select(User).where(User.username == username))).scalar_one_or_none() if not target: raise HTTPException(status_code=404, detail="User not found") if target.id == group.admin_id: raise HTTPException( status_code=409, detail="The owner cannot be removed from their own group. Hand the " "group over or delete it.") membership = await db.get(GroupMember, (group_id, target.id)) if not membership: raise HTTPException(status_code=404, detail="Not a member of this group") await db.delete(membership) db.add(IPLog(user_id=current_user.id, event="group_leave", ip_address=client_ip(request), detail=f"{username} removed from {group.name}")) await db.commit() return {"status": "removed", "group_id": group_id, "username": username} @router.post("/{group_id}/leave") async def leave_group( group_id: str, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): """ Leave a group you are a member of. Deliberately separate from `DELETE /{group_id}/members/{username}`, which is the owner removing somebody else and is refused to everyone else. Reusing it would have meant relaxing that check for the self case, and an authorization rule with an exception in it is the kind that gets read wrong later. The owner cannot leave: the group would be left with no one able to admit a member, edit it or delete it. That is the same answer the removal endpoint already gives, and the same one account deletion gives while you still own groups — hand the group over (not yet possible) or delete it. This is only the hub's half, exactly as for removal: membership is gone, so signaling will not reach a node and the next token will not name this group. The node keeps what it holds — the identity it pinned, the keypair bundle, and the files uploaded — until its operator unpins them, and whoever left still holds the group key they were served, so the operator should rotate it (`meshbay-node gek-init`) if that matters. """ group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id == current_user.id: raise HTTPException( status_code=409, detail="You own this group, so you cannot leave it — it would be left " "with nobody able to manage it. Delete the group instead.") membership = await db.get(GroupMember, (group_id, current_user.id)) if not membership: raise HTTPException(status_code=404, detail="You are not a member of this group") await db.delete(membership) db.add(IPLog(user_id=current_user.id, event="group_leave", ip_address=client_ip(request), detail=f"left {group.name}")) await db.commit() return {"status": "left", "group_id": group_id} class GroupUpdateRequest(BaseModel): description: str | None = None @router.patch("/{group_id}") async def update_group( group_id: str, body: GroupUpdateRequest, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): """ Change the group's description. Owner only. Only the description: name, visibility and join policy are what members joined on the strength of, and a group that can quietly become public is a different thing from the one they agreed to. Those need a decision about who is told, not a PATCH. """ group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id != current_user.id: raise HTTPException(status_code=403, detail="Only the group owner can edit it") if body.description is not None: desc = body.description.strip()[:512] group.description = desc or None await db.commit() return {"group_id": group.id, "description": group.description or ""} @router.post("/{group_id}/members/{username}", status_code=201) async def add_group_member( group_id: str, username: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): # `get_current_user`, not `require_user_scope`: the node calls this after a # CLI `member invite` so the group becomes visible in the invitee's SPA # (commit 0443cf8). The node authenticates with a node-scoped token, and the # `group.admin_id == current_user.id` check below is the real guard — a node # can only touch its own operator's groups, adding an already-registered # account. (Third-review M6 proposed tightening this to `require_user_scope`; # that broke the CLI invite flow and was reverted — see the review doc.) group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id != current_user.id: raise HTTPException(status_code=403, detail="Only admin can add members") result = await db.execute(select(User).where(User.username == username)) target = result.scalar_one_or_none() if not target: raise HTTPException(status_code=404, detail="User not found") new_member = False 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}", group_id=group_id, ) await db.commit() return {"status": "stored", "group_id": group_id, "username": username} class MuteRequest(BaseModel): muted: bool @router.post("/{group_id}/mute") async def set_group_mute( group_id: str, body: MuteRequest, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): """ Turn this group's notifications on or off, for this account. Server-side on purpose: it used to be a checkbox in the browser's localStorage that nothing ever read, so turning notifications off for a group had no effect anywhere. Now nothing is created in the first place. """ membership = await db.get(GroupMember, (group_id, current_user.id)) if not membership: raise HTTPException(status_code=404, detail="Not a member of this group") membership.muted = body.muted await db.commit() return {"status": "ok", "group_id": group_id, "muted": body.muted} @router.delete("/{group_id}") async def delete_group( group_id: str, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id != current_user.id: raise HTTPException(status_code=403, detail="Only the group creator can delete") from meshbay_hub.db.purge import purge_groups db.add(IPLog(user_id=current_user.id, event="group_delete", ip_address=client_ip(request), detail=group.name)) await purge_groups(db, [group_id]) await db.commit() return {"status": "deleted", "group_id": group_id} # `XXXX-XXXX`, as `roster.generate_code` produces. Checked because this string # is placed in an email the hub sends under its own domain, and the endpoint # used to accept any text at all. _INVITE_CODE = re.compile(r"^[0-9A-Za-z]{4}-[0-9A-Za-z]{4}$") class InviteNotifyRequest(BaseModel): username: str code: str # `group_name` used to be here and went straight into the email's subject # line. The hub knows the group's name — it is reading the row two lines # into the handler — so accepting a second answer only let the sender # choose the subject of a message the hub signs with its own domain. @router.post("/{group_id}/invite-notify") @limiter.limit("20/hour") async def invite_notify( group_id: str, body: InviteNotifyRequest, request: Request, current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): """Send an invitation email to a member who was just invited. The invite code was created on the node — the hub only knows about it because the inviter's browser sends it here. The hub looks up the invitee's encrypted email, decrypts it, and sends the notification. The inviter never sees the email address. Availability: the target is any account on the hub — it has to be, since an invitee is by definition not yet a member — so this is the one endpoint where one user causes mail to be sent to another. It was unmetered and the subject line came from the request. Anyone who created a group, which is to say anyone, could send any registered account arbitrary text from the hub's own domain, as fast as they liked. The rate limit and the two checks below are what keep that from being a phishing kit with the hub's reputation attached. """ group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") if group.admin_id != current_user.id: raise HTTPException(status_code=403, detail="Only the group owner can send invitations") if not _INVITE_CODE.match(body.code or ""): raise HTTPException(status_code=422, detail="Not an invite code") target = (await db.execute( select(User).where(User.username == body.username))).scalar_one_or_none() if not target: raise HTTPException(status_code=404, detail="User not found") email = "" try: email = decrypt_email(target.email) if target.email else "" except Exception: pass if not email: return {"status": "no_email"} try: await mail.send_off_loop( db, mail.send_invite_notification, email, body.code, current_user.username, group.name, purpose="invite") except Exception: return {"status": "send_failed"} return {"status": "sent"}