Source code for fleetmesh_node.protocols.ssb.package

"""fleetmesh-protocol-ssb: Secure Scuttlebutt (SSB) protocol package.

Conforms to ProtocolPackage (fleetmesh_core.wire.interfaces.ProtocolPackage).
Integrates the SSB sidecar daemon, client, MuxRPC routing, and SSBRung
into the Fleetmesh protocol host and transport ladder.
"""
from __future__ import annotations

from fleetmesh_core.wire import spelling  # noqa: E402

import json
import os
from typing import Any, Mapping, Optional

from fleetmesh_core.crypto.ssb import (
    SSB_MAINNET_NETWORK_KEY,
    SSBCryptoError,
    format_ssb_feed_id,
    parse_ssb_feed_id,
)
from fleetmesh_core.wire.interfaces import (
    ProtocolHealth,
    ProtocolHostRouter,
    ProtocolIdentityAdapter,
)
from fleetmesh_node.protocols.base import Ed25519IdentityAdapter
from fleetmesh_node.transport.ssb_rung import SSBRung
from fleetmesh_node.sidecar.fleetmesh_ssb import SSBSidecarClient, SSBSidecarDaemon

__all__ = [
    'SSBIdentityAdapter',
    'SSBProtocolPackage',
]


[docs]class SSBIdentityAdapter(Ed25519IdentityAdapter): """Identity and assertion adapter for Secure Scuttlebutt (@pubkey.ed25519)."""
[docs] def __init__(self, private_key: Any = None, feed_id: Optional[str] = None): super().__init__(private_key=private_key) self._feed_id = feed_id if self.private_key is not None and not self._feed_id and hasattr(self.private_key, 'public_key'): pk_raw = self.private_key.public_key().public_bytes_raw() self._feed_id = format_ssb_feed_id(pk_raw)
[docs] def resolve_id(self, uri: str) -> Optional[str]: """Resolves SSB feed ID from raw feed ID or ssb: URI.""" clean = uri.strip() if clean.startswith("ssb:"): clean = clean[4:] if clean.startswith("@") and clean.endswith(".ed25519"): try: parse_ssb_feed_id(clean) return clean except (SSBCryptoError, ValueError): return None return None
[docs] def verify_assertion(self, payload: bytes, signature: bytes, pubkey: str) -> bool: try: if pubkey.startswith("@") and pubkey.endswith(".ed25519"): pk_bytes = parse_ssb_feed_id(pubkey) elif spelling.is_hex(pubkey, 64, upper=True): pk_bytes = bytes.fromhex(pubkey) else: pk_bytes = pubkey.encode('utf-8') except (SSBCryptoError, ValueError): return False return self._verify_ed25519_bytes(payload, signature, pk_bytes)
[docs]class SSBProtocolPackage: """The Secure Scuttlebutt (SSB) protocol suite for Fleetmesh.""" name: str = 'ssb' version: str = '1.0.0' standards: tuple[str, ...] = ( 'ssb', 'SSB-SHS', 'SSB-BoxStream', 'SSB-MuxRPC', 'secret-handshake', 'boxstream', 'muxrpc', )
[docs] def __init__( self, node_dir: Optional[str] = None, socket_path: Optional[str] = None, tcp_host: str = "127.0.0.1", tcp_port: int = 8008, network_key: bytes = SSB_MAINNET_NETWORK_KEY, secret_key_bytes: Optional[bytes] = None, sidecar_client: Optional[SSBSidecarClient] = None, auto_start_sidecar: bool = False, private_key: Optional[Any] = None, ): self.node_dir = node_dir or "/tmp/fleetmesh-ssb" self.socket_path = socket_path or os.path.join(self.node_dir, "ssb.sock") self.tcp_host = tcp_host self.tcp_port = tcp_port self.network_key = network_key self.secret_key_bytes = secret_key_bytes self.private_key = private_key self.auto_start_sidecar = auto_start_sidecar if self.private_key is not None and not self.secret_key_bytes: try: self.secret_key_bytes = self.private_key.private_bytes_raw() except Exception: pass self._client = sidecar_client self._daemon: Optional[SSBSidecarDaemon] = None self._host: Optional[ProtocolHostRouter] = None self._enabled: bool = True self.config: Mapping[str, Any] = {}
[docs] def configure(self, config: Mapping[str, Any]) -> None: self.config = dict(config) self._enabled = self.config.get('enabled', True) if 'socket_path' in self.config: self.socket_path = self.config['socket_path'] if 'tcp_host' in self.config: self.tcp_host = self.config['tcp_host'] if 'tcp_port' in self.config: self.tcp_port = self.config['tcp_port'] if 'auto_start_sidecar' in self.config: self.auto_start_sidecar = self.config['auto_start_sidecar'] if 'network_key' in self.config: nk = self.config['network_key'] self.network_key = bytes.fromhex(nk) if isinstance(nk, str) else nk
@property def client(self) -> Optional[SSBSidecarClient]: if self._client is not None: return self._client if os.path.exists(self.socket_path): self._client = SSBSidecarClient(self.socket_path) return self._client
[docs] def identity_adapter(self, keystore: Any = None) -> Optional[ProtocolIdentityAdapter]: priv = self.private_key if priv is None and keystore is not None: # Check if keystore has ed25519 key priv = getattr(keystore, 'ed25519_sk', None) return SSBIdentityAdapter(private_key=priv)
[docs] def mount_ingress(self, host: ProtocolHostRouter) -> None: if not self._enabled: return self._host = host # Register status inspection route for HTTP multiplexer def _handle_ssb_status(conn: Any, req: Any = None) -> Any: st = self.health() payload = { "healthy": st.healthy, "status": st.status, "connections_active": st.connections_active, "messages_in": st.messages_in, "messages_out": st.messages_out, "errors": list(st.errors), "socket_path": self.socket_path, "tcp_port": self.tcp_port, } body = json.dumps(payload, indent=2).encode('utf-8') if conn is not None and hasattr(conn, 'sendall'): from fleetmesh_node.transport import ws ws.http_response(conn, "200 OK", body, "application/json") return True return 200, {"Content-Type": "application/json"}, body if hasattr(host, 'mount_route'): host.mount_route('/ssb/status', _handle_ssb_status, methods=('GET',), owner=self.name) elif hasattr(host, 'register_route'): host.register_route("GET", "/ssb/status", _handle_ssb_status, owner=self.name)
[docs] def transport_rung(self, context: Any = None) -> Optional[Any]: if not self._enabled: return None router = getattr(context, 'router', None) or context return SSBRung( router=router, sidecar_client=self.client, socket_path=self.socket_path, )
[docs] def compartments(self) -> tuple[type[Any], ...]: return ()
[docs] def start(self) -> None: if not self._enabled: return if self.auto_start_sidecar and self._daemon is None: self._daemon = SSBSidecarDaemon( node_dir=self.node_dir, tcp_port=self.tcp_port, bind_host=self.tcp_host, uds_path=self.socket_path, network_key=self.network_key, secret_key_bytes=self.secret_key_bytes, ) self._daemon.start() self.tcp_port = self._daemon.tcp_port self._client = SSBSidecarClient(self.socket_path)
[docs] def stop(self) -> None: if self._client is not None: self._client.close() self._client = None if self._daemon is not None: self._daemon.stop() self._daemon = None
[docs] def health(self) -> ProtocolHealth: if not self._enabled: return ProtocolHealth( healthy=True, status="disabled", connections_active=0, messages_in=0, messages_out=0, errors=(), ) client = self.client if client is not None and os.path.exists(self.socket_path): try: st = client.status() if st.get('ok'): return ProtocolHealth( healthy=True, status="serving", connections_active=st.get('peers_connected', 0), messages_in=st.get('messages_count', 0), messages_out=0, errors=(), ) except Exception as e: return ProtocolHealth( healthy=False, status="unreachable", connections_active=0, messages_in=0, messages_out=0, errors=(str(e),), ) return ProtocolHealth( healthy=True, status="configured", connections_active=0, messages_in=0, messages_out=0, errors=(), )
[docs] def descriptor_capabilities(self) -> tuple[tuple[str, str], ...]: if not self._enabled: return () return ( ('c', 'ssb'), ('c', 'shs'), ('c', 'muxrpc'), )