""" MeshBay Node — WebRTC DataChannel server for browser clients. Browsers cannot use QUIC for NAT traversal (WebTransport doesn't allow choosing the UDP source port — Port-Restricted Cone NAT requires exact port matching). WebRTC DataChannel with ICE/STUN handles this automatically. The MNP protocol (handshake, file_request, file_chunk, chat, etc.) runs identically over WebRTC DataChannel as over QUIC streams. Same E2E encryption, same message types, same msgpack wire format. Wire format on the DataChannel: - Each message is length-prefixed msgpack (4-byte big-endian + msgpack payload) - Same as QUIC streams and TCP+TLS - DataChannel is ordered and reliable (SCTP over DTLS) Signaling flow (handled externally by the hub): Browser → Hub : POST /v1/nodes/{id}/webrtc/offer {sdp, ice_candidates} Hub → Node : WS push {type: "webrtc_offer", sdp, ice_candidates, peer_id} Node → Hub : WS push {type: "webrtc_answer", sdp, ice_candidates, peer_id} Hub → Browser : SSE/response {sdp, ice_candidates} After signaling, DataChannel is P2P — hub is out of the loop. """ import asyncio import base64 import logging import os import re import time import uuid from pathlib import Path from typing import Any from aiortc import RTCDataChannel, RTCPeerConnection, RTCSessionDescription from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey, ) from meshbay_common import MNP_VERSION from meshbay_common.adminop import ( ADMIN_CHALLENGE_TTL, OP_APP_DIRECTORIES, OP_APPS_ENABLED, OP_CHAT_DIRECTORY, OP_CHAT_EPOCH, OP_CHAT_LINK_PREVIEW, OP_DIR_DELETE, OP_FILE_DELETE, OP_GEK_ROTATE, OP_GROUP_ATTACH, OP_GROUP_DETACH, OP_INVITE_CANCEL, OP_INVITE_CREATE, OP_INVITE_LINK_CREATE, OP_MEMBER_REVOKE, OP_MEMBER_UNPIN, OP_MUSICBRAINZ_ENABLED, OP_ROOT_ADD, OP_ROOT_EJECT, OP_ROOT_PLUG, OP_ROOT_REMOVE, OP_ROOT_UPDATE, OP_SEARCH_LISTED, OP_SET_SCAN_SETTINGS, OP_TMDB_CONFIG, OP_TMDB_ENABLED, OP_TMDB_OVERRIDE, OP_TMDB_REMATCH, OP_TRANSFER_LIMITS, admin_transcript, ) from meshbay_common.crypto import pk_to_b64, wrap_gek_aes from meshbay_common.device import ( DEVICE_TTL, device_add_transcript, device_hello_transcript, device_request_transcript, ) from meshbay_common.groupbox import ( PURPOSE_ACK, PURPOSE_ROSTER, seal, ) from meshbay_common.handshake import ( MNP_MIN_SUPPORTED, NONCE_LEN, ROLE_CLIENT, ROLE_NODE, HandshakeError, authorize_token, challenge_transcript, check_version, handshake_transcript, make_proof, verify_proof, webrtc_binding, ) from meshbay_common.join import ( JOIN_TTL, ROLE_MEMBER, ROLE_OPERATOR, join_transcript, ) from meshbay_common.protocol import ( MNP, UPLOAD_PROBE_INDEX, file_upload_ack_wire, file_upload_payload, ) from meshbay_node import ops from meshbay_node import transfers as transfers_mod from meshbay_node import uploads as uploads_mod from meshbay_node.indexer import GroupIndex from meshbay_node.indexer.indexer import DirectoryIndexer # Re-imported under its original name: every call site and existing test in # this module still refers to it as `_probe_video`. The implementation lives # in media_probe.py so the indexer package (imported just above) can call it # too, for index-time enrichment, without a circular import. from meshbay_node.roots import ( SAFE_UPLOAD_NAME, RootSet, _free_name, off_disk, ) from meshbay_node.roster import KIND_ACCOUNT, KIND_LINK from meshbay_node.transfers import TransferSlots from meshbay_node.transport.webrtc.apps.music import MusicMixin from meshbay_node.transport.webrtc.apps.streaming import StreamingMixin from meshbay_node.transport.webrtc.apps.subtitles import SubtitlesMixin from meshbay_node.transport.webrtc.apps.video_meta import VideoMetaMixin from meshbay_node.transport.webrtc.blobs import BlobsMixin from meshbay_node.transport.webrtc.channel import ( _REPLY_TO, _DataChannelBuffer, _extract_dtls_fingerprint, _get_remote_ip, _pack, ) from meshbay_node.transport.webrtc.chat import ChatMixin from meshbay_node.transport.webrtc.files import FilesMixin from meshbay_node.transport.webrtc.limits import LEASE_GRANTED, LEASE_NONE, LEASE_QUEUED, MAX_MSG log = logging.getLogger(__name__) # An invitation link's handle, as `roster.create_link_invite` mints it. _INVITE_ID_RE = re.compile(r"[0-9a-f]{32}") # Upload limits (finding C5a). Uploads used to land directly in the shared root under # a name the client chose, overwriting whatever was already there — which both violated # node sovereignty and defeated the delete authorization (overwrite a file, become its # recorded uploader, then delete it legitimately). # The ceiling is the operator's to set (`max_upload_gb` in node.toml, the Node # page and `meshbay-node transfers max-size`) because it is their disk that # fills: this is only the default a node starts from when they have said # nothing. It is read from the transport context on every chunk, so a change # applies to an upload already in flight. MAX_UPLOAD_BYTES = 8 * 1024 * 1024 * 1024 # 8 GB per file GB_BYTES = 1024 * 1024 * 1024 # Budget for an unauthenticated peer: enough for a handshake and a bundle fetch, # nowhere near enough to be a memory-exhaustion primitive (H6). PRE_HANDSHAKE_MAX_MSG = 64 * 1024 # How many peer connections this node holds at once, and how long one may stay # without completing the MNP handshake. The budget above bounds what *one* # unauthenticated peer costs; these bound how many there may be and how long # each lasts, which is the other half and was missing. The hub caps three # offers in flight per account — a limit on each caller, not on this machine — # so the cost to an operator grew with the number of people in their groups. # Sized to be unreachable in ordinary use: a browser holds one connection per # open group, and a handshake unfinished after a minute is not going to finish. MAX_PEER_SESSIONS = 64 UNAUTHENTICATED_SESSION_TIMEOUT = 60 # seconds # Bundle fetches are served in the pre-proof window (C4). Bounded and audited # until the native client removes remote keypair bundles entirely. MAX_PRE_PROOF_FETCHES = 4 # Pairing codes carry 40 bits and are single-use, but a connection must not be # allowed to sit there guessing. Failures are audited, so a grind is visible. MAX_JOIN_ATTEMPTS = 5 # Per-connection limits alone would not bind an attacker who can open connections # at will — and the adversary who can mint tokens for any account is the hub. So # failed pairings are also counted node-wide over a window. MAX_JOIN_FAILURES_WINDOW = 20 JOIN_FAILURE_WINDOW = 600 # seconds # Everything a member sends lands here: files from the Files panel and # attachments from the chat alike. One visible directory the operator can look # into, back up or empty — rather than a hidden tree of per-user uuids that # nobody could read, or files scattered wherever someone happened to be looking. # How often transfer leases are swept. Nothing depends on it being # prompt -- the session teardown is the reclaim that matters and is # immediate; this catches peers that vanished without the connection # noticing, so it trades latency for a timer that hardly ever runs. TRANSFER_SWEEP_SECS = 15 # Opt-in, off by default: a per-session heartbeat log (message count, time # since the last message, ICE state) and ICE-state-change logging, on top of # the connectionstatechange logging that already runs unconditionally. Added # while chasing a report of the browser side going unresponsive after a # mobile screen lock; --log-level DEBUG was not the right knob for this, # since it is already used for the per-message request/response tracing # every group index lookup produces, and turning that on for days of normal # operation just to catch one intermittent session is not viable. Set # MESHBAY_WEBRTC_TRACE=1 in the node's environment for the duration of a # debugging session. _WEBRTC_TRACE = os.environ.get("MESHBAY_WEBRTC_TRACE") == "1" _WEBRTC_TRACE_INTERVAL_S = 30.0 class WebRTCPeerSession( BlobsMixin, ChatMixin, FilesMixin, StreamingMixin, VideoMetaMixin, MusicMixin, SubtitlesMixin, ): """One WebRTC peer connection, handling MNP over a DataChannel.""" def __init__(self, pc: RTCPeerConnection, node_ctx: dict, peer_id: str = ""): self._pc = pc self._ctx = node_ctx # Every background task this session starts. asyncio keeps only a *weak* # reference to a task, so one that is merely fired and forgotten can be # collected while it is still running — "Task was destroyed but it is # pending!" in the log. For _stream_video that meant its `async with # sem` never reached __aexit__ and the transcode slot was gone for good. # There are two slots: after two abandoned streams the node answered # "Server busy" to everything and no video would start at all. self._tasks: set[asyncio.Task] = set() self._channel: RTCDataChannel | None = None self._buffer = _DataChannelBuffer(max_message=PRE_HANDSHAKE_MAX_MSG) self._pre_proof_fetches = 0 self._user_id: str | None = None self._group_id: str | None = None self._peer_id: str = peer_id self._remote_ip: str = "" self._username: str = "" # This connection's key in the group's peer registry. **Per connection, # never per account**: one person may hold several devices here, and # keying the registry by user_id makes the second evict the first, and # the symptom is invisible: two devices of one account cannot both be # connected, and whichever disconnects takes the other's chat delivery # with it. self._registry_key: str = uuid.uuid4().hex # Set from the roster: the key this node pinned for this account. Never # from the JWT — the hub picks what goes in there. # # This is the account's *oldest* live device unless `device_hello` has # told us better — see _do_device_hello. Treat it as "a device of this # account", not "the device on this connection", anywhere that has not # checked `_device_confirmed`. self._pinned_pk: str = "" # True once this connection proved which device it is. Until then the # node knows the account and not the key, which is all it ever knew # before device linking existed. self._device_confirmed: bool = False # Flow control for video: how many segments the client says it can take. self._stream_credit = 0 self._stream_credit_evt = asyncio.Event() self._stream_stopped = False # When the peer last said anything about this stream. See # _await_stream_credit: silence is what ends a stream, not stinginess. self._stream_heard_at = 0.0 # Diagnostics: how many `stream_more n=0` the peer sent. See # _grant_stream_credit — it tells a paced client from an unpaced one. self._stream_keepalives = 0 # The stream this session currently owns. One viewer plays one film at # a time, so a second request means the first is over — see # _replace_stream for why waiting for it to time out is not an option. self._stream_task: asyncio.Task | None = None # Diagnostics only: when the current stream began and how far it got. self._stream_started_at: float = 0.0 self._stream_segments: int = 0 self._gek_challenge: bytes | None = None # Same value as the GEK challenge, but kept for the life of the connection: # a join_request is signed over it, and it must stay verifiable after the # handshake clears the challenge (an operator pairs while already connected). self._nonce_node: bytes = b"" self._join_attempts = 0 self._nonce_client: bytes = b"" self._admin_ops: dict[str, dict] = {} # op_id → pending admin operation # Uploads in progress live in the group context, not here: see # `_partial_uploads` and `uploads.py`. # # Leaseless reads, though, *are* this connection's: the bound is on what # one session may do while claiming to be browsing, not a pool shared # between them. Three tabs open is browsing in three tabs. self._leaseless = transfers_mod.LeaselessReads() # Whether this session has already been noted as transferring under a # lease the node does not have (see `_note_unleased`). One line per # connection, not per chunk. self._unleased_noted = False # Diagnostics only (_WEBRTC_TRACE): when the last DataChannel message # arrived, so the heartbeat can report silence duration. self._last_msg_at: float = 0.0 def _setup_channel(self, channel: RTCDataChannel) -> None: self._channel = channel self._msg_count = 0 @channel.on("message") def on_message(message): if isinstance(message, str): message = message.encode() self._msg_count += 1 self._last_msg_at = time.monotonic() if self._msg_count <= 3: log.info("WebRTC data received: %d bytes, msg #%d (peer=%s)", len(message), self._msg_count, self._peer_id) self._buffer.feed(message) for msg in self._buffer.messages(): self._handle_message(msg) if _WEBRTC_TRACE: self._spawn(self._trace_heartbeat()) async def _trace_heartbeat(self) -> None: """Diagnostics only (_WEBRTC_TRACE): periodic proof-of-life for this session, so a gap in these lines pinpoints when the node stopped hearing from a peer that (from its own side) may still look connected.""" while True: await asyncio.sleep(_WEBRTC_TRACE_INTERVAL_S) silence = time.monotonic() - self._last_msg_at if self._last_msg_at else -1 log.info( "WebRTC heartbeat peer=%s msgs=%d silence=%.0fs pc=%s ice=%s", self._peer_id, self._msg_count, silence, self._pc.connectionState, self._pc.iceConnectionState, ) def _handle_message(self, msg: dict) -> None: """Answer one MNP message, under the correlation id it carries. The id is published for the whole handler — see _REPLY_TO — so that every reply _send puts on the wire, including the ones a spawned task sends much later and the generic refusal below, names the request it answers. Resetting on the way out only clears it for *this* call: a task spawned in between captured its own copy of the context when it was created and keeps answering under the right id. """ token = _REPLY_TO.set((self, msg.get("req_id"))) try: self._dispatch_message(msg) finally: _REPLY_TO.reset(token) def _dispatch_message(self, msg: dict) -> None: mtype = msg.get("type") log.debug("WebRTC recv: %s", mtype) try: if mtype == MNP.HANDSHAKE: self._do_handshake(msg) elif mtype == MNP.HANDSHAKE_RESPONSE: self._do_handshake_response(msg) elif mtype in (MNP.GEK_BUNDLE_FETCH, MNP.KEYPAIR_BUNDLE_FETCH) \ and self._gek_challenge is not None: # Served before the GEK proof by necessity: the client needs its # wrapped bundle in order to compute the proof. That window is a # disclosure surface (C4) — a hub that forges a JWT reaches it — so # it is bounded and audited here, and closed properly when clients # stop storing keypair bundles on other people's nodes. self._pre_proof_fetches += 1 if self._pre_proof_fetches > MAX_PRE_PROOF_FETCHES: self._audit_auth_failed( getattr(self, "_pending_group", ""), "pre-proof fetch flood") self._send({"type": "error", "detail": "Too many requests"}) return self._audit_pre_proof_fetch(mtype) if mtype == MNP.GEK_BUNDLE_FETCH: self._spawn(self._do_gek_bundle_fetch()) else: self._spawn(self._do_keypair_bundle_fetch()) elif mtype == MNP.JOIN_REQUEST and self._nonce_node: # Valid both before the GEK proof (a new member has no GEK to prove # with) and after it (an operator pairing a browser is already # connected). Authority comes from the pairing code and the # signature, never from the session state. self._spawn(self._do_join_request(msg)) elif self._user_id is None: self._send({"type": "error", "detail": "Handshake required"}) elif mtype == MNP.INDEX_SYNC: self._do_index_sync() elif mtype == MNP.FILE_REQUEST: # Spawned rather than answered inline: the reply waits for room # on the channel, and blocking the message loop for that would # stop everything else this peer is doing — including the # uploads whose acks free the very buffer we are waiting on. # Chunks are matched by file and index on the client, so # answering out of order is safe. self._spawn(self._do_file_request(msg)) elif mtype == MNP.CHAT_MESSAGE: self._do_chat_message(msg) elif mtype == MNP.CHAT_HISTORY: self._do_chat_history(msg) elif mtype == MNP.LINK_PREVIEW_REQ: self._spawn(self._do_link_preview_request(msg)) elif mtype == MNP.PING: self._do_ping(msg) elif mtype == MNP.TRANSFER_OPEN: self._do_transfer_open(msg) elif mtype == MNP.TRANSFER_CLOSE: self._do_transfer_close(msg) elif mtype == MNP.FILE_UPLOAD: self._spawn(self._do_file_upload(msg)) elif mtype == MNP.DIR_CREATE: self._spawn(self._do_dir_create(msg)) elif mtype == MNP.DIR_DELETE: self._spawn(self._do_dir_delete(msg)) elif mtype == MNP.FILE_DELETE: self._do_file_delete(msg) elif mtype == MNP.ADMIN_RESPONSE: self._do_admin_response(msg) elif mtype == MNP.INVITE_CREATE: self._do_invite_create(msg) elif mtype == MNP.INVITE_LINK_CREATE: self._do_invite_link_create(msg) elif mtype == MNP.INVITE_CANCEL: self._do_invite_cancel(msg) elif mtype == MNP.MEMBER_REVOKE: self._do_member_revoke(msg) elif mtype == MNP.DEVICE_REQUEST: self._spawn(self._do_device_request(msg)) elif mtype == MNP.DEVICE_LOOKUP: self._spawn(self._do_device_lookup(msg)) elif mtype == MNP.DEVICE_ADD: self._spawn(self._do_device_add(msg)) elif mtype == MNP.DEVICE_LIST: self._spawn(self._do_device_list(msg)) elif mtype == MNP.DEVICE_REVOKE: self._spawn(self._do_device_revoke(msg)) elif mtype == MNP.DEVICE_HELLO: self._spawn(self._do_device_hello(msg)) elif mtype == MNP.APPS_ENABLED: self._do_apps_enabled(msg) elif mtype == MNP.TRANSFER_LIMITS: self._do_transfer_limits(msg) elif mtype == MNP.SET_SCAN_SETTINGS: self._do_set_scan_settings(msg) elif mtype == MNP.TMDB_CONFIG: self._do_tmdb_config(msg) elif mtype == MNP.TMDB_ENABLED: self._do_tmdb_enabled(msg) elif mtype == MNP.APP_DIRECTORIES: self._do_app_directories(msg) elif mtype == MNP.CHAT_DIRECTORY: self._do_chat_directory(msg) elif mtype == MNP.CHAT_LINK_PREVIEW: self._do_chat_link_preview(msg) elif mtype == MNP.SEARCH_LISTED: self._do_search_listed(msg) elif mtype == MNP.CHAT_EPOCH: self._do_chat_epoch(msg) elif mtype == MNP.CHAT_KEYS_REQ: self._spawn(self._do_chat_keys_req(msg)) elif mtype == MNP.GROUP_ROSTER_REQ: self._spawn(self._do_group_roster_req(msg)) elif mtype == MNP.MEDIA_META_REQ: self._spawn(self._do_media_meta_request(msg)) elif mtype == MNP.SEASON_META_REQ: self._spawn(self._do_season_meta_request(msg)) elif mtype == MNP.TMDB_SEARCH_REQ: self._spawn(self._do_tmdb_search_request(msg)) elif mtype == MNP.TMDB_OVERRIDE: self._do_tmdb_override(msg) elif mtype == MNP.TMDB_REMATCH: self._do_tmdb_rematch(msg) elif mtype == MNP.MUSICBRAINZ_ENABLED: self._do_musicbrainz_enabled(msg) elif mtype == MNP.MUSIC_META_REQ: self._spawn(self._do_music_meta_request(msg)) elif mtype == MNP.AUDIO_TRANSCODE_REQ: self._spawn(self._do_audio_transcode_request(msg)) elif mtype == MNP.SUBTITLE_REQ: self._spawn(self._do_subtitle_request(msg)) elif mtype == MNP.MEMBER_UNPIN: self._do_member_unpin(msg) elif mtype == MNP.GEK_ROTATE: self._do_gek_rotate(msg) elif mtype == MNP.NODE_STATUS: self._spawn(self._do_node_status(msg)) elif mtype == MNP.ROOT_ADD: self._do_root_add(msg) elif mtype == MNP.ROOT_REMOVE: self._do_root_remove(msg) elif mtype == MNP.ROOT_UPDATE: self._do_root_update(msg) elif mtype == MNP.ROOT_EJECT: self._do_root_eject(msg) elif mtype == MNP.ROOT_PLUG: self._do_root_plug(msg) elif mtype == MNP.ROSTER_READ: self._spawn(self._do_roster_read(msg)) elif mtype == MNP.DENYLIST_READ: self._spawn(self._do_denylist_read(msg)) elif mtype == MNP.DENYLIST_CLEAR: self._spawn(self._do_denylist_clear(msg)) elif mtype == MNP.GROUP_ATTACH: self._do_group_attach(msg) elif mtype == MNP.GROUP_DETACH: self._do_group_detach(msg) elif mtype == MNP.NODE_SETTINGS_SET: self._spawn(self._do_node_settings_set(msg)) elif mtype == MNP.NODE_RELOAD: self._spawn(self._do_node_reload(msg)) elif mtype == MNP.KEYPAIR_BUNDLE_STORE: self._spawn(self._do_keypair_bundle_store(msg)) elif mtype == MNP.KEYPAIR_BUNDLE_DELETE: self._spawn(self._do_keypair_bundle_delete()) elif mtype == MNP.USER_BLOB_STORE: self._spawn(self._do_user_blob_store(msg)) elif mtype == MNP.USER_BLOB_FETCH: self._spawn(self._do_user_blob_fetch(msg)) elif mtype == MNP.USER_BLOB_LIST: self._spawn(self._do_user_blob_list()) elif mtype == MNP.USER_BLOB_DELETE: self._spawn(self._do_user_blob_delete(msg)) elif mtype == MNP.STREAM_REQUEST: sem = self._ctx.get("_transcode_sem") log.info("stream: req file=%s credits=%s slots_free=%s prev=%s", str(msg.get("file_id"))[:12], msg.get("credits"), getattr(sem, "_value", "?"), "alive" if (self._stream_task and not self._stream_task.done()) else "none") self._spawn(self._replace_stream(msg)) elif mtype == MNP.STREAM_MORE: self._grant_stream_credit(msg) elif mtype == "client_diag": # Diagnostics only. The node acts on none of it — it writes it # next to its own view of the same stream, which is the only # place the two halves can be compared when the client is a # phone with no console. # Every field is peer-controlled, so each is stringified and # cut short: this is a log line, not a channel for writing # whatever one likes into the operator's file. def _f(key: str, n: int = 24) -> str: return str(msg.get(key))[:n].replace("\n", " ") if msg.get("event"): # Once per stream or per seek, not once per five seconds — # and a seek nobody asked for looks exactly like a viewer # dragging the scrubber from this side, so it has to be # visible without turning DEBUG on. log.info( "stream: client %s target=%s t=%ss offset=%s ready=%s " "duration=%s ranges=[%s]", _f("event", 16), _f("target"), _f("t"), _f("offset"), _f("ready"), _f("duration"), _f("ranges", 120)) # Debug: one line every five seconds per viewer. Run the daemon # with --log-level debug to see inside a player that is # misbehaving — it is the only view of the browser there is # when the browser is a phone. else: # `ahead` on its own cannot say whether a short buffer is # the player's own gate holding or the network failing to # keep up, and those two want opposite answers. `limit` is # what the gate is set to for this film and `budget` the # byte budget it was derived from, so the three read as one # sentence. log.debug( "stream: client t=%ss ahead=%ss/%ss budget=%sMB " "ready=%s paused=%s " "stalled=%s q=%s inflight=%s appending=%s updating=%s " "quota=%s ms=%s err=%s ranges=[%s] (sent=%d)", _f("t"), _f("ahead"), _f("limit"), _f("budgetMB"), _f("ready"), _f("paused"), _f("stalled"), _f("q"), _f("inflight"), _f("appending"), _f("updating"), _f("quota"), _f("ms"), _f("err", 80), _f("ranges", 120), self._stream_segments) elif mtype == MNP.STREAM_STOP: age = (time.monotonic() - self._stream_started_at if self._stream_started_at else -1) log.info("stream: stop received %.1fs after start, %d segments sent", age, self._stream_segments) self._stop_stream() else: log.warning("Unknown MNP message type on DataChannel: %s", mtype) except Exception as e: # Log the detail locally; send the peer a generic message. Exception # text here carries filesystem paths and internal state (finding L3). log.error("Error handling %s on DataChannel: %s", mtype, e, exc_info=True) self._send({"type": "error", "detail": "Request failed"}) def _audit(self, event: str, detail: str = "") -> None: audit = self._ctx.get("audit_store") if audit and self._user_id: if not self._remote_ip: self._remote_ip = _get_remote_ip(self._pc) self._spawn(audit.log_event( user_id=self._user_id, event=event, ip=self._remote_ip, username=self._username, group_id=self._group_id or "", detail=detail, )) def _channel_binding(self) -> bytes: """Both DTLS fingerprints, so a proof is valid on this connection only.""" offer_fp = b"" answer_fp = b"" if self._pc.remoteDescription: offer_fp = _extract_dtls_fingerprint(self._pc.remoteDescription.sdp) if self._pc.localDescription: answer_fp = _extract_dtls_fingerprint(self._pc.localDescription.sdp) if not offer_fp or not answer_fp: return b"" return webrtc_binding(offer_fp, answer_fp) def _do_handshake(self, msg: dict) -> None: group_id = msg.get("group_id", "") log.info("WebRTC handshake request: group=%s (peer=%s)", group_id[:8] if group_id else "none", self._peer_id) # Before the token, and before anything is decided from it: a peer we # cannot speak to is refused with a code it can act on, rather than # served messages it will misread as missing fields (L2). try: check_version(msg.get("v", ""), msg.get("v_min", "")) except HandshakeError as refusal: self._send({"type": "error", "detail": str(refusal), "code": refusal.code}) return try: peer = authorize_token( msg.get("token", ""), self._ctx["hub_pk_pem"], group_id=group_id, hosted_groups=self._ctx.get("groups"), denylist=self._ctx.get("denylist"), ) except HandshakeError as refusal: # HandshakeError messages are authored to be peer-safe, unlike arbitrary # exception text (L3) — the client needs to know *why* it was refused. self._send({"type": "error", "detail": str(refusal), "code": getattr(refusal, "code", "")}) self._audit_auth_failed(group_id, str(refusal)) return try: self._nonce_client = base64.b64decode(msg.get("nonce", "")) except Exception: self._nonce_client = b"" if len(self._nonce_client) < NONCE_LEN: # The client nonce is what makes the NODE's proof fresh (C3). Without # it a recorded ack could be replayed by an impersonating peer. self._send({"type": "error", "detail": "Client nonce required"}) return # Decoded, but NOT authenticated: that happens on the GEK proof. self._pending_sub = peer.user_id self._pending_group = peer.group_id self._pending_username = peer.username gctx = self._ctx["groups"][peer.group_id] if "groups" in self._ctx else self._ctx if not gctx.get("gek"): log.warning("Handshake refused — no GEK for group=%s", peer.group_id[:8]) self._send({ "type": "error", "detail": "Group encryption not initialized — contact node operator", }) return self._gek_challenge = os.urandom(NONCE_LEN) self._nonce_node = self._gek_challenge log.info("WebRTC handshake challenge sent (peer=%s)", self._peer_id) self._send({ "type": MNP.HANDSHAKE_CHALLENGE, "v": MNP_VERSION, # Our half of the range. The client refuses us on this rather than # discovering the mismatch when a field it expected is not there. "v_min": MNP_MIN_SUPPORTED, "nonce": base64.b64encode(self._gek_challenge).decode(), # Announced here because a first-time joiner needs it *before* the # ack: join_request signs a transcript naming this node, and someone # who has never held the GEK cannot complete the handshake to learn # it. Unverified at this point — the ack proves it, the client checks # the two match, and a wrong value only makes our own verification # fail. It is never a substitute for the ack's proof and signature. "node_pk": self._node_pk_b64(), # ...except that since 3.4 it is signed, so a client that already # knows which key to expect can check it before it sends a code. **self._challenge_sig(peer.group_id, self._channel_binding()), }) def _challenge_sig(self, group_id: str, binding: bytes) -> dict: """ `{"sig": ...}` over the challenge transcript, or nothing (MNP 3.4). What makes `node_pk` above more than an announcement: a client about to send an invitation code can check this node holds the key it was told to expect, before the code leaves. No binding means no signature rather than an unbound one — a signature that is not tied to the channel is one somebody can relay, and the handshake proof refuses that case anyway. """ if not binding: return {} transcript = challenge_transcript( group_id, self._nonce_client, self._gek_challenge, binding) return {"sig": base64.b64encode(self._ctx["sk_node"].sign(transcript)).decode()} def _do_handshake_response(self, msg: dict) -> None: if not self._gek_challenge or not hasattr(self, "_pending_sub"): self._send({"type": "error", "detail": "No pending handshake challenge"}) return group_id = self._pending_group gctx = self._ctx["groups"][group_id] if "groups" in self._ctx else self._ctx gek = gctx.get("gek") if not gek: self._send({"type": "error", "detail": "Group encryption not initialized"}) self._gek_challenge = None return try: proof_bytes = base64.b64decode(msg.get("proof", "")) except Exception: self._send({"type": "error", "detail": "Invalid proof encoding"}) return binding = self._channel_binding() if not binding: # Refuse rather than fall back to an unbound proof (L4). self._send({"type": "error", "detail": "Channel binding unavailable"}) self._gek_challenge = None self._audit_auth_failed(group_id, "no channel binding") return if not verify_proof(gek, proof_bytes, ROLE_CLIENT, group_id, self._nonce_client, self._gek_challenge, binding): self._send({"type": "error", "detail": "GEK proof failed"}) self._gek_challenge = None self._audit_auth_failed(group_id, "GEK HMAC mismatch") return self._complete_handshake(gek, binding) self._gek_challenge = None def _complete_handshake(self, gek: bytes, binding: bytes) -> None: # Authenticated peers may send large frames (file uploads); unauthenticated # ones may not (H6). self._buffer.max_message = MAX_MSG self._user_id = self._pending_sub self._group_id = self._pending_group self._username = self._pending_username self._spawn(self._load_pinned_pk()) self._register_peer() node_user_id = self._ctx.get("node_user_id") log.info("WebRTC handshake OK — user=%s group=%s", self._user_id[:8], self._group_id[:8] if self._group_id else "none") # The node proves itself too (C3): possession of the GEK over the client's # nonce, plus a signature over the same transcript with its long-term key. # Previously the client received an unverifiable node_pk and trusted # is_node_admin from whoever answered — so a peer that had hijacked # signaling could serve a forged index, chat history and permissions. node_transcript = handshake_transcript( ROLE_NODE, self._group_id or "", self._nonce_client, self._gek_challenge or b"", binding) node_proof = make_proof( gek, ROLE_NODE, self._group_id or "", self._nonce_client, self._gek_challenge or b"", binding) # Everything the client needs in order to *authenticate* us stays in clear — # node_pk, proof and sig are what it checks before it would trust a # decryption, so they cannot themselves be behind one. The configuration # below is sealed under a GEK-derived subkey, which gives it an # authentication tag from a key the hub does not hold. Until MNP 1.0 the # signed transcript named no ack field at all, so is_node_admin, # enabled_apps, the app directories and the rest were authenticated by DTLS # channel and nothing else. config = { "is_node_admin": self._is_node_admin(), # Which group "applications" to show. Absent/empty falls back to # every registered one client-side, so a node that predates this # setting (or one whose context has not loaded it yet) hides # nothing. "enabled_apps": list(self._group_ctx().get("enabled_apps") or []), # Read once and kept current in place by the signed op, and # surfaced here rather than only via tmdb_enabled_ack, so a client # that connects after the operator configured it does not have to # wait for a live change to find out. "tmdb_enabled": bool(self._group_ctx().get("tmdb_enabled", True)), # Token/language stay node-wide (one shared credential/cache) — # via daemon_state, kept current by tmdb_config_ack. "tmdb_token_customized": bool( self._ctx.get("daemon_state", {}).get("tmdb_token_customized", False)), "tmdb_language": str( self._ctx.get("daemon_state", {}).get("tmdb_language") or ""), # Music app (docs/MESHBAY_DESIGN.md §9.8) — same shape as the TMDB # fields above. No language field: MusicBrainz search doesn't # take one the way TMDB does. "musicbrainz_enabled": bool(self._group_ctx().get("musicbrainz_enabled", True)), # Every app's configured folders — `_directories`, keyed by # the app's own registry name, always a list. Built by daemon.py's # `_app_directories_ctx`, and the only form on the wire: the # `video_root` / `audio_root` / `photo_roots` scalars that used to # ride here are gone. One folder was never the general case, and two # spellings of one answer meant whichever the reader consulted first # decided it. # # `chat_directory` below is the one surviving second name, and it is # safe for the reason those were not: it is *derived* from this list # on every build rather than stored beside it, so the two cannot # drift apart. **self._app_directories_ack(), # Where chat attachments are written — the singular form, because # Chat genuinely has one destination. "" means the operator has not # chosen, and the paperclip says so. "chat_directory": self._group_ctx().get("chat_directory") or "", # Whether the node unfurls links members post here. Absent means # on, which is what it did before this existed. "chat_link_preview": bool( self._group_ctx().get("chat_link_preview", True)), # Whether the reader's cross-group Search should list this group. # Presentation only: the index below is served to Search and to the # group page alike, and this cannot tell them apart. Sealed like the # rest, so the hub cannot flip it. Absent means listed. "search_listed": bool(self._group_ctx().get("search_listed", True)), # Which chat epoch key a client should be sealing under. Inside # the sealed part of the ack like every other configuration field, # so it carries an authentication tag from a key the hub does not # hold — a forged epoch would have a client sealing under a key the # group has retired. # # No `chat_encrypted` beside it: there is no switch. A peer that # reached this point speaks MNP 2.0, and 2.0 has no plaintext chat. "chat_epoch": int(self._group_ctx().get("chat_epoch", 0) or 0), # This member's own transfer caps in this group, so the interface # can say "2 of 2 of your slots are busy" rather than draw a bare # spinner. Absent reads as "no limit known" and the hint is simply # not drawn — never as "unlimited", which would have the interface # contradicting the node. "transfer_limits": { "download": self._slots().member_cap( transfers_mod.DOWNLOAD, (self._group_id or "", self._user_id or "")), "upload": self._slots().member_cap( transfers_mod.UPLOAD, (self._group_id or "", self._user_id or "")), }, # So a client that connects mid-scan shows the indexing state # immediately, instead of waiting for the next periodic # INDEX_PROGRESS push. Never a path or filename — see # IndexProgress in indexer.py. "indexing": self._indexing_status(), # Current values only — not enforced from here, just shown to # the operator in Settings so the number on screen matches what # the indexer is actually doing (set_scan_settings, ops.py). "scan_settings": { "reconcile_interval_secs": self._group_ctx().get( "reconcile_interval_secs", DirectoryIndexer.DEFAULT_RECONCILE_SECS), "debounce_secs": self._group_ctx().get( "debounce_secs", DirectoryIndexer.DEFAULT_DEBOUNCE_SECS), }, } if node_user_id: config["node_user_id"] = node_user_id pk_x_b64 = self._ctx.get("pk_x25519_b64") if pk_x_b64: config["node_pk_x25519"] = pk_x_b64 ack = { "type": MNP.HANDSHAKE_ACK, "v": MNP_VERSION, "node_pk": pk_to_b64(self._ctx["sk_node"].public_key()), "proof": base64.b64encode(node_proof).decode(), "sig": base64.b64encode( self._ctx["sk_node"].sign(node_transcript)).decode(), **seal(gek, PURPOSE_ACK, MNP.HANDSHAKE_ACK, self._group_id or "", config), } self._send(ack) self._audit("handshake") # Someone is here now — reconcile's backstop should be prompt again # rather than however far its backoff had stretched while nobody # was connected (indexer.py DirectoryIndexer.note_activity). note_activity = self._group_ctx().get("note_activity") if note_activity: note_activity() def _do_invite_create(self, msg: dict) -> None: """ Issue a one-time pairing code for someone the operator wants to admit. Replaces the old invite path, where the inviter fetched the invitee's public key from the hub and wrapped the group key for whatever came back (H3). The node now needs nothing but a name: it will wrap the key itself, later, for a key the invitee proves they hold. """ roster = self._ctx.get("roster") if roster is None: self._send({"type": "error", "detail": "Roster not available"}) return invitee_id = msg.get("user_id", "") group_id = msg.get("group_id") or self._group_id if not invitee_id or not group_id: self._send({"type": "error", "detail": "Missing user_id or group_id"}) return if group_id != self._group_id: self._send({"type": "error", "detail": "Wrong group for this session"}) return if not self._has_admin_authority(): self._send({ "type": "error", "detail": "No operator paired — run `meshbay-node operator pair`", }) return self._issue_admin_challenge(OP_INVITE_CREATE, invitee_id, { "group_id": group_id, "user_id": invitee_id, "username": str(msg.get("username", ""))[:64], }) def _do_invite_link_create(self, msg: dict) -> None: """ Issue a code bound to no account, for an invitation link — into the group this connection authenticated to, and no other: a link names its group, so the operator signs for exactly that one (docs/MESHBAY_DESIGN.md §3.4). """ group_id = self._group_id or "" if not group_id: self._send({"type": "error", "detail": "No group on this connection"}) return if msg.get("group_id") and msg["group_id"] != group_id: self._send({"type": "error", "detail": "Wrong group for this session"}) return if not self._has_admin_authority(): self._send({ "type": "error", "detail": "No operator paired — run `meshbay-node operator pair`", }) return self._issue_admin_challenge( OP_INVITE_LINK_CREATE, f"link:{group_id}", {"group_id": group_id}) def _do_invite_cancel(self, msg: dict) -> None: """Take back an unredeemed link of this group, by its handle.""" group_id = self._group_id or "" invite_id = str(msg.get("invite_id", "")) if not group_id: self._send({"type": "error", "detail": "No group on this connection"}) return if not _INVITE_ID_RE.fullmatch(invite_id): self._send({"type": "error", "detail": "Not an invitation id"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_INVITE_CANCEL, invite_id, {"group_id": group_id, "invite_id": invite_id}) # ── Per-account blobs (playlists, docs/playlists.md §8.2) ──────────────── # # The node stores bytes it cannot read and hands them back. `self._user_id` # comes from the authenticated session and never from the message: a # `user_id` in the body would let any member of this group read or # overwrite any other member's blob, which is finding C5 one size down. # ── Pairing and join (H3, M3) ──────────────────────────────────────────── def _join_refuse(self, reason: str, audit_detail: str = "") -> None: self._join_attempts += 1 # Node-wide window, shared across connections: reconnecting must not reset # the budget. now = time.time() failures = [t for t in self._ctx.get("join_failures", []) if now - t < JOIN_FAILURE_WINDOW] failures.append(now) self._ctx["join_failures"] = failures self._audit_join("join_refused", audit_detail or reason) self._send({ "type": MNP.JOIN_RESULT, "v": MNP_VERSION, "ok": False, "reason": reason, }) def _audit_join(self, event: str, detail: str) -> None: audit = self._ctx.get("audit_store") if not audit: return self._remote_ip = self._remote_ip or _get_remote_ip(self._pc) self._spawn(audit.log_event( user_id=self._user_id or getattr(self, "_pending_sub", "unknown"), event=event, ip=self._remote_ip, username=self._username or getattr(self, "_pending_username", ""), group_id=self._group_id or getattr(self, "_pending_group", "") or "", detail=detail, )) async def _do_join_request(self, msg: dict) -> None: """ Pin an identity, or recognise one already pinned. The client signs its own Ed25519 and X25519 keys together with the node's nonce, so the identity key vouches for the encryption key — that is what will make it safe for the node to wrap the GEK for a key that arrived over the wire instead of one fetched from the hub's directory (H3). A first pairing needs a one-time code, which the hub never sees. Afterwards the pin is the credential and a changed key is refused outright, the same rule the client applies to `pk_node` (11.5.8). """ roster = self._ctx.get("roster") if roster is None: self._send({"type": "error", "detail": "Roster not available"}) return if self._join_attempts >= MAX_JOIN_ATTEMPTS: self._send({"type": "error", "detail": "Too many attempts"}) return now = time.time() recent = [t for t in self._ctx.get("join_failures", []) if now - t < JOIN_FAILURE_WINDOW] if len(recent) >= MAX_JOIN_FAILURES_WINDOW: self._audit_join("join_throttled", f"{len(recent)} failures in window") self._send({"type": "error", "detail": "Pairing temporarily locked"}) return user_id = self._user_id or getattr(self, "_pending_sub", "") username = self._username or getattr(self, "_pending_username", "") if not user_id: self._send({"type": "error", "detail": "Handshake required"}) return pk_ed_b64 = msg.get("pk_ed25519", "") pk_x_b64 = msg.get("pk_x25519", "") code = msg.get("code", "") ts = msg.get("ts", 0) try: pk_ed_raw = base64.b64decode(pk_ed_b64) pk_x_raw = base64.b64decode(pk_x_b64) if len(pk_ed_raw) != 32 or len(pk_x_raw) != 32: raise ValueError pk_ed = Ed25519PublicKey.from_public_bytes(pk_ed_raw) except Exception: self._join_refuse("invalid_keys") return if not isinstance(ts, int) or abs(time.time() - ts) > JOIN_TTL: self._join_refuse("stale_request") return # An empty group_id means operator pairing, which is node-wide. Anything # else must be the group this connection authenticated to — a signature # obtained for one group must not name another. group_id = msg.get("group_id", "") or "" session_group = self._group_id or getattr(self, "_pending_group", "") or "" if group_id and group_id != session_group: self._join_refuse("group_mismatch") return transcript = join_transcript( node_pk_b64=self._node_pk_b64(), group_id=group_id, user_id=user_id, pk_ed25519_b64=pk_ed_b64, pk_x25519_b64=pk_x_b64, nonce_node=self._nonce_node, ts=ts, ) try: sig = base64.b64decode(msg.get("sig", "")) except Exception: self._join_refuse("invalid_signature_encoding") return if not self._verify_sig(pk_ed, transcript, sig): self._join_refuse("signature_invalid") return # One person may hold several devices here — a browser and a desktop # client are two keys on one account. So the question is not "is this # THE key" but "is this ONE OF this account's live devices". device = await roster.find_device(user_id, pk_ed_b64) if device and device["pk_x25519"] != pk_x_b64: # The Ed25519 key is pinned but arrives with a different encryption # key. The join transcript signs both together, so this is either a # client that regenerated half its identity or something splicing # two messages; either way the pair is not the one admitted. self._join_refuse( "key_changed", f"pinned x25519={device['pk_x25519'][:16]} presented={pk_x_b64[:16]}") return known = device if not known and await roster.list_devices(user_id): # The account is known here but this key is not one of its devices. # Not an error to shout about: it is a second browser or a new # client, and the way in is a device-add approved by a device that # is already trusted — no operator, no new invitation code. self._join_refuse( "unknown_device", f"presented={pk_ed_b64[:16]} — approve it from a device already " f"paired with this node") return if known: # This group's own row first; then the join message's group_id (empty # on the node-wide first connect); then the operator's node-wide row, # which is where an operator opening any group finds their authority. member = (await roster.get_member(session_group, user_id) or await roster.get_member(group_id, user_id) or await roster.get_member("", user_id)) if not member and self._group_join_policy(session_group) == "open": await roster.set_member( group_id=session_group, user_id=user_id, role=ROLE_MEMBER, status="active", approved_by="open-join", ) member = await roster.get_member(session_group, user_id) # A pending invite means the operator explicitly re-invited this # person — require the code even if they already have a member # row (e.g. they left and were re-invited, or were revoked then # re-invited). Without this gate a stale roster row lets them # back in without proving they received the new code. pending_invite = any( i["kind"] == KIND_ACCOUNT and i["user_id"] == user_id and i["group_id"] in (session_group, "") for i in await roster.list_invites()) # Or they bring a link for this group: somebody already pinned here # through another group, which is the ordinary case for a link, or # somebody removed from it and invited back. Only when they are not # an active member — a member opening the group leaves the link for # whoever it was meant for. active = bool(member) and member.get("status") == "active" if pending_invite or (code and not active): if not code: self._join_refuse("code_required") return invite = await roster.consume_invite(code, user_id, session_group) if not invite: self._join_refuse("code_invalid") return await roster.set_member( group_id=invite["group_id"], user_id=user_id, role=invite["role"], status="active", approved_by=invite["created_by"], ) self._audit_join( "join_pinned", f"group={invite['group_id'][:8]} role={invite['role']} " f"via={'link' if invite['kind'] == KIND_LINK else 'code'} " "(device already known)") member = (await roster.get_member(session_group, user_id) or await roster.get_member(invite["group_id"], user_id)) if not member: self._join_refuse("not_authorized_for_group") return await self._join_ok( user_id, pk_x_raw, session_group, role=member["role"] if member else "", recognised=True, ) return if not code: if self._group_join_policy(session_group) == "open": # An open-join group admits anyone the hub calls a member, so a # code would protect nothing — the hub can walk in through the # front door. Pin what turns up and say so in the audit log. await self._pin_and_admit( roster, user_id, username, pk_ed_b64, pk_x_b64, group_id=session_group, role=ROLE_MEMBER, approved_by="open-join", via="tofu") await self._join_ok(user_id, pk_x_raw, session_group, role=ROLE_MEMBER, recognised=False) return self._join_refuse("code_required") return invite = await roster.consume_invite(code, user_id, session_group) if not invite: self._join_refuse("code_invalid") return await self._pin_and_admit( # The name comes from the invitation, not from the token: the hub does # not put a username claim in a JWT, so pinning from the session alone # left the roster nameless and `member revoke ` unable to match. roster, user_id, invite["username"] or username, pk_ed_b64, pk_x_b64, group_id=invite["group_id"], role=invite["role"], approved_by=invite["created_by"], via="link" if invite["kind"] == KIND_LINK else "code") # The roster row comes from the invitation; the key comes from the # connection. An operator pairing is node-wide (empty group), but they # redeemed the code while opening a group and expect to read it — and # is_authorized() already grants an operator every group on this node. await self._join_ok(user_id, pk_x_raw, session_group or invite["group_id"], role=invite["role"], recognised=False) # ── Device linking ─────────────────────────────────────────────────────── # # A person may hold several devices on one node. The authority admitting a # new one is a key the node already pinned — never the hub, which has stored # no user keys since 2026-08-14 and therefore cannot countersign anything. # See docs/MESHBAY_DESIGN.md §3.3. async def _do_device_request(self, msg: dict) -> None: """ A new device files itself as pending, bound to a code it displays. Served in the pre-proof window: by construction the caller holds no key this node knows, so there is nothing yet to prove. Filing is inert — nothing is admitted until an existing device countersigns. """ roster = self._ctx.get("roster") if roster is None or not self._user_id or not self._nonce_node: self._send({"type": "error", "detail": "Not ready for a device request"}) return if not self._spend_device_attempt(): return pk_ed_b64 = str(msg.get("pk_ed25519", "")) pk_x_b64 = str(msg.get("pk_x25519", "")) code_hash = str(msg.get("code_hash", "")) if not (pk_ed_b64 and pk_x_b64 and code_hash): self._send({"type": "error", "detail": "Missing device keys or code"}) return # The account must already be known here. Anti-spam rather than a # security boundary: the filing key is unpinned by construction, so this # bounds the table, not the trust. existing = await roster.list_devices(self._user_id) if not existing: self._send({"type": "error", "detail": "This account has no device on this node yet — " "an invitation code is what admits the first"}) return if len(existing) >= roster.MAX_DEVICES_PER_USER: self._send({"type": "error", "detail": f"Already {len(existing)} devices, which is the " f"limit. Revoke one first."}) return ts = int(msg.get("ts", 0)) if abs(time.time() - ts) > DEVICE_TTL: self._send({"type": "error", "detail": "Device request expired"}) return transcript = device_request_transcript( node_pk_b64=self._node_pk_b64(), user_id=self._user_id, pk_ed25519_b64=pk_ed_b64, pk_x25519_b64=pk_x_b64, code_hash=code_hash, nonce_node=self._nonce_node, ts=ts) try: pk_ed = Ed25519PublicKey.from_public_bytes(base64.b64decode(pk_ed_b64)) sig = base64.b64decode(msg.get("sig", "")) except Exception: self._send({"type": "error", "detail": "Invalid device key encoding"}) return if not self._verify_sig(pk_ed, transcript, sig): # Proof of possession, and nothing more: this says the caller holds # the keys, never that they belong to this account. self._send({"type": "error", "detail": "Device signature invalid"}) return ttl = int(self._ctx.get("device_request_ttl") or 3600) expires = await roster.file_device_request( user_id=self._user_id, username=self._username or "", pk_ed25519=pk_ed_b64, pk_x25519=pk_x_b64, code_hash=code_hash, ttl=ttl) self._audit("device_request", f"{pk_ed_b64[:16]}") log.info("Device request filed for %s (%s)", self._user_id[:8], pk_ed_b64[:16]) self._send({"type": MNP.DEVICE_REQUEST_ACK, "v": MNP_VERSION, "expires_at": expires}) async def _do_device_lookup(self, msg: dict) -> None: """ List this account's pending device requests, each with its code hash. **The node never learns the code**, which is what makes it unable to substitute a key. It answers with candidates; the approver recomputes `sha256(code ‖ keys)` for each and keeps the one that matches. A node offering fabricated keys would have to produce a hash matching `sha256(code ‖ fabricated)` — and it does not know the code. An earlier version of this took the hash from the client and looked the request up by it. That is circular: the client cannot compute the hash without already knowing the keys it is asking about. """ roster = self._ctx.get("roster") if roster is None or not self._user_id: self._send({"type": "error", "detail": "Roster not available"}) return pending = await roster.list_device_requests(self._user_id) self._send({ "type": MNP.DEVICE_LOOKUP_RESULT, "v": MNP_VERSION, "requests": [ {"pk_ed25519": r["pk_ed25519"], "pk_x25519": r["pk_x25519"], "code_hash": r["code_hash"], "created_at": r["created_at"]} for r in pending ], }) async def _do_device_add(self, msg: dict) -> None: """ Admit a device, countersigned by one this node already pinned. The whole control is in `_verify_device_signer`: the signature must verify against a **live device of this same account**. The hub holds no user keys and so cannot produce one. """ roster = self._ctx.get("roster") if roster is None or not self._user_id or not self._nonce_node: self._send({"type": "error", "detail": "Not ready to add a device"}) return if not self._spend_device_attempt(): return pk_ed_b64 = str(msg.get("pk_ed25519", "")) pk_x_b64 = str(msg.get("pk_x25519", "")) ts = int(msg.get("ts", 0)) if not (pk_ed_b64 and pk_x_b64): self._send({"type": "error", "detail": "Missing device keys"}) return if abs(time.time() - ts) > DEVICE_TTL: self._send({"type": "error", "detail": "Approval expired"}) return transcript = device_add_transcript( node_pk_b64=self._node_pk_b64(), user_id=self._user_id, pk_ed25519_b64=pk_ed_b64, pk_x25519_b64=pk_x_b64, nonce_node=self._nonce_node, ts=ts) signer = await self._verify_device_signer(roster, transcript, msg.get("sig", "")) if signer is None: self._audit("device_add_refused", pk_ed_b64[:16]) self._send({"type": "error", "detail": "Not signed by a device already paired here"}) return devices = await roster.list_devices(self._user_id) if len(devices) >= roster.MAX_DEVICES_PER_USER: self._send({"type": "error", "detail": "Device limit reached"}) return # Spend the request. Single use: an approval cannot be replayed, and a # code that was used is gone whatever else happens next. code_hash = str(msg.get("code_hash", "")) if code_hash and not await roster.take_device_request( code_hash, self._user_id): self._send({"type": "error", "detail": "That request is no longer pending"}) return # The countersignature is **kept**, with the two fields needed to rebuild # what it signed. Until 2026-09-07 it was verified here and thrown away, # leaving only `added_by_pk` — which says *which* key approved and # proves nothing to anyone else. `device_add_transcript` binds # `nonce_node`, this connection's handshake nonce, so a stored signature # without it is still unverifiable; that is why all three go in. # # This is what lets another member check for themselves that this device # belongs to an account whose earlier device they have already pinned, # instead of taking the node's word (Tier 2, docs/MESHBAY_DESIGN.md §3.3). await roster.pin_identity( user_id=self._user_id, username=self._username or "", pk_ed25519=pk_ed_b64, pk_x25519=pk_x_b64, via="device", label=str(msg.get("label", ""))[:64], added_by_pk=signer, add_sig=str(msg.get("sig", "")), add_nonce=base64.b64encode(self._nonce_node).decode(), add_ts=ts) self._audit("device_added", f"{pk_ed_b64[:16]} by {signer[:16]}") log.info("Device added for %s: %s (approved by %s)", self._user_id[:8], pk_ed_b64[:16], signer[:16]) self._send({"type": MNP.DEVICE_ADD_ACK, "v": MNP_VERSION, "pk_ed25519": pk_ed_b64}) async def _do_device_hello(self, msg: dict) -> None: """ Learn which of this account's devices is on this connection. The handshake authenticates a *group membership* (the GEK-HMAC) and an *account* (the hub's token). It has never authenticated a device, and while one account meant one key that was the same statement. It stopped being so on 2026-08-18, and `_load_pinned_pk` — which resolves the account's oldest live device — has been standing in for the real answer ever since, including as the recorded uploader of every file. What is checked, in order: the key is a live device *of this account* in the node's own roster (never a token claim — that is `docs/MESHBAY_DESIGN.md` §3.2's rule), the timestamp is fresh, and the signature verifies over a transcript naming this node, this group and this connection's nonce. A key that is merely well-formed proves nothing. Idempotent for the same key, refused for a different one: a connection does not get to change device half way through, which would let one session's uploads be attributed to two. """ roster = self._ctx.get("roster") if roster is None or not self._user_id: self._send({"type": "error", "detail": "Roster not available"}) return if not self._spend_device_attempt(): return pk_ed_b64 = str(msg.get("pk_ed25519", "")) ts = int(msg.get("ts", 0) or 0) if not pk_ed_b64: self._send({"type": "error", "detail": "Missing device key"}) return if self._device_confirmed and pk_ed_b64 != self._pinned_pk: self._send({"type": "error", "detail": "This connection is already another device"}) return if abs(time.time() - ts) > DEVICE_TTL: self._send({"type": "error", "detail": "Stale device_hello"}) return device = await roster.find_device(self._user_id, pk_ed_b64) if device is None: self._audit("device_hello_refused", pk_ed_b64[:16]) self._send({"type": "error", "detail": "Not a device paired here"}) return transcript = device_hello_transcript( node_pk_b64=self._node_pk_b64(), group_id=self._group_id or "", user_id=self._user_id, pk_ed25519_b64=pk_ed_b64, nonce_node=self._nonce_node, ts=ts) try: pk = Ed25519PublicKey.from_public_bytes(base64.b64decode(pk_ed_b64)) except Exception: self._send({"type": "error", "detail": "Unreadable device key"}) return try: sig = base64.b64decode(msg.get("sig", "")) except Exception: sig = b"" if not self._verify_sig(pk, transcript, sig): self._audit("device_hello_refused", pk_ed_b64[:16]) self._send({"type": "error", "detail": "Signature verification failed"}) return self._pinned_pk = pk_ed_b64 self._device_confirmed = True log.info("Device identified on connection: user=%s device=%s", self._user_id[:8], pk_ed_b64[:16]) self._send({"type": MNP.DEVICE_HELLO_ACK, "v": MNP_VERSION, "pk_ed25519": pk_ed_b64}) async def _do_device_list(self, msg: dict) -> None: """This account's devices. Anyone may read their own, nobody else's.""" roster = self._ctx.get("roster") if roster is None or not self._user_id: self._send({"type": "error", "detail": "Roster not available"}) return devices = await roster.list_devices(self._user_id) pending = await roster.pending_device_requests(self._user_id) self._send({ "type": MNP.DEVICE_LIST_RESULT, "v": MNP_VERSION, "pending": pending, "devices": [ {"pk_ed25519": d["pk_ed25519"], "label": d.get("label", ""), "pinned_at": d["pinned_at"], "pinned_via": d["pinned_via"], "added_by_pk": d.get("added_by_pk", ""), "is_this_one": d["pk_ed25519"] == self._pinned_pk} for d in devices ], }) async def _do_device_revoke(self, msg: dict) -> None: """ Retire one of this account's devices — a lost laptop. Countersigned like an addition, by a live device of the same account. The last one cannot go: an account with no device on this node can only return through an operator's invitation code, and doing that to yourself by accident is not a mistake worth allowing. """ roster = self._ctx.get("roster") if roster is None or not self._user_id or not self._nonce_node: self._send({"type": "error", "detail": "Not ready"}) return if not self._spend_device_attempt(): return target = str(msg.get("pk_ed25519", "")) ts = int(msg.get("ts", 0)) if not target: self._send({"type": "error", "detail": "Missing device key"}) return if abs(time.time() - ts) > DEVICE_TTL: self._send({"type": "error", "detail": "Request expired"}) return victim = await roster.find_device(self._user_id, target) if victim is None: self._send({"type": "error", "detail": "No such device"}) return transcript = device_add_transcript( node_pk_b64=self._node_pk_b64(), user_id=self._user_id, pk_ed25519_b64=target, pk_x25519_b64=victim["pk_x25519"], nonce_node=self._nonce_node, ts=ts) signer = await self._verify_device_signer(roster, transcript, msg.get("sig", "")) if signer is None: self._send({"type": "error", "detail": "Not signed by a device already paired here"}) return if len(await roster.list_devices(self._user_id)) <= 1: self._send({"type": "error", "detail": "This is your only device here — removing it " "would need an operator code to come back"}) return await roster.revoke_device(self._user_id, target) # A revoked device holds every chat key it ever received — a lost laptop # reads the group's chat until the epoch moves. await self._new_chat_epoch(self._group_id or "", "device_revoke") self._audit("device_revoked", f"{target[:16]} by {signer[:16]}") log.info("Device revoked for %s: %s", self._user_id[:8], target[:16]) self._send({"type": MNP.DEVICE_ADD_ACK, "v": MNP_VERSION, "revoked": target}) async def _verify_device_signer(self, roster, transcript: bytes, sig_b64: str) -> str | None: """ The pinned key that signed this, or None. Every live device of the account is tried, because any of them may approve. A revoked one is not in the list — that is the point of marking rather than deleting: a lost laptop must stop being able to admit its replacement. """ try: sig = base64.b64decode(sig_b64) except Exception: return None for device in await roster.list_devices(self._user_id): try: pk = Ed25519PublicKey.from_public_bytes( base64.b64decode(device["pk_ed25519"])) except Exception: continue if self._verify_sig(pk, transcript, sig): return device["pk_ed25519"] return None def _spend_device_attempt(self) -> bool: """ Bound guessing on this connection, as the join path does. A code is 40 bits, single use and bound to the keys it names, so this is depth rather than the control — but an unbounded loop over the lookup is still a free oracle, and a burst of failures belongs in the audit log. """ self._device_attempts = getattr(self, "_device_attempts", 0) + 1 if self._device_attempts > 5: self._audit("device_attempts_exceeded", str(self._device_attempts)) self._send({"type": "error", "detail": "Too many device attempts on this connection"}) return False return True def _group_join_policy(self, group_id: str) -> str: """ Admission policy for a group, read from the node's own configuration. Never from the hub: a hub that could declare a group open would be handed the key to it (docs/MESHBAY_DESIGN.md §3.4). """ gctx = (self._ctx.get("groups") or {}).get(group_id) or {} return gctx.get("join_policy", "invite") async def _pin_and_admit( self, roster, user_id: str, username: str, pk_ed_b64: str, pk_x_b64: str, *, group_id: str, role: str, approved_by: str, via: str, ) -> None: await roster.pin_identity( user_id=user_id, username=username, pk_ed25519=pk_ed_b64, pk_x25519=pk_x_b64, via=via, ) await roster.set_member( group_id=group_id, user_id=user_id, role=role, status="active", approved_by=approved_by, ) if role == ROLE_OPERATOR: self._ctx["has_admin_authority"] = True log.info("Identity pinned (%s): user=%s role=%s", via, user_id[:8], role) self._audit_join("join_pinned", f"role={role} via={via}") async def _join_ok( self, user_id: str, pk_x_raw: bytes, group_id: str, *, role: str, recognised: bool, ) -> None: """ Answer a join, wrapping the group key for the key the caller just proved. This is the H3 fix. The inviter used to fetch the invitee's public key from the hub and wrap the GEK for whatever came back, so a hub that answered with its own key was handed the group key by an honest member following the protocol exactly. The node now wraps for a key that arrived from its owner over an authenticated channel, bound to a pinned identity. """ reply = { "type": MNP.JOIN_RESULT, "v": MNP_VERSION, "ok": True, "recognised": recognised, "role": role, } roster = self._ctx["roster"] if group_id and not await roster.is_authorized(group_id, user_id): # Pinned on this node, but not admitted to this group. Hub membership # alone must not produce a key. reply["gek"] = False reply["reason"] = "not_authorized_for_group" self._send(reply) self._audit_join("join_no_gek", f"group={group_id[:8]} not authorized") return gctx = (self._ctx.get("groups") or {}).get(group_id) or {} gek = gctx.get("gek") if not gek: reply["gek"] = False reply["reason"] = "no_gek" self._send(reply) return bundle = wrap_gek_aes(gek, pk_x_raw) reply["gek"] = True reply["pk_eph_b64"] = bundle["pk_eph_b64"] reply["nonce_b64"] = bundle["nonce_b64"] reply["wrapped_b64"] = bundle["wrapped_b64"] self._send(reply) self._audit_join("gek_wrapped", f"group={group_id[:8]}") def _do_member_revoke(self, msg: dict) -> None: """ Stop serving the group key to someone, at the operator's request. The same authority as an invite, and the same reason: the roster decides who this node serves, so only a key the node pinned as an operator may change it. Membership on the hub is not consulted — the hub can remove someone from a group, and that stops them reaching the node at all, but it cannot make the node forget them. """ user_id = str(msg.get("user_id", "")).strip() if not user_id: self._send({"type": "error", "detail": "Missing user_id"}) return if user_id == self._user_id: # Removing yourself from your own node is not a member operation; # it would leave the group with nobody able to invite. self._send({"type": "error", "detail": "Cannot revoke yourself"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge(OP_MEMBER_REVOKE, user_id) def _do_gek_rotate(self, msg: dict) -> None: """ Ask for a new group key. Operator only, and signed. This is what actually removes a revoked member's access: revocation stops the node serving the *next* key, and they still hold the current one. The node generates the replacement itself — nothing arriving here contributes key material, which is what the C5b rule is about. """ group_id = str(msg.get("group_id", "")).strip() or self._group_id if not group_id: self._send({"type": "error", "detail": "No group on this connection"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge(OP_GEK_ROTATE, group_id, group_id=group_id) async def _admin_exec_gek_rotate( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"gek_rotate:{pending['subject'][:8]}") return try: result = await self._run_op( ops.set_gek, pending["subject"], rotate=True) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return # The operator is rotating because somebody left, and the chat archive # key is not derived from the group key — so rotating that one does not # move this one. Doing both here is what makes "rotate after a removal" # mean the same thing for chat as it does for files. await self._new_chat_epoch(pending["subject"], "gek_rotate") self._audit("gek_rotate", pending["subject"]) self._send({ "type": MNP.GEK_ROTATE_ACK, "v": MNP_VERSION, "group_id": pending["subject"], "authorized_members": result.get("authorized_members", 0), # Said plainly, because rotating is the step people skip: content # already downloaded stays readable to whoever holds it. "note": "members re-receive the key on their next connect; content " "already downloaded is unaffected", }) def _do_member_unpin(self, msg: dict) -> None: """Forget a pinned identity, so someone can pair again with a new key.""" user_id = str(msg.get("user_id", "")).strip() if not user_id: self._send({"type": "error", "detail": "Missing user_id"}) return if user_id == self._user_id: # Unpinning yourself over the connection your pin authorizes would # end that connection's authority mid-operation. self._send({"type": "error", "detail": "Cannot unpin yourself"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge(OP_MEMBER_UNPIN, user_id) async def _admin_exec_member_unpin( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: user_id = pending["subject"] if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"member_unpin:{user_id[:8]}") return try: await self._run_op(ops.unpin_member, user_id) await self._new_chat_epoch(self._group_id or "", "member_unpin") except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("member_unpin", user_id) self._send({"type": MNP.MEMBER_UNPIN_ACK, "v": MNP_VERSION, "user_id": user_id}) # Every "application" a group can show. Photos joins this set (and # apps.js's registry, client-side) when it lands; nothing else about # this handler changes. DEFAULT_APPS (roster.py) deliberately does not # include "video" or "music" — both can make outbound third-party # network calls (TMDB, MusicBrainz) once enabled, so an operator opts a # group in explicitly rather than getting it for free # (docs/MESHBAY_DESIGN.md §9.7, §9.8). # `helloworld` is the reference implementation (docs/MESHBAY_DESIGN.md # §9.4), hidden client-side behind `?dev=1`. It is here because the # allow-list is server-side enforcement — a client that names an app this # node does not know is refused — and an app the node refused could not # demonstrate anything. This entry and the client's registry line are the # whole of what adding an application costs. ALLOWED_APPS = frozenset({"chat", "files", "video", "music", "photo", "helloworld"}) def _do_apps_enabled(self, msg: dict) -> None: """ Turn a group "application" on or off for everyone, for this group. Signed like the root ops: this decides what a member sees, and an unsigned message would let any member turn a disabled one back on. """ apps = msg.get("apps") if not isinstance(apps, list) or not apps: self._send({"type": "error", "detail": "Missing or empty apps"}) return unknown = set(apps) - self.ALLOWED_APPS if unknown: self._send({"type": "error", "detail": f"Unknown app(s): {', '.join(sorted(unknown))}"}) return # Files is not a toggle: MNP permits root exploration regardless of # what this list says, so hiding the tab only ever misled. Added at the # front, the same order ops.set_enabled_apps writes, so the landing-tab # preference sees one list and not two. if "files" not in apps: apps.insert(0, "files") if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return # The subject is what the operator is shown before signing, and what # the client compares its own request against (transport.js) — a # canonical form so both sides build the same transcript. self._issue_admin_challenge(OP_APPS_ENABLED, ",".join(sorted(apps))) async def _admin_exec_apps_enabled( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: apps = pending["subject"].split(",") if pending["subject"] else [] if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"apps_enabled:{pending['subject']}") return try: await self._run_op( ops.set_enabled_apps, self._group_id or "", apps) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("apps_enabled", pending["subject"]) # Everyone already connected is told, so a disabled tab disappears # without waiting for a reconnection. notice = {"type": MNP.APPS_ENABLED_ACK, "v": MNP_VERSION, "apps": apps} for uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass # ── App directories (generic) ──────────────────────────────────────── def _do_app_directories(self, msg: dict) -> None: """ Which folder(s) an application works over, for any application. One handler for every application, keyed by the app's own name: adding an application adds no message type, and there is no per-app handler differing only in the key it writes and whether it carries a string or a list. `app` must be one this node knows (`ALLOWED_APPS`) — a client-supplied key is otherwise a way to write arbitrary rows into `group_settings`. The paths are checked by `ops._validate_app_dirs`, which runs after the signature: this is a settings change, not a capability, so refusing early here would be a courtesy rather than the control. """ app = str(msg.get("app", "")).strip() dirs = msg.get("directories") if app not in self.ALLOWED_APPS: self._send({"type": "error", "detail": f"Unknown app {app!r}"}) return if not isinstance(dirs, list) or not all(isinstance(d, str) for d in dirs): self._send({"type": "error", "detail": "Missing or invalid 'directories'"}) return clean = sorted({d.strip("/") for d in dirs if d.strip("/")}) if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return # The app is in the subject, not only the paths: an operator shown # "Media/Films" alone cannot tell which application is about to be # pointed at it, and two apps' challenges would be indistinguishable. self._issue_admin_challenge( OP_APP_DIRECTORIES, f"{app}:{','.join(clean)}") async def _admin_exec_app_directories( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: app, _, joined = pending["subject"].partition(":") dirs = joined.split(",") if joined else [] if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"app_directories:{pending['subject']}") return try: result = await self._run_op( ops.set_app_directories, self._group_id or "", app, dirs) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("app_directories", pending["subject"]) self._broadcast_to_group({"type": MNP.APP_DIRECTORIES_ACK, "v": MNP_VERSION, "app": app, "directories": result["directories"]}) # ── Chat ───────────────────────────────────────────────────────────── def _do_search_listed(self, msg: dict) -> None: """ Whether this group's files appear in members' cross-group Search. Signed because it changes what every member's Search shows, not because it protects anything — see ops.set_search_listed. """ listed = msg.get("listed") if not isinstance(listed, bool): self._send({"type": "error", "detail": "Missing or invalid 'listed'"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge(OP_SEARCH_LISTED, "on" if listed else "off") async def _admin_exec_search_listed( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: listed = pending["subject"] == "on" if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"search_listed:{pending['subject']}") return try: await self._run_op(ops.set_search_listed, self._group_id or "", listed) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("search_listed", pending["subject"]) self._broadcast_to_group({"type": MNP.SEARCH_LISTED_ACK, "v": MNP_VERSION, "listed": listed}) async def _do_group_roster_req(self, msg: dict) -> None: """ Who is in this group, and which device keys they hold. Answers **any member**, not only the operator — that is the whole point. A member verifies for themselves that a message came from a device belonging to the account it claims, instead of taking the node's `sender_id` on trust. What makes that possible is relayed here: each device's key, which already-pinned key countersigned it, and the signature plus the nonce and timestamp needed to rebuild what was signed. Sealed under a GEK-derived subkey, for the same reason the index is: it is the group's membership, and a peer that has not completed the handshake has no business reading it. What this deliberately does not do is *decide* anything. The node hands over evidence; the client checks the chain and keeps its own pins. A node that lies here is caught by a client that has seen the account before, which is the property Tier 2 buys and the reason the node is not asked to assert trust. """ gctx = self._group_ctx() gek = gctx.get("gek") roster = self._ctx.get("roster") if not gek: self._send({"type": "error", "detail": "Group encryption not initialized"}) return if roster is None: self._send({"type": "error", "detail": "Roster not available"}) return devices = await roster.group_devices(self._group_id or "") payload = {"devices": devices, "node_pk": self._node_pk_b64()} sealed = seal(gek, PURPOSE_ROSTER, MNP.GROUP_ROSTER_RESP, self._group_id or "", payload) self._send({"type": MNP.GROUP_ROSTER_RESP, "v": MNP_VERSION, "group_id": self._group_id or "", **sealed}) def _broadcast_to_group(self, notice: dict) -> None: """ Tell everyone connected to this group about a setting that changed. Enforcement never depends on this reaching them — the node is what refuses — but a control that stays on screen until the next reconnection is a control people use. """ for _uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass # Reconcile's backstop and the watchdog debounce (indexer.py # DirectoryIndexer) — how hard the node works on the operator's own # disk, not a member-facing permission. Signed for the same reason as # apps_enabled: consistency of the authorization model, not because a # wrong value here is itself dangerous. MIN_RECONCILE_SECS = 10.0 MAX_RECONCILE_SECS = 24 * 3600.0 MIN_DEBOUNCE_SECS = 0.0 MAX_DEBOUNCE_SECS = 300.0 def _do_set_scan_settings(self, msg: dict) -> None: try: reconcile = float(msg.get("reconcile_interval_secs")) debounce = float(msg.get("debounce_secs")) except (TypeError, ValueError): self._send({"type": "error", "detail": "Invalid scan settings"}) return if not (self.MIN_RECONCILE_SECS <= reconcile <= self.MAX_RECONCILE_SECS): self._send({"type": "error", "detail": f"reconcile_interval_secs must be between " f"{self.MIN_RECONCILE_SECS:.0f} and " f"{self.MAX_RECONCILE_SECS:.0f}"}) return if not (self.MIN_DEBOUNCE_SECS <= debounce <= self.MAX_DEBOUNCE_SECS): self._send({"type": "error", "detail": f"debounce_secs must be between " f"{self.MIN_DEBOUNCE_SECS:.0f} and " f"{self.MAX_DEBOUNCE_SECS:.0f}"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_SET_SCAN_SETTINGS, f"{reconcile:g},{debounce:g}") MIN_TRANSFER_LIMIT = 1 MAX_TRANSFER_LIMIT = 32 def _do_transfer_limits(self, msg: dict) -> None: """How many transfers one member may run at once in this group. Zero is not "unlimited" and is refused: a member who may not transfer at all is a member the operator revokes, and reading 0 as no-limit would make the most dangerous value the easiest to type by accident. """ try: downloads = int(msg.get("downloads")) uploads = int(msg.get("uploads")) except (TypeError, ValueError): self._send({"type": "error", "detail": "Invalid transfer limits"}) return for value in (downloads, uploads): if not (self.MIN_TRANSFER_LIMIT <= value <= self.MAX_TRANSFER_LIMIT): self._send({"type": "error", "detail": f"transfer limits must be between " f"{self.MIN_TRANSFER_LIMIT} and " f"{self.MAX_TRANSFER_LIMIT}"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge(OP_TRANSFER_LIMITS, f"d={downloads},u={uploads}") async def _admin_exec_transfer_limits( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: try: parts = dict(p.split("=") for p in pending["subject"].split(",")) downloads, uploads = int(parts["d"]), int(parts["u"]) except (ValueError, KeyError): self._send({"type": "error", "detail": "Invalid transfer limits"}) return if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"transfer_limits:{pending['subject']}") return try: result = await self._run_op( ops.set_transfer_limits, self._group_id or "", downloads, uploads) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("transfer_limits", pending["subject"]) notice = {"type": MNP.TRANSFER_LIMITS_ACK, "v": MNP_VERSION, "limits": result["limits"]} for session in list(self._peer_registry().values()): try: session._send(notice) except Exception: pass async def _admin_exec_set_scan_settings( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: try: reconcile_s, debounce_s = pending["subject"].split(",") reconcile, debounce = float(reconcile_s), float(debounce_s) except (ValueError, KeyError): self._send({"type": "error", "detail": "Invalid scan settings"}) return if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"set_scan_settings:{pending['subject']}") return try: result = await self._run_op( ops.set_scan_settings, self._group_id or "", reconcile, debounce) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("set_scan_settings", pending["subject"]) notice = {"type": MNP.SET_SCAN_SETTINGS_ACK, "v": MNP_VERSION, **result} for uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass # ── Node management (D5) ───────────────────────────────────────────────── async def _do_node_status(self, msg: dict) -> None: """All groups, roots, peers — the operator's overview. Including every root's absolute path, which is why this is gated on a proved operator device and not on an account the hub named. """ node_uid = self._ctx.get("node_user_id") log.info("node_status: user=%s node_user=%s owner=%s device=%s", self._user_id, node_uid, self._is_node_admin(), "confirmed" if self._device_confirmed else "unidentified") if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return try: result = await self._run_op(ops.list_groups) self._send({"type": MNP.NODE_STATUS_ACK, "v": MNP_VERSION, **result}) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) except Exception as e: log.error("node_status failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) async def _do_node_settings_set(self, msg: dict) -> None: if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return settings = msg.get("settings", {}) if not settings: self._send({"type": "error", "detail": "No settings provided"}) return try: result = await self._run_op(ops.set_node_settings, settings) self._send({"type": MNP.NODE_SETTINGS_SET_ACK, "v": MNP_VERSION, **result}) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) except Exception as e: log.error("node_settings_set failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) async def _do_roster_read(self, msg: dict) -> None: if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return group_id = str(msg.get("group_id", "")).strip() try: result = await self._run_op(ops.read_roster, group_id) self._send({"type": MNP.ROSTER_READ_ACK, "v": MNP_VERSION, **result}) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) except Exception as e: log.error("roster_read failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) async def _do_denylist_read(self, msg: dict) -> None: if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return try: result = await self._run_op(ops.read_denylist) self._send({"type": MNP.DENYLIST_READ_ACK, "v": MNP_VERSION, **result}) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) except Exception as e: log.error("denylist_read failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) async def _do_denylist_clear(self, msg: dict) -> None: if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return subject = str(msg.get("subject", "")).strip() try: result = await self._run_op(ops.clear_denylist, subject=subject) self._audit("denylist_clear", subject or "all") self._send({"type": MNP.DENYLIST_CLEAR_ACK, "v": MNP_VERSION, **result}) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) except Exception as e: log.error("denylist_clear failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) def _do_group_attach(self, msg: dict) -> None: name = str(msg.get("name", "")).strip() shared_dir = str(msg.get("shared_dir", "")).strip() if not name or not shared_dir: self._send({"type": "error", "detail": "Missing name or shared_dir"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return # `upload_dir` is not read here any more, and a client still sending it # is ignored rather than obeyed: on load it forces every other root # read-only, which is the model the RO/RW one replaced. A second # writable directory is `root_add` with `writable`. self._issue_admin_challenge( OP_GROUP_ATTACH, name, payload={"name": name, "shared_dir": shared_dir, "writable": bool(msg.get("writable", True))}, group_id="") async def _admin_exec_group_attach( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"group_attach:{pending['subject'][:16]}") return p = pending.get("payload") or {} try: result = await self._run_op( ops.attach_group, p["name"], p["shared_dir"], writable=bool(p.get("writable", True))) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("group_attach", pending["subject"]) self._send({"type": MNP.GROUP_ATTACH_ACK, "v": MNP_VERSION, **result}) state = self._ctx.get("daemon_state") reload_fn = state.get("reload_fn") if state else None if reload_fn: try: await reload_fn() except Exception as e: log.error("Reload after group_attach failed: %s", e) def _do_group_detach(self, msg: dict) -> None: name = str(msg.get("name", "")).strip() if not name: self._send({"type": "error", "detail": "Missing group name or id"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_GROUP_DETACH, name, payload={"name": name}, group_id="") async def _admin_exec_group_detach( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"group_detach:{pending['subject'][:16]}") return p = pending.get("payload") or {} try: result = await self._run_op(ops.detach_group, p["name"]) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("group_detach", pending["subject"]) self._send({"type": MNP.GROUP_DETACH_ACK, "v": MNP_VERSION, **result}) state = self._ctx.get("daemon_state") reload_fn = state.get("reload_fn") if state else None if reload_fn: try: await reload_fn() except Exception as e: log.error("Reload after group_detach failed: %s", e) async def _do_node_reload(self, msg: dict) -> None: if not await self._operator_device(): self._send({"type": "error", "detail": "Not the node operator", "code": "not_operator"}) return state = self._ctx.get("daemon_state") reload_fn = state.get("reload_fn") if state else None if not reload_fn: self._send({"type": "error", "detail": "Reload not available"}) return try: await reload_fn() self._send({"type": MNP.NODE_RELOAD_ACK, "v": MNP_VERSION, "status": "reloaded"}) except Exception as e: log.error("node_reload failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Reload failed"}) def _do_root_add(self, msg: dict) -> None: target_group = str(msg.get("group_id", "")).strip() path = str(msg.get("path", "")).strip() if not target_group or not path: self._send({"type": "error", "detail": "Missing group_id or path"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_ROOT_ADD, path, payload={ "group_id": target_group, "path": path, "name": str(msg.get("name", ""))[:128], "kind": str(msg.get("kind", "generic"))[:16], "writable": bool(msg.get("writable", msg.get("upload", False))), "removable": bool(msg.get("removable", False)), }, group_id=target_group) async def _admin_exec_root_add( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"root_add:{pending['subject'][:24]}") return p = pending["payload"] try: result = await self._run_op( ops.add_root, p["group_id"], p["path"], name=p.get("name", ""), kind=p.get("kind", "generic"), writable=p.get("writable", False), removable=p.get("removable", False)) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return except Exception as e: log.error("root_add failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) return self._audit("root_add", f"{p['path']}→{p['group_id'][:8]}") await self._retarget_indexer(p["group_id"]) self._send({"type": MNP.ROOT_ADD_ACK, "v": MNP_VERSION, **result}) def _do_root_remove(self, msg: dict) -> None: target_group = str(msg.get("group_id", "")).strip() root_name = str(msg.get("root_name", "")).strip() if not target_group or not root_name: self._send({"type": "error", "detail": "Missing group_id or root_name"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_ROOT_REMOVE, root_name, payload={"group_id": target_group, "root_name": root_name}, group_id=target_group) async def _admin_exec_root_remove( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"root_remove:{pending['subject'][:24]}") return p = pending["payload"] try: result = await self._run_op( ops.remove_root, p["group_id"], p["root_name"]) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return except Exception as e: log.error("root_remove failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) return self._audit("root_remove", f"{p['root_name']}←{p['group_id'][:8]}") await self._retarget_indexer(p["group_id"]) self._send({"type": MNP.ROOT_REMOVE_ACK, "v": MNP_VERSION, **result}) def _do_root_update(self, msg: dict) -> None: target_group = str(msg.get("group_id", self._group_id or "")).strip() root_name = str(msg.get("root_name", "")).strip() if not target_group or not root_name: self._send({"type": "error", "detail": "Missing group_id or root_name"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return updates = [] if "writable" in msg: updates.append(f"rw={'on' if msg['writable'] else 'off'}") if "removable" in msg: updates.append(f"rem={'on' if msg['removable'] else 'off'}") subject = f"{root_name}:{','.join(updates)}" if updates else root_name self._issue_admin_challenge( OP_ROOT_UPDATE, subject, payload={ "group_id": target_group, "root_name": root_name, "writable": msg.get("writable"), "removable": msg.get("removable"), }, group_id=target_group) async def _admin_exec_root_update( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"root_update:{pending['subject'][:24]}") return p = pending["payload"] try: result = await self._run_op( ops.update_root, p["group_id"], p["root_name"], writable=p.get("writable"), removable=p.get("removable")) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return except Exception as e: log.error("root_update failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) return self._audit("root_update", pending["subject"]) await self._retarget_indexer(p["group_id"]) notice = {"type": MNP.ROOT_UPDATE_ACK, "v": MNP_VERSION, **result} for uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass def _do_root_eject(self, msg: dict) -> None: target_group = str(msg.get("group_id", self._group_id or "")).strip() root_name = str(msg.get("root_name", "")).strip() if not target_group or not root_name: self._send({"type": "error", "detail": "Missing group_id or root_name"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_ROOT_EJECT, root_name, payload={"group_id": target_group, "root_name": root_name}, group_id=target_group) async def _admin_exec_root_eject( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"root_eject:{pending['subject'][:24]}") return p = pending["payload"] try: result = await self._run_op( ops.eject_root, p["group_id"], p["root_name"]) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return except Exception as e: log.error("root_eject failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) return self._audit("root_eject", p["root_name"]) notice = {"type": MNP.ROOT_EJECT_ACK, "v": MNP_VERSION, **result} for uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass def _do_root_plug(self, msg: dict) -> None: target_group = str(msg.get("group_id", self._group_id or "")).strip() root_name = str(msg.get("root_name", "")).strip() if not target_group or not root_name: self._send({"type": "error", "detail": "Missing group_id or root_name"}) return if not self._has_admin_authority(): self._send({"type": "error", "detail": "No authorized key for this"}) return self._issue_admin_challenge( OP_ROOT_PLUG, root_name, payload={"group_id": target_group, "root_name": root_name}, group_id=target_group) async def _admin_exec_root_plug( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"root_plug:{pending['subject'][:24]}") return p = pending["payload"] try: result = await self._run_op( ops.plug_root, p["group_id"], p["root_name"]) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return except Exception as e: log.error("root_plug failed: %s", e, exc_info=True) self._send({"type": "error", "detail": "Internal error"}) return self._audit("root_plug", p["root_name"]) notice = {"type": MNP.ROOT_PLUG_ACK, "v": MNP_VERSION, **result} for uid, session in list(self._peer_registry().items()): try: session._send(notice) except Exception: pass async def _run_op(self, fn, *args, **kwargs): """ Call an operation from `meshbay_node.ops` with the daemon's own view. The transport carries its own context and the loopback API carries the daemon state; they overlap but are not the same dict. Handing the MNP path a *second* set of lookups is exactly how two implementations of one operation start disagreeing — C1 and C6 one size down — so the daemon publishes its state here and both adapters call the same function. """ state = self._ctx.get("daemon_state") if state is None: raise ops.OpError("Node state not available", status=503) return await fn(state, *args, **kwargs) async def _retarget_indexer(self, group_id: str) -> None: """ Pick up a root that was just added to or removed from node.toml. Through the daemon's own reload, which is what the loopback API has always done after the same operations (`ui/app.py`). This used to re-point the indexer at `groups_ctx[gid]["roots"]` instead — the very object the op had just edited — so `retarget` diffed a set against itself, found no new names, scanned nothing, and dropped nothing. A directory added over MNP reached node.toml and was invisible until a restart; one removed kept serving its files. Two front doors doing different things is the shape `ops.py` exists to prevent, and this was it: the loopback path worked and the MNP path did not, which is why it survived until the operator added a directory from a browser. Not awaited: a reload rescans, and a new library is minutes. The ack the caller sends carries the set the node is moving to, and the `index_sync` that follows the scan carries what it found. """ state = self._ctx.get("daemon_state") if not state: return reload_fn = state.get("reload_fn") if reload_fn: self._spawn(reload_fn()) return # No daemon to ask — a test harness, or a context assembled by hand. # Retarget directly, which is correct as long as the caller did not # edit the live set in place. indexer = state.get("indexers", {}).get(group_id) roots = state.get("groups_ctx", {}).get(group_id, {}).get("roots") if indexer and roots: await indexer.retarget(roots) async def _admin_exec_member_revoke( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: user_id = pending["subject"] if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"member_revoke:{user_id[:8]}") return try: result = await self._run_op( ops.revoke_member, user_id, self._group_id or "") await self._new_chat_epoch(self._group_id or "", "member_revoke") except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return # Anyone connected right now keeps the key they already unwrapped; what # they lose is the next one. Rotating it is the operator's call, and the # ack says so rather than implying this undid anything already read. # Every connection that account holds, not "the" one: with device # linking a person may be connected from several at once, and the # registry is keyed per connection precisely because it cannot hold # only one of them. for peer in self._sessions_of(user_id): try: await peer.close() except Exception: pass self._audit("member_revoke", user_id) self._send({ "type": MNP.MEMBER_REVOKE_ACK, "v": MNP_VERSION, "user_id": user_id, "reminder": result.get("reminder", ""), }) def _audit_pre_proof_fetch(self, mtype: str) -> None: """Record bundle access made before the GEK proof (C4).""" audit = self._ctx.get("audit_store") if not audit: return self._remote_ip = self._remote_ip or _get_remote_ip(self._pc) self._spawn(audit.log_event( user_id=getattr(self, "_pending_sub", "unknown"), event="pre_proof_fetch", ip=self._remote_ip, username=self._username or getattr(self, "_pending_username", ""), group_id=getattr(self, "_pending_group", "") or "", detail=mtype, )) def _audit_auth_failed(self, group_id: str, reason: str) -> None: audit = self._ctx.get("audit_store") if audit: self._remote_ip = _get_remote_ip(self._pc) self._spawn(audit.log_event( user_id="unknown", event="auth_failed", ip=self._remote_ip, group_id=group_id, detail=reason, )) def _spawn(self, coro) -> asyncio.Task: """Run a coroutine in the background and hold on to it. The reference is what keeps the task alive; the done callback is what stops the set growing. Anything that owns a resource for its lifetime — a transcode slot, an ffmpeg process — must go through here rather than `asyncio.ensure_future`. """ task = asyncio.ensure_future(coro) self._tasks.add(task) def _on_done(t): self._tasks.discard(t) if not t.cancelled() and t.exception(): log.error("Spawned task failed: %s", t.exception(), exc_info=t.exception()) task.add_done_callback(_on_done) return task def _app_directories_ack(self) -> dict: """ Every application's configured folders, for the handshake ack. Read off the group context rather than from a list of applications kept here, so this cannot name an application the node knows nothing else about — and cannot fail to name one the daemon does. A copy of the daemon's `APP_DIR_KEYS` lived here until 2026-09-10 and had already lost an entry, which made the app that entry belonged to the single one whose directories never reached a client. This module names an application in exactly one place, and it is `ALLOWED_APPS`. `_app_directories_ctx` is the only thing that puts a `*_directories` key in that context, and an absent one reads as none configured — never as "the whole group index". """ return {key: list(value or []) for key, value in self._group_ctx().items() if key.endswith("_directories")} def _group_ctx(self) -> dict: if "groups" in self._ctx and self._group_id: # `.get`, not a bare subscript. A config reload removes a group # from this map (daemon.py's reload does `groups_ctx.pop`) while # sessions connected to it are still open, and the next request # any of them made raised KeyError into _dispatch_message's # catch-all. An absent group now reads the way an unconfigured # one already does — the handlers all test for what they need — # instead of failing every request the session has left. return self._ctx["groups"].get(self._group_id) or {} return self._ctx def _indexing_status(self) -> dict: """ The counters of `_push_index_progress` (daemon.py), for the handshake ack — never a path, a filename or a root name, which stay local to the operator's own admin UI. Absent "progress" (context not loaded, or a group with no indexer at all) reads as idle rather than erroring. """ progress = self._group_ctx().get("progress") if progress is None: return {"scanning": False, "scanned_bytes": 0, "total_bytes": 0, "files_done": 0, "files_total": 0, "kind": "", "root_pos": -1, "queued": 0} return { "scanning": progress.scanning, "scanned_bytes": progress.scanned_bytes, "total_bytes": progress.total_bytes, "files_done": progress.files_done, "files_total": progress.files_total, "kind": progress.kind, "root_pos": progress.root_pos, "queued": len(progress.queued), } # ── Upload ceiling and transfer slots ──────────────────────────────────── def _max_upload_bytes(self) -> int: """The per-file upload ceiling this node is running with, in bytes. Read from the transport context rather than captured once, for the same reason the transfer pools are refreshed there: the operator can change it from the Node page or the CLI while an upload is running, and a ceiling that only applies after a restart is not the one they were shown. `None` means they have said nothing and the default stands. """ gb = self._ctx.get("max_upload_gb") if not gb: return MAX_UPLOAD_BYTES return max(1, int(float(gb) * GB_BYTES)) def _slots(self) -> "TransferSlots": """The node's transfer pools, shared across every peer and every group. On the transport context, not the session: it counts the node's transfers, not one browser's. Built once, for the same reason the transcode semaphore is — rebuilding it per call would hand every caller its own budget and cap nothing at all. """ slots = self._ctx.get("_transfer_slots") if slots is None: slots = TransferSlots() n = self._ctx.get("max_concurrent_downloads") u = self._ctx.get("max_concurrent_uploads") if n: slots.caps[transfers_mod.DOWNLOAD] = int(n) if u: slots.caps[transfers_mod.UPLOAD] = int(u) self._ctx["_transfer_slots"] = slots log.info("transfer: %s", slots.summary()) # Refreshed from the group context rather than only at construction: a # node serves several groups, each with its own signed cap, and the # pools are built by whichever group happens to transfer first. limits = self._group_ctx().get("transfer_limits") if limits and self._group_id: slots.group_limits[self._group_id] = dict(limits) return slots def _lease_of(self, tr) -> str: """What the `tr` on a request actually is, from the node's own record. `tr` is drawn by the client (§5.5) and arrives on every chunk request and every upload chunk. It was read as a boolean: *present* meant "this is a leased transfer", and nothing asked whether the node had ever granted such a lease — so any non-empty string skipped the leaseless ceiling and every cap the operator set. `touch()` has always answered exactly this question (`False` if it is not granted) and its answer was discarded. Three outcomes, because they deserve different treatment: - **`granted`** — a live lease of *this session*, and the transfer is under the caps it was granted against. The session is checked as well as the id: a lease belongs to a connection, and touching somebody else's would refresh their idle timer. - **`queued`** — the node has this lease and has not granted it. The client is jumping its own queue; refused, and no shipped client does it (the transfer store awaits the grant before it reads a byte). - **`none`** — the node has no such lease. Deliberately *not* a refusal: it is what a reconnect looks like from here, where the session's leases died with the old connection and the client is re-opening them, and it is what a client that never asked looks like. Both are then bounded by the leaseless ceiling instead — which is the residual §5.5 already states: a client that lies gets that bound's worth of files at a time, not the whole library. """ slots = self._ctx.get("_transfer_slots") if slots is None: return LEASE_NONE lease = slots.leases.get(tr) if lease is None or lease.session_key != self._registry_key: return LEASE_NONE if lease.state != "granted": return LEASE_QUEUED slots.touch(tr) return LEASE_GRANTED def _note_unleased(self, tr: str) -> None: """Say once that this connection transferred outside its lease. Once per session, not per chunk: the interesting fact is that it happened, and a per-chunk line would bury it under itself. The bound is the leaseless ceiling either way; this is what makes the residual visible to the operator rather than merely stated in a document. """ if self._unleased_noted: return self._unleased_noted = True log.info("transfer: %s sent chunk requests under an unknown lease %s " "— bounded by the leaseless ceiling", (self._user_id or "?")[:8], str(tr)[:8]) self._audit("transfer_unleased", str(tr)[:16]) def _transfer_state_msg(self, lease, state: str, reason: str = "") -> dict: slots = self._slots() out = { "type": MNP.TRANSFER_STATE, "v": MNP_VERSION, "tr": lease.tr, "state": state, "kind": lease.kind, "used": slots.member_in_use(lease.kind, lease.member), # `member_cap`, not the node-wide default: this group's own limit is # what `_has_room` enforces and what the handshake ack announces, so # reading the default here would have the widget contradicting both # — "1 of 2" in a group where the operator signed 5, or two slots # offered in a group limited to one. "cap": slots.member_cap(lease.kind, lease.member), "node_used": slots.in_use(lease.kind), "node_cap": slots.caps.get(lease.kind, transfers_mod.DEFAULT_MAX_CONCURRENT), } if state == "queued": out["ahead"] = slots.ahead_of(lease) if reason: out["reason"] = reason return out def _notify_transfer(self, lease, state: str, reason: str = "") -> None: """Push a lease's state to the connection that owns it. By session key, never by account: a lease belongs to one connection, and telling a member's other device that *its* transfer was granted is how a queue starts lying. """ session = self._peer_registry().get(lease.session_key) for candidate in ([session] if session else self._sessions_everywhere(lease.session_key)): try: candidate._send(self._transfer_state_msg(lease, state, reason)) except Exception: pass def _sessions_everywhere(self, session_key: str) -> list["WebRTCPeerSession"]: """The session with this key, whichever group it is in. `_peer_registry` is per group (finding H1) and the pools are node-wide, so a slot freed in one group can grant one in another: the peer to tell is not necessarily in this session's own registry. """ groups = self._ctx.get("groups") registries = ([g.get("_peers", {}) for g in groups.values()] if groups else [self._ctx.get("_peers", {})]) return [reg[session_key] for reg in registries if session_key in reg] def _announce(self, granted: list, ended: list | None = None) -> None: for lease, reason in (ended or []): self._notify_transfer( lease, "queued" if lease.state == "queued" else "closed", reason) for lease in granted: self._notify_transfer(lease, "granted") def _do_transfer_open(self, msg: dict) -> None: tr = str(msg.get("tr") or "")[:64] kind = str(msg.get("kind") or transfers_mod.DOWNLOAD) if not tr: self._send({"type": "error", "detail": "Missing transfer id", "code": "bad_transfer_id"}) return slots = self._slots() try: nbytes = int(msg.get("bytes") or 0) chunks = int(msg.get("chunks") or 0) except (TypeError, ValueError): self._send({"type": "error", "detail": "Invalid transfer size", "code": "bad_transfer_size", "tr": tr}) return lease, err = slots.open( tr=tr, kind=kind, session_key=self._registry_key, user_id=self._user_id or "", group_id=self._group_id or "", bytes=nbytes, chunks=chunks) if err: self._send({"type": "error", "detail": err, "code": err, "tr": tr}) return self._send(self._transfer_state_msg(lease, lease.state)) # INFO, not DEBUG. This is the line that answers "did the client ever # ask for a slot, and what was it told" when somebody reports a stuck # transfer — and a whole afternoon was spent concluding "the node saw # nothing" from a journal that could not have shown it. One line per # transfer is not a volume problem; turning the root logger up to DEBUG # to see it is, because aiortc logs every SCTP chunk. log.info("transfer: open %s %s -> %s (%s)", kind, tr[:8], lease.state, slots.summary()) self._ensure_transfer_sweeper() def _do_transfer_close(self, msg: dict) -> None: tr = str(msg.get("tr") or "")[:64] reason = str(msg.get("reason") or transfers_mod.REASON_DONE)[:32] slots = self._slots() held = slots.leases.get(tr) if held is not None and held.session_key != self._registry_key: # Closing somebody else's transfer would be a denial of service one # random id away. self._send({"type": "error", "detail": "not_your_transfer", "code": "not_your_transfer", "tr": tr}) return lease, granted = slots.close(tr, reason) if lease is not None: self._send(self._transfer_state_msg(lease, "closed", reason)) self._announce(granted) def _release_transfers(self) -> None: """Give back everything this connection held. Called from teardown.""" slots = self._ctx.get("_transfer_slots") if slots is None: return gone, granted = slots.release_session(self._registry_key) if gone: log.info("transfer: session gone, released %d (%s)", len(gone), slots.summary()) self._announce(granted) def _ensure_transfer_sweeper(self) -> None: """Start the maintenance task, once, and only while it has work. It reclaims what a session teardown cannot see — a grant nobody took up, a transfer that went quiet — and logs the one line that answers "was this peer ever in a queue" when somebody reports a stuck transfer. It stops when the last lease goes, so an idle node runs no timer. """ running = self._ctx.get("_transfer_sweeper") if running is not None and not running.done(): return ctx = self._ctx async def _sweep_loop() -> None: while True: await asyncio.sleep(TRANSFER_SWEEP_SECS) slots = ctx.get("_transfer_slots") if slots is None or not slots.leases: return ended, granted = slots.sweep() for lease, reason in ended: log.info("transfer: reclaimed %s (%s)", lease.tr[:8], reason) self._announce(granted, ended) log.debug("transfer: %s", slots.summary()) # Deliberately NOT `self._spawn`, which is otherwise the only way to # start a task here. `_spawn` ties a task to *this session's* set, and # `shutdown_tasks` cancels those when the peer leaves — so the sweeper # would die with whichever connection happened to open the first # transfer, and every other peer's abandoned lease would then never be # reclaimed. It belongs to the node, so the strong reference that keeps # it off the garbage collector lives on the transport context; the rule # `_spawn` exists for (asyncio holds only a weak reference) is satisfied # by that reference, not by which set it is in. task = asyncio.ensure_future(_sweep_loop()) ctx["_transfer_sweeper"] = task def _finished(done: asyncio.Task) -> None: if ctx.get("_transfer_sweeper") is done: ctx["_transfer_sweeper"] = None if not done.cancelled() and done.exception() is not None: # Nothing awaits this task, so an exception here would otherwise # be swallowed and idle leases would silently stop being # reclaimed — the failure mode is a node that fills up over days. log.error("transfer: sweeper died: %r", done.exception()) task.add_done_callback(_finished) def _register_peer(self) -> None: """Add this connection to its group's peer set. One place decides the key, and it is `_registry_key` — per connection, never per account. Written as a method so a test drives the real registration rather than a second copy of this line that agrees with it by construction. """ self._peer_registry()[self._registry_key] = self def _unregister_peer(self) -> None: self._peer_registry().pop(self._registry_key, None) def _sessions_of(self, user_id: str) -> list["WebRTCPeerSession"]: """Every live connection this account holds in this group. Never "the" connection: with device linking a person may be connected from a laptop and a phone at once, and an operation that acts on one of them at random is a revocation that leaves a session running. """ return [s for s in list(self._peer_registry().values()) if s._user_id == user_id] def _peer_registry(self) -> dict: """ Connected peers for THIS group only. Finding H1: this used to live on the shared transport context, so a chat message was broadcast to every peer on the node regardless of which group they had authenticated to. """ return self._group_ctx().setdefault("_peers", {}) def _user_names(self) -> dict: """Display-name cache, per group — same leak as _peer_registry (H1).""" return self._group_ctx().setdefault("_user_names", {}) def _do_ping(self, msg: dict) -> None: """Answer a liveness probe on an open channel, echoing the caller's token. Echoed rather than bare so a client can match the answer to the probe it sent and measure a round trip, instead of being reassured by a reply to some earlier one. """ self._send({"type": MNP.PONG, "v": MNP_VERSION, "token": msg.get("token")}) def _partial_uploads(self, ctx: dict) -> uploads_mod.PartialUploads: """This group's uploads in progress, created on first use. In the group context rather than on the session, so a client that reconnects finds its own upload where it left it — and so the reaper has something to ask "is anyone still writing this?". """ store = ctx.get("partial_uploads") if store is None: store = uploads_mod.PartialUploads() ctx["partial_uploads"] = store return store @staticmethod def _upload_lock(ctx: dict) -> asyncio.Lock: """ One lock per group, beside the state it protects. Not per session: `partial_uploads` lives in the group context so a client that reconnects finds its upload where it left it, which means two sessions of the same member share the position of one `.part` file. A lock on the session would let them interleave — and the loop no longer serializes them for free now that a chunk write is awaited. """ lock = ctx.get("upload_lock") if lock is None: lock = asyncio.Lock() ctx["upload_lock"] = lock return lock async def _do_file_upload(self, msg: dict) -> None: """ One chunk of an upload, in the order it arrived. The chunk ordering rule — `chunk_index != state.next_index` is refused — used to hold for free: the handler was synchronous, so nothing could run between the check and the `advance` that answers it. Awaiting the write opens that gap, and two chunks of one upload racing through it is a `.part` file with a hole in it or a chunk refused for arriving on time. So the check, the write and the advance are one critical section again. The order is the arrival order: `_dispatch_message` runs per message as it arrives and creates these tasks in that order, tasks start in creation order, and this lock is the first thing each one waits on, so its queue of waiters is in arrival order too. """ async with self._upload_lock(self._group_ctx()): await self._upload_chunk(msg) async def _upload_chunk(self, msg: dict) -> None: """ One chunk of an upload, sealed under the group key (MNP 2.0). Sealing this direction is not symmetry for its own sake. Downloads have been under a GEK-derived key since the beginning; uploads carried the filename and the raw bytes in plain msgpack, so the same file was ciphertext leaving a node and plaintext arriving at one. The node holds the GEK for its own group, so it opens the payload here — before it decides a destination, before it touches the disk — and refuses a chunk that does not open. `upload_id` is the correlation key and stays in clear; `filename`, `dir` and `root` moved inside the seal, which is why every refusal below names the upload rather than the file. A `code` says which refusal it is, and the client already knows what it sent. """ ctx = self._group_ctx() upload_id = str(msg.get("upload_id") or "")[:64] # Say the slot is being used, chunk by chunk, exactly as `_do_file_req` # does for a download. # # A grant nobody takes up is reclaimed after GRANT_DEADLINE_SECS and, on # the third miss, abandoned. Uploads were not gated by the lease, so the # file still arrived — but the widget follows the lease, so a 3.5 GB # upload showed "waiting, 0 ahead" for a minute and a half while it was # in fact transferring, and the node logged three reclaims against a # transfer that never stopped. Measured, from the journal: # # 11:52:49 open upload 919ebf54 -> granted # 11:53:19 reclaimed 919ebf54 (not_taken_up) # 11:54:19 reclaimed 919ebf54 (abandoned) # 11:55:48 Upload complete: ... (3 522 297 517 bytes) # # `_do_file_request` marks a lease alive for exactly the same reason; # both sides of a transfer have to say they are still moving, or the # sweeper reclaims whichever one forgot. # # And a queued lease is refused here rather than written to disk. There # is no leaseless fallback on this side — a write is never "browsing" — # so the two cases part company: a lease this node has not granted is a # member taking a slot they were told to wait for, and an unknown `tr` # is the reconnect case, where the client is re-opening leases that died # with the old connection and the four upload protections (§6.4) are # what bound it meanwhile. tr = str(msg.get("tr") or "")[:64] if tr: state = self._lease_of(tr) if state == LEASE_QUEUED: self._send({ "type": "error", "detail": "This upload is waiting for a slot.", "code": "lease_not_granted", "upload_id": upload_id, "tr": tr, }) return if state == LEASE_NONE: self._note_unleased(tr) gek = ctx.get("gek") if not gek: self._send({"type": "error", "detail": "Group encryption not initialized", "code": "no_group_key", "upload_id": upload_id}) return try: payload = file_upload_payload(gek, self._group_id or "", msg) except Exception: # Deliberately one answer for "not sealed at all" and "sealed wrong": # distinguishing them tells a peer which of the two it got right. # An MNP 1.x client lands here, which is the whole of the upgrade # story — everything else it does still works. self._audit("upload_refused", "unsealed") self._send({ "type": "error", "detail": "This upload did not open under the group key — the " "client may be running an older version", "code": "upload_not_sealed", "upload_id": upload_id, }) return filename = payload.get("filename") or "" data = payload.get("data") # From the clear part of the message, so peer-controlled and unchecked # by the AEAD. Everything below compares and adds to them. try: chunk_index = int(msg.get("chunk_index", 0)) total_chunks = int(msg.get("total_chunks", 1)) except (TypeError, ValueError): self._send({"type": "error", "detail": "Invalid chunk index", "code": "bad_chunk_index", "upload_id": upload_id}) return def _refuse(detail: str, code: str = "") -> None: """A refusal names the upload, never the file: the name is sealed.""" out = {"type": "error", "detail": detail, "upload_id": upload_id} if code: out["code"] = code self._send(out) # Types first, and before any state is created. What comes out of a # sealed payload is authenticated, not validated: it is msgpack a # member wrote, and `SAFE_UPLOAD_NAME.match(123)` raises where a # refusal was meant. if not isinstance(filename, str) or not filename: _refuse("Missing filename or data", "upload_incomplete") return # Bytes, always: base64 was the shape of the old plaintext `data` field # and there is no sealed message that can carry a string here. if not isinstance(data, (bytes, bytearray)): _refuse("Invalid chunk encoding", "bad_chunk_encoding") return chunk_bytes = bytes(data) if not SAFE_UPLOAD_NAME.match(filename): _refuse("Invalid filename", "invalid_filename") return roots: RootSet | None = ctx.get("roots") if not roots: _refuse("No directories configured for this group", "no_roots") return # The client names the root it is uploading into — it is browsing one, # and with several writable roots any other choice is a guess. It names # a root, never a path: the destination inside it is decided below and # is not negotiable, which is what keeps C5a closed. # # An unknown name is refused rather than falling back to a writable # root, because "the file went somewhere else" is discovered weeks # later — the same reason the old single upload root was never guessed. # `dir` is the folder being browsed, as a virtual path # (`Media/Films/1999`); `root` is the older, coarser form and is what # its first segment means on its own. Both are sealed now, so a refusal # below can no longer quote them back. target_rel = str(payload.get("dir") or "").strip().strip("/") target_root_name = (target_rel.split("/")[0] if target_rel else str(payload.get("root") or "").strip()) upload_root = None if target_root_name: upload_root = roots.by_name(target_root_name) if upload_root is None: _refuse("No such directory in this group", "no_such_root") return else: writable = roots.writable_roots upload_root = writable[0] if writable else None if upload_root is None: _refuse("No writable directory in this group", "no_writable_root") return if not upload_root.writable: _refuse("That directory is read-only", "root_read_only") self._audit("upload_refused", filename[:64]) return if not upload_root.available: _refuse("That directory is currently unavailable", "root_unavailable") return # The folder the sender is looking at, and no subdirectory of the node's # invention. # # Uploads used to be confined to `/uploads/`, created on demand. # That was the last of v5's quarantine (the per-user layer went on # 2026-08-14, for the same reason): a shared directory nobody can # organise is not a shared directory, and a folder appearing beside the # operator's library because somebody sent a file is the node deciding # how their disk is arranged. # # What made the quarantine worth having is not the subdirectory — it is # the filename allowlist, the size cap, the chunk ordering, and the # no-overwrite rule below. All four are unchanged. # # `resolve()` and not a join: it refuses `..`, absolute segments and # anything whose resolved form escapes its root, symlinks included. The # client names *where among the group's own folders*, never a path on # the operator's filesystem. if target_rel: target_dir = await off_disk(roots, roots.resolve, target_rel) if target_dir is None or not await off_disk(roots, target_dir.is_dir): _refuse("Not a directory in this group", "no_such_directory") return rel_dir = target_rel else: # A client that names nothing: the first writable root is where its # one destination is. target_dir = upload_root.path rel_dir = upload_root.name if not await off_disk(roots, target_dir.is_dir): _refuse("That directory is currently unavailable", "root_unavailable") return # Held by the group, not by this connection. # # This used to be `self._uploads`, on the session. A dropped link threw # the position away and the next chunk was refused with `not_started`: # an upload interrupted at 99% could only be started again from zero, on # a connection flaky enough to have interrupted it once. And the state # it lost was the only thing that knew about the `.part` file left # behind — see `uploads.orphaned_parts`, which is the other half of this. # # Keyed by member as well as by name, because a shared directory means # two people can be sending IMG_1234.jpg at the same moment and neither # may inherit the other's position. uploads = self._partial_uploads(ctx) user_id = self._user_id or "" state = uploads.get(user_id, rel_dir, filename) # A shared directory means two people can send the same name. Refusing the # second is safe but silly — everyone's camera produces IMG_1234.jpg — so # a free name is found instead. Never a replacement. stored_name = (state.stored_name if state else await off_disk(roots, _free_name, target_dir, filename)) tmp_path = target_dir / f"{stored_name}{uploads_mod.PART_SUFFIX}" final_path = target_dir / stored_name if chunk_index == UPLOAD_PROBE_INDEX: # "Where am I?", asked inside the seal rather than on a clear # message, because the answer is about a file whose name is exactly # what sealing this path was for. # # It writes nothing, creates no state and reserves no name: a client # that asks and then goes away has cost this node one reply. Every # check above has already run, so it cannot be used to ask questions # about a directory the caller may not write to. self._send(file_upload_ack_wire( gek, self._group_id or "", upload_id=upload_id, chunk_index=UPLOAD_PROBE_INDEX, filename=filename, # Only what is really on disk. Without state, `_free_name` above # picked a name nothing has claimed yet, and reporting it would # promise a destination the real chunk 0 may not choose. stored_as=state.stored_name if state else "", dir=rel_dir, resume_from=state.next_index if state else 0, )) return if chunk_index == 0: # Backstop: _free_name already guarantees this, and it stays because # it asserts the invariant where the write happens. if await off_disk(roots, final_path.exists): _refuse("File already exists", "already_exists") return state = uploads.start(user_id, rel_dir, filename, stored_name, part_path=tmp_path) elif state is None: _refuse("Upload not started", "not_started") return # Reject out-of-order or replayed chunks — otherwise chunk_index>0 appends # blindly to whatever .part file is already on disk. if chunk_index != state.next_index: _refuse("Unexpected chunk index", "bad_chunk_index") return if state.bytes + len(chunk_bytes) > self._max_upload_bytes(): uploads.drop(user_id, rel_dir, filename) await off_disk(roots, tmp_path.unlink, True) _refuse("Upload exceeds size limit", "too_large") return await off_disk(roots, _append_chunk, tmp_path, chunk_bytes, chunk_index == 0) uploads.advance(user_id, rel_dir, filename, chunk_index, len(chunk_bytes)) self._send(file_upload_ack_wire( gek, self._group_id or "", upload_id=upload_id, chunk_index=chunk_index, filename=filename, # What it is actually called on disk, which a chat attachment has to # reference and the uploader deserves to be told. stored_as=stored_name, dir=rel_dir, )) if chunk_index + 1 >= total_chunks: uploads.drop(user_id, rel_dir, filename) await off_disk(roots, tmp_path.rename, final_path) log.info("Upload complete: %s (%d chunks, %d bytes)", stored_name, total_chunks, state.bytes) self._audit("file_upload", f"{rel_dir}/{stored_name}") self._register_uploader(ctx, final_path) def _register_uploader(self, ctx: dict, file_path: Path) -> None: """ Record who sent this file, for the index entry that does not exist yet. The key recorded is the one this node pinned, not the one the token carried. `pk_user` was a hub-chosen claim, and it decided who could later delete the file: a hub issuing a token naming its own key could delete anyone's uploads on any node. Deletion is supposed to be authorized by the node, and this closes the last place where it was not. **The entry is not here to be tagged.** This used to walk `ctx["index"]` for the name just written and set the fields on it; at this point the watchdog has not fired (it debounces for two seconds and then hashes) and the file was a `.part` until the line above, which is not indexable — so the walk matched nothing, every time, and said nothing about it. The indexer stamps the entry from this record when it creates it. """ record = ctx.get("record_upload") if record is None: return self._spawn(record(file_path, self._user_id or "", self._pinned_pk or "")) # ── Admin operation challenge/response (finding H5) ────────────────────── def _node_pk_b64(self) -> str: return pk_to_b64(self._ctx["sk_node"].public_key()) def _issue_admin_challenge( self, op: str, subject: str, payload: dict | None = None, group_id: str | None = None, ) -> None: """ Ask the client to authorize `op` on `subject` with its Ed25519 identity key. The client is sent the transcript *fields*, not opaque bytes, so it can rebuild and inspect what it signs. The node keeps the authoritative copy and rebuilds the transcript itself at verification time — nothing signed is ever taken from the response message. `group_id` overrides the connection's group for cross-group operations (e.g. root management from a NodePage connection). """ gid = group_id if group_id is not None else (self._group_id or "") nonce = os.urandom(32) ts = int(time.time()) op_id = base64.b64encode(os.urandom(16)).decode() self._admin_ops[op_id] = { "op": op, "subject": subject, "nonce": nonce, "ts": ts, "payload": payload or {}, "group_id": gid, } self._send({ "type": MNP.ADMIN_CHALLENGE, "v": MNP_VERSION, "op_id": op_id, "op": op, "subject": subject, "nonce": base64.b64encode(nonce).decode(), "ts": ts, "node_pk": self._node_pk_b64(), "group_id": gid, }) @staticmethod def _verify_sig(pk: Ed25519PublicKey | None, transcript: bytes, sig: bytes) -> bool: if pk is None: return False try: pk.verify(sig, transcript) return True except Exception: return False async def _load_pinned_pk(self) -> None: """ A key this node pinned for the account we just authenticated. `get_identity` returns the account's **oldest** live device, which is a stand-in, not an answer: the handshake never said which device is on this connection. `device_hello` is the answer, and it arrives later — so this must never overwrite a confirmed one. It is spawned from `_complete_handshake` and can therefore finish *after* a fast client has already identified itself, which is exactly the ordering that would put the wrong key back. """ roster = self._ctx.get("roster") if roster is None or not self._user_id or self._device_confirmed: return ident = await roster.get_identity(self._user_id) if ident and not self._device_confirmed: self._pinned_pk = ident["pk_ed25519"] def _is_node_admin(self) -> bool: """ Whether the **account** on this connection is the one the node belongs to. This is a display hint and half of a check — never authority on its own. `self._user_id` is the `sub` of a JWT the hub issued, so read alone it says "the hub says you are the owner", which is the one thing NS4 and M3 rule out: a hub that can name the operator can install itself as node administrator. It rides the handshake ack so a client knows whether to offer the Node page at all, and every operation is gated on `_operator_device()` below. """ node_user_id = self._ctx.get("node_user_id") return bool(node_user_id and self._user_id == node_user_id) async def _operator_device(self) -> bool: """ Whether this connection may run the node's own controls. Two things, and the second is the one that cannot be forged: - the account is the one this node belongs to (`_is_node_admin`), which is what keeps node-wide controls with the machine's owner rather than with every paired operator of every group on it; and - **the device on this connection proved a key the node pinned as an operator**. `device_hello` is signed over a transcript naming this node, this group and this connection's nonce, and `operator_pks()` is rebuilt from the roster on each call, so an unpinned browser and a revoked one are both refused at once. The second clause is the fix for the door this used to leave open. `node_status`, `node_settings_set`, `roster_read`, `denylist_read`, `denylist_clear` and `node_reload` were gated on the account id alone — a value the hub chooses. An active hub that can also reach the group key (which §3.5 concedes it can in an open-join group) could therefore mint a token for the owner's account and read `node_status`, which lists every group on the node with the operator's **absolute paths**, or clear the denylist, which is the persisted revocation H4 exists to keep. It holds no user keys and cannot countersign anything, so it cannot produce a `device_hello` — which is the same property device linking rests on (§3.3), applied to the node's own surface. """ if not self._is_node_admin(): return False if not self._device_confirmed or not self._pinned_pk: return False roster = self._ctx.get("roster") if roster is None: return False return self._pinned_pk in await roster.operator_pks() def _has_admin_authority(self) -> bool: """ Cheap synchronous pre-check: is there anyone who could authorize this? Only decides whether to issue a challenge at all — the gate is `_verify_admin_sig`. The flag is set at startup and refreshed in-process when an operator pairs. """ return bool(self._ctx.get("has_admin_authority")) async def _verify_admin_sig(self, transcript: bytes, sig: bytes) -> bool: """ Check a signature against every key holding node-operator authority. Read from the roster on each call rather than cached: revoking a paired browser must take effect immediately, and admin operations are rare enough that a SQLite read costs nothing. There is one source of operator authority and this is it. `admin_pk_ed25519` in node.toml used to be honoured alongside the roster; it is gone, and a config that still names it is warned about at startup rather than obeyed. """ roster = self._ctx.get("roster") if roster is None: return False for pk_b64 in await roster.operator_pks(): try: pk = Ed25519PublicKey.from_public_bytes(base64.b64decode(pk_b64)) except Exception: continue if self._verify_sig(pk, transcript, sig): return True return False def _do_admin_response(self, msg: dict) -> None: op_id = msg.get("op_id", "") sig_b64 = msg.get("signature", "") pending = self._admin_ops.pop(op_id, None) if not pending: self._send({"type": "error", "detail": "No pending admin operation"}) return if time.time() - pending["ts"] > ADMIN_CHALLENGE_TTL: self._send({"type": "error", "detail": "Admin challenge expired"}) return try: sig_bytes = base64.b64decode(sig_b64) except Exception: self._send({"type": "error", "detail": "Invalid signature encoding"}) return transcript = admin_transcript( op=pending["op"], node_pk_b64=self._node_pk_b64(), group_id=(pending["group_id"] if pending.get("group_id") is not None else (self._group_id or "")), subject=pending["subject"], nonce=pending["nonce"], ts=pending["ts"], ) if pending["op"] == OP_FILE_DELETE: self._spawn( self._admin_exec_file_delete(pending, transcript, sig_bytes)) elif pending["op"] == OP_DIR_DELETE: self._spawn( self._admin_exec_dir_delete(pending, transcript, sig_bytes)) elif pending["op"] == OP_MEMBER_REVOKE: self._spawn( self._admin_exec_member_revoke(pending, transcript, sig_bytes)) elif pending["op"] == OP_INVITE_CREATE: self._spawn( self._admin_exec_invite_create(pending, transcript, sig_bytes)) elif pending["op"] == OP_INVITE_LINK_CREATE: self._spawn( self._admin_exec_invite_link_create(pending, transcript, sig_bytes)) elif pending["op"] == OP_INVITE_CANCEL: self._spawn( self._admin_exec_invite_cancel(pending, transcript, sig_bytes)) elif pending["op"] == OP_GEK_ROTATE: self._spawn( self._admin_exec_gek_rotate(pending, transcript, sig_bytes)) elif pending["op"] == OP_MEMBER_UNPIN: self._spawn( self._admin_exec_member_unpin(pending, transcript, sig_bytes)) elif pending["op"] == OP_APPS_ENABLED: self._spawn( self._admin_exec_apps_enabled(pending, transcript, sig_bytes)) elif pending["op"] == OP_TRANSFER_LIMITS: self._spawn( self._admin_exec_transfer_limits(pending, transcript, sig_bytes)) elif pending["op"] == OP_SET_SCAN_SETTINGS: self._spawn( self._admin_exec_set_scan_settings(pending, transcript, sig_bytes)) elif pending["op"] == OP_TMDB_CONFIG: self._spawn( self._admin_exec_tmdb_config(pending, transcript, sig_bytes)) elif pending["op"] == OP_TMDB_ENABLED: self._spawn( self._admin_exec_tmdb_enabled(pending, transcript, sig_bytes)) elif pending["op"] == OP_TMDB_OVERRIDE: self._spawn( self._admin_exec_tmdb_override(pending, transcript, sig_bytes)) elif pending["op"] == OP_TMDB_REMATCH: self._spawn( self._admin_exec_tmdb_rematch(pending, transcript, sig_bytes)) elif pending["op"] == OP_MUSICBRAINZ_ENABLED: self._spawn( self._admin_exec_musicbrainz_enabled(pending, transcript, sig_bytes)) elif pending["op"] == OP_ROOT_ADD: self._spawn( self._admin_exec_root_add(pending, transcript, sig_bytes)) elif pending["op"] == OP_ROOT_REMOVE: self._spawn( self._admin_exec_root_remove(pending, transcript, sig_bytes)) elif pending["op"] == OP_APP_DIRECTORIES: self._spawn( self._admin_exec_app_directories(pending, transcript, sig_bytes)) elif pending["op"] == OP_CHAT_DIRECTORY: self._spawn( self._admin_exec_chat_directory(pending, transcript, sig_bytes)) elif pending["op"] == OP_CHAT_LINK_PREVIEW: self._spawn( self._admin_exec_chat_link_preview(pending, transcript, sig_bytes)) elif pending["op"] == OP_SEARCH_LISTED: self._spawn( self._admin_exec_search_listed(pending, transcript, sig_bytes)) elif pending["op"] == OP_CHAT_EPOCH: self._spawn( self._admin_exec_chat_epoch(pending, transcript, sig_bytes)) elif pending["op"] == OP_ROOT_UPDATE: self._spawn( self._admin_exec_root_update(pending, transcript, sig_bytes)) elif pending["op"] == OP_ROOT_EJECT: self._spawn( self._admin_exec_root_eject(pending, transcript, sig_bytes)) elif pending["op"] == OP_ROOT_PLUG: self._spawn( self._admin_exec_root_plug(pending, transcript, sig_bytes)) elif pending["op"] == OP_GROUP_ATTACH: self._spawn( self._admin_exec_group_attach(pending, transcript, sig_bytes)) elif pending["op"] == OP_GROUP_DETACH: self._spawn( self._admin_exec_group_detach(pending, transcript, sig_bytes)) else: self._send({"type": "error", "detail": "Unknown admin operation"}) async def _admin_exec_invite_create( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: # Node operator only. A group admin who does not run the node has no # authority over who this node admits (deny by default). Delegation is # designed but deferred — see docs/MESHBAY_DESIGN.md §3.4. if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"invite_create:{pending['subject'][:16]}") return payload = pending["payload"] try: result = await self._run_op( ops.create_invite, payload["group_id"], payload.get("username", ""), user_id=payload["user_id"], created_by=self._user_id or "", ) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("invite_create", f"target={payload['user_id'][:8]}") self._send({ "type": MNP.INVITE_RESULT, "v": MNP_VERSION, "code": result["code"], "expires_at": result["expires_at"], "user_id": result["user_id"], "username": result.get("username", ""), }) async def _admin_exec_invite_link_create( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", "invite_link_create") return try: result = await self._run_op( ops.create_link_invite, pending["payload"]["group_id"], created_by=self._user_id or "") except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("invite_link_create", f"invite={result['invite_id'][:8]}") self._send({ "type": MNP.INVITE_LINK_RESULT, "v": MNP_VERSION, "code": result["code"], "invite_id": result["invite_id"], "expires_at": result["expires_at"], "group_id": result["group_id"], }) async def _admin_exec_invite_cancel( self, pending: dict, transcript: bytes, sig: bytes, ) -> None: if not await self._verify_admin_sig(transcript, sig): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"invite_cancel:{pending['subject'][:8]}") return payload = pending["payload"] try: await self._run_op(ops.cancel_invite, payload["group_id"], payload["invite_id"]) except ops.OpError as e: self._send({"type": "error", "detail": e.message}) return self._audit("invite_cancel", f"invite={payload['invite_id'][:8]}") self._send({"type": "ack", "v": MNP_VERSION, "detail": "invite_cancelled", "invite_id": payload["invite_id"]}) def _send(self, obj: dict) -> None: # Stamp the reply with the id of the request being answered, so the # caller never has to guess. Only for this session's own replies: a # handler that also pushes to other peers (a chat broadcast, an index # delta) reaches them through *their* _send, where the owner no longer # matches and nothing is stamped — those messages answer no request. # An explicit req_id already on the object wins, and an unsolicited # push (no request in scope) carries none, exactly as before. owner, req_id = _REPLY_TO.get() if req_id is not None and owner is self and "req_id" not in obj: obj = {**obj, "req_id": req_id} if self._channel and self._channel.readyState == "open": self._channel.send(_pack(obj)) else: log.warning("WebRTC send skipped: channel=%s", self._channel.readyState if self._channel else "none") async def shutdown_tasks(self) -> None: """Stop everything this session is doing and give back what it holds. Separate from close() because the connection-state handler runs while aiortc is already tearing the peer connection down — calling pc.close() from in there would re-enter it. What matters for the transcode slot is here: cancelling the task runs the exit of its `async with sem`. """ self._stop_stream() # Before the tasks are cancelled: a lease is not held by a task, so # nothing else would give it back, and this hook is the one place every # way of walking away arrives at (see the connectionstatechange handler, # which calls it for a closed tab, a quit browser and a dead network # alike). self._release_transfers() for task in list(self._tasks): task.cancel() if self._tasks: await asyncio.gather(*self._tasks, return_exceptions=True) async def close(self) -> None: self._audit("disconnect") self._release_transfers() if self._user_id: self._unregister_peer() await self.shutdown_tasks() await self._pc.close() def _append_chunk(tmp_path: Path, chunk_bytes: bytes, first: bool) -> None: """Add one chunk to a partial upload. Blocking; called through `off_disk`.""" with open(tmp_path, "wb" if first else "ab") as f: f.write(chunk_bytes) class WebRTCTransport: """ Manages WebRTC peer connections for browser clients. Usage: transport = WebRTCTransport(sk_node, hub_pk_pem, gek, roots, index) answer_sdp = await transport.handle_offer(offer_sdp, peer_id) # Return answer_sdp to the browser via hub signaling """ def __init__( self, sk_node: Ed25519PrivateKey, hub_pk_pem: bytes, gek: bytes, roots: RootSet, index: GroupIndex, groups: dict[str, dict] | None = None, denylist: Any | None = None, stun_servers: list[str] | None = None, max_concurrent_streams: int | None = None, max_concurrent_downloads: int | None = None, max_concurrent_uploads: int | None = None, max_upload_gb: float | None = None, transcode_incompatible_video: bool = True, ): self._ctx: dict[str, Any] = { "sk_node": sk_node, "hub_pk_pem": hub_pk_pem, "gek": gek, "roots": roots, "index": index, "_peers": {}, # None means "the operator said nothing" — the default applies. It # is read once, when the first stream builds the semaphore. "max_concurrent_streams": max_concurrent_streams, # Read once, when the first transfer builds the pools. None means # the operator said nothing and transfers.py's defaults apply. "max_concurrent_downloads": max_concurrent_downloads, "max_concurrent_uploads": max_concurrent_uploads, # The per-file upload ceiling, in GB. None means the operator said # nothing and MAX_UPLOAD_BYTES stands. "max_upload_gb": max_upload_gb, # Operator opt-out (node.toml) for the HEVC-etc. transcode # fallback in _stream_video_inner — real CPU cost, unlike copy. "transcode_incompatible_video": transcode_incompatible_video, } if groups: self._ctx["groups"] = groups if denylist: self._ctx["denylist"] = denylist from meshbay_node.config import DEFAULT_STUN_SERVERS self._stun = stun_servers or list(DEFAULT_STUN_SERVERS) self._sessions: dict[str, WebRTCPeerSession] = {} self._reapers: set[asyncio.Task] = set() def set_capacity(self, *, max_concurrent_streams: int | None = None, max_concurrent_downloads: int | None = None, max_concurrent_uploads: int | None = None, max_upload_gb: float | None = None) -> dict: """Resize a live pool without restarting the daemon. `ops.set_node_settings` used to do this by assigning `webrtc._stream_sem`, an attribute that has never existed — the pool is `ctx["_transcode_sem"]`, and `hasattr(webrtc, "_stream_sem")` is always False. So the hot-swap was a no-op and **`max_concurrent_streams` has never taken effect from the Node page without a restart**, contrary to docs/MESHBAY_DESIGN.md §6.8. This is the one implementation, on the object that owns the state, so the next two caps do not each grow their own copy of the mistake. What resizing means, stated because it is a decision and not a detail: **the new cap governs new streams; the ones already running are never interrupted.** A slot is held for the length of a film, so lowering the cap below what is in flight cannot take a viewer's film away — it stops the next one starting. The replacement pool is therefore created with the permits that remain (`new - in_flight`, floored at zero), not with a full set, or lowering the cap would briefly allow more viewers than either the old value or the new one. """ changed: dict = {} if max_concurrent_streams is not None: n = int(max_concurrent_streams) if n < 1: raise ValueError("max_concurrent_streams must be positive") before = self._ctx.get("max_concurrent_streams") self._ctx["max_concurrent_streams"] = n if self._ctx.get("_transcode_sem") is not None: in_flight = self._ctx.get("_streams_in_flight", 0) self._ctx["_transcode_sem"] = asyncio.Semaphore( max(0, n - in_flight)) log.info("stream: capacity %s -> %d (%d in flight, %d free now)", before, n, in_flight, max(0, n - in_flight)) else: # Nothing has streamed yet; the pool is built from this value on # first use, so there is nothing to resize. log.info("stream: capacity %s -> %d (no pool built yet)", before, n) changed["max_concurrent_streams"] = n pools = {} if max_concurrent_downloads is not None: pools[transfers_mod.DOWNLOAD] = int(max_concurrent_downloads) if max_concurrent_uploads is not None: pools[transfers_mod.UPLOAD] = int(max_concurrent_uploads) for key, value in pools.items(): if value < 1: raise ValueError(f"max_concurrent_{key}s must be positive") if pools: # Kept on the context whether or not a pool exists yet: the pools # are built on the first transfer, and would otherwise come up with # the defaults after an operator had already changed them. for key, value in pools.items(): self._ctx[f"max_concurrent_{key}s"] = value changed[f"max_concurrent_{key}s"] = value slots = self._ctx.get("_transfer_slots") if slots is not None: granted = slots.set_caps(node=pools) log.info("transfer: capacity now %s (%d started at once)", slots.summary(), len(granted)) # Raising a cap can start queued transfers immediately, and the # peers waiting on them have to be told: a grant nobody hears # about is the "stuck at waiting" report this design exists to # prevent. for lease in granted: self._notify_granted(lease) if max_upload_gb is not None: gb = float(max_upload_gb) if gb <= 0: raise ValueError("max_upload_gb must be greater than zero") self._ctx["max_upload_gb"] = gb changed["max_upload_gb"] = gb log.info("upload: per-file ceiling now %g GB", gb) return changed def _notify_granted(self, lease) -> None: """Tell the connection that owns `lease` it may start. On the transport rather than the session because a cap change has no session behind it — it arrives from the loopback API. """ groups = self._ctx.get("groups") registries = ([g.get("_peers", {}) for g in groups.values()] if groups else [self._ctx.get("_peers", {})]) for reg in registries: session = reg.get(lease.session_key) if session is not None: try: session._send( session._transfer_state_msg(lease, "granted")) except Exception: pass return async def handle_offer( self, offer_sdp: str, peer_id: str, ) -> tuple[str, list[dict]]: """ Process a WebRTC SDP offer from a browser client. Returns (answer_sdp, ice_candidates) to relay back via hub signaling. ICE candidates are embedded in the SDP (aiortc gathers before returning). """ from aiortc import RTCConfiguration, RTCIceServer # aiortc keeps only the first STUN entry it sees here; the actual # multi-server fan-out is done by transport/stun_multi, which patches # aioice. The full list is still passed so a one-server deploy and the # tests that read `_stun` stay coherent. config = RTCConfiguration( iceServers=[RTCIceServer(urls=s) for s in self._stun] if self._stun else [] ) # Before anything is allocated. Every offer costs an RTCPeerConnection # with its own DTLS and SCTP stacks, and nothing here used to bound how # many a node would hold: the hub meters offers *per account* # (signaling.py), which is a limit on each caller and not on this # machine, so the cost # grew with the number of members in the group. An operator's node must # not be exhaustible by the people they invited. if len(self._sessions) >= MAX_PEER_SESSIONS: log.warning("Refusing WebRTC offer: %d peer sessions already open", len(self._sessions)) raise RuntimeError("Node is at its peer-connection limit") pc = RTCPeerConnection(configuration=config) session = WebRTCPeerSession(pc, self._ctx, peer_id=peer_id) self._sessions[peer_id] = session self._reap_if_unauthenticated(peer_id) @pc.on("datachannel") def on_datachannel(channel: RTCDataChannel): log.info("WebRTC DataChannel opened: %s (peer=%s)", channel.label, peer_id) session._setup_channel(channel) if _WEBRTC_TRACE: @pc.on("iceconnectionstatechange") def on_ice_state_change(): log.info("WebRTC ICE state: %s (peer=%s)", pc.iceConnectionState, peer_id) @pc.on("connectionstatechange") async def on_state_change(): state = pc.connectionState log.info("WebRTC connection state: %s (peer=%s)", state, peer_id) if state in ("failed", "closed"): gone = self._sessions.pop(peer_id, None) if gone is not None: # Popping only forgets the session. Its stream went on # transcoding until the credit timeout — measured at 91s # after the connection closed — holding one of the node's # two slots the whole time. Closing the viewer, the tab or # the browser all arrive here, so this is the one place # that covers every way of walking away. # # And the group's peer set forgets it too, as close() does: # otherwise every later broadcast to the group is written # to a closed channel, and every reconnect leaves one more # dead session held until the node restarts. if gone._user_id: gone._unregister_peer() await gone.shutdown_tasks() offer = RTCSessionDescription(sdp=offer_sdp, type="offer") await pc.setRemoteDescription(offer) answer = await pc.createAnswer() gather_start = time.monotonic() await pc.setLocalDescription(answer) # ICE gathering runs inside setLocalDescription (non-trickle). A slow or # unreachable STUN server shows up here as seconds of wait and zero # srflx lines — the symptom the multi-server fan-out exists to prevent. answer_sdp = pc.localDescription.sdp srflx = answer_sdp.count(" typ srflx") # The host addresses this node put in the answer. When a peer reports # "DataChannel closed" the first question is whether the node offered # anything that peer could route to at all — on a NAT'd host or a VM the # only host candidate is an address no one else can reach, and the log # otherwise looks identical to a working connection. host_addrs: set[str] = set() for line in answer_sdp.splitlines(): if line.startswith("a=candidate:") and " typ host " in line: parts = line.split() if len(parts) > 5: host_addrs.add(parts[4]) log.info( "WebRTC answer ready for peer=%s (ICE gather %.2fs, host: %s, %d srflx)", peer_id, time.monotonic() - gather_start, ", ".join(sorted(host_addrs)) or "none", srflx) return answer_sdp, [] def _reap_if_unauthenticated(self, peer_id: str) -> None: """Close a session that never completes the handshake. A peer that connects and then says nothing is indistinguishable from a working one until it is asked to prove something, and it was never asked: `connectionstatechange` reaps a connection that *fails*, and one that succeeds and stays silent was held for the node's lifetime. That is the cheapest way to spend someone else's memory — no GEK, no token, no group, just an open connection. `_user_id` is set by the GEK proof (`_do_handshake_response`), so it is the one honest test of whether this peer ever became anybody. """ async def reap() -> None: try: await asyncio.sleep(UNAUTHENTICATED_SESSION_TIMEOUT) session = self._sessions.get(peer_id) if session is not None and not session._user_id: log.warning("Closing peer %s: no handshake within %ds", peer_id[:8], UNAUTHENTICATED_SESSION_TIMEOUT) await self.close_peer(peer_id) except asyncio.CancelledError: raise except Exception as e: log.warning("Reaping peer %s failed: %s", peer_id[:8], e) # Held in a set for the same reason every other task here is: asyncio # keeps only a weak reference, and a reaper collected mid-sleep reaps # nothing (see WebRTCPeerSession.__init__). task = asyncio.ensure_future(reap()) self._reapers.add(task) task.add_done_callback(self._reapers.discard) async def close_peer(self, peer_id: str) -> None: session = self._sessions.pop(peer_id, None) if session: await session.close() async def close_all(self) -> None: for task in list(self._reapers): task.cancel() self._reapers.clear() for session in list(self._sessions.values()): await session.close() self._sessions.clear() @property def active_peers(self) -> int: return len(self._sessions)