"""FleetMesh Hosted Leaf Relay & Mediator (`node.protocols.textile.hosted_relay`).
Hosts an embedded Nostr/Fleetmesh Leaf Relay & Mediator, advertising a signed kind 11801
descriptor, mediating DIDComm v2 envelopes (coordinate-mediation/2.0, routing/2.0,
messagepickup/2.0 & 3.0), and indexing the 4-layer Textile hierarchy (Fibers -> Strands -> Fabrics -> Quilts).
"""
from __future__ import annotations
import os
import threading
import time
from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence
from cryptography.hazmat.primitives.asymmetric import x25519
from fleetmesh_core.identity import identity
from fleetmesh_core.textile import leaf_crypto as lc
from .leaf_relay import (
KIND_FABRIC,
KIND_FIBER,
KIND_QUILT,
KIND_STRAND,
NegentropyServer,
build_engine_textile_inventory,
det_hex,
serve_relay_websocket,
)
PROTOCOL_VERSION = "fleetmesh/0.1-draft"
PROTOCOL_DIGEST = "695a868c3f2b343dba6f134cc23706bf8e48db392122cce63e06b69b3f92b7a7"
SOFTWARE_URL = identity.FLEETMESH.rstrip("/")
MEDIATION_PROTOCOL = identity.FLEETMESH + "mediation/1.0"
TEXTILE_PROTOCOL = identity.FLEETMESH + "textile/1.0"
def _matches_filter(ev: Mapping[str, Any], flt: Mapping[str, Any]) -> bool:
if "ids" in flt and ev.get("id") not in flt["ids"]:
return False
if "kinds" in flt and ev.get("kind") not in flt["kinds"]:
return False
if "authors" in flt and ev.get("pubkey") not in flt["authors"]:
return False
created = int(ev.get("created_at") or 0)
if "since" in flt and created < int(flt["since"]):
return False
if "until" in flt and created > int(flt["until"]):
return False
tags = ev.get("tags") or []
for k, vals in flt.items():
if k.startswith("#") and len(k) > 1 and isinstance(vals, list):
tname = k[1:]
tvals = {t[1] for t in tags if isinstance(t, list) and len(t) >= 2 and t[0] == tname}
if not (tvals & set(vals)):
return False
return True
def _matches_any(ev: Mapping[str, Any], filters: Sequence[Mapping[str, Any]]) -> bool:
return any(_matches_filter(ev, f) for f in filters if isinstance(f, Mapping)) if filters else True
def _trim(store: MutableMapping[str, Any], cap: int, counts: Callable[[Any], bool]) -> None:
"""Drop the oldest entries `counts` covers until at most `cap` of them are left."""
n = sum(1 for v in store.values() if counts(v))
if n <= cap:
return
for k in list(store):
if n <= cap:
break
if counts(store[k]):
del store[k]
n -= 1
[docs]class HostedLeafRelay:
"""Embedded Leaf Relay, DIDComm v2 Mediator, and Textile Negentropy Engine."""
# What it keeps of what anyone sends, the oldest going first (audit
# 2026-11-18, textile #7: every event, negentropy session and descriptor
# was kept for good, so memory grew with whatever anyone sent). The
# relay's own events are not counted and never dropped.
MAX_EVENTS: int = 10_000
MAX_NEG_SESSIONS: int = 256
MAX_DESCRIPTORS: int = 10_000
[docs] def __init__(self, engine: Any, default_domain: str = "fleetmesh.org") -> None:
self.engine = engine
self.default_domain = default_domain
self._lock = threading.RLock()
# Every key comes from a secret: FLEETMESH_LEAF_RELAY_SECRET, else the engine's own node key.
# There is no default. A seed anyone can write down (this used to fall back to
# `fleetmesh-hosted-leaf-mediator:<domain>`) gives anyone the agreement key, so anyone
# could open every envelope sealed to the mediator and sign as it.
eng_sk = str(getattr(engine, "_node_sk", "") or getattr(engine, "node_sk", "") or "").strip().lower()
secret = (os.environ.get("FLEETMESH_LEAF_RELAY_SECRET") or "").strip()
if secret:
seed = secret
elif lc.is_hex(eng_sk, 64):
seed = det_hex(f"hosted-leaf-relay-seed:{eng_sk}")
else:
raise ValueError(
"HostedLeafRelay needs a secret: set FLEETMESH_LEAF_RELAY_SECRET, or give the engine a node key "
"(_node_sk). Its agreement and signing keys derive from it."
)
self.node_sk: str = eng_sk if lc.is_hex(eng_sk, 64) else det_hex(f"node-sk:{seed}")
self.node_pk: str = lc.pubkey(self.node_sk)
self.did: str = f"did:nostr:{self.node_pk}"
self.agreement_sk: bytes = bytes.fromhex(det_hex(f"agree-sk:{seed}"))
self.agreement_pk: bytes = (
x25519.X25519PrivateKey.from_private_bytes(self.agreement_sk).public_key().public_bytes_raw()
)
self.agreement_pk_hex: str = self.agreement_pk.hex()
self.transport_pk_hex: str = det_hex(f"transport-pk:{seed}")
self.operator_pk: str = det_hex(f"operator-pk:{seed}")
self._descriptors: dict[str, MutableMapping[str, Any]] = {}
self._events: dict[str, MutableMapping[str, Any]] = {}
self._admitted_leaves: dict[str, int] = {}
self._keylists: dict[str, set[str]] = {}
self._inbox: list[MutableMapping[str, Any]] = []
self._ws_subs: dict[int, tuple[Callable[[list[Any]], None], dict[str, list[MutableMapping[str, Any]]]]] = {}
self._neg_sessions: dict[str, NegentropyServer] = {}
self._cached_desc: Optional[MutableMapping[str, Any]] = None
self._cached_desc_ep: str = ""
[docs] def default_endpoint(self) -> str:
env_ep = (
os.environ.get("FLEETMESH_LEAF_MEDIATOR_URL")
or os.environ.get("FLEETMESH_MEDIATOR_ENDPOINT")
or ""
).strip()
return env_ep or f"wss://leaf.{self.default_domain}/relay"
def _remember(self, ev: MutableMapping[str, Any]) -> None:
"""Keep `ev` (at the back if it was here), dropping the oldest of other
keys' events past MAX_EVENTS. Call with the lock held."""
eid = str(ev.get("id") or "")
self._events.pop(eid, None)
self._events[eid] = ev
_trim(self._events, self.MAX_EVENTS, lambda e: e.get("pubkey") != self.node_pk)
def _remember_descriptor(self, ev: MutableMapping[str, Any]) -> None:
pk = str(ev["pubkey"]).lower()
self._descriptors.pop(pk, None)
self._descriptors[pk] = ev
_trim(self._descriptors, self.MAX_DESCRIPTORS, lambda d: str(d.get("pubkey") or "").lower() != self.node_pk)
[docs] def release_owner(self, leaf_did: str, owner_did: str) -> None:
"""A leaf no longer picks up for an owner it has moved away from."""
clean_ldid, clean_owner = str(leaf_did or "").strip().lower(), str(owner_did or "").strip().lower()
if clean_owner and clean_owner != clean_ldid:
with self._lock:
(self._keylists.get(clean_ldid) or set()).discard(clean_owner)
[docs] def register_leaf_binding(self, leaf_did: str, agreement_pk_hex: str, owner_did: str = "") -> None:
clean_ldid = str(leaf_did or "").strip().lower()
clean_agree = str(agreement_pk_hex or "").strip().lower()
if not clean_ldid.startswith("did:nostr:") or not lc.is_hex(clean_ldid[10:], 64) or not lc.is_hex(clean_agree, 64):
return
lpk = clean_ldid[10:]
with self._lock:
self._admitted_leaves.setdefault(clean_ldid, int(time.time()))
keys = self._keylists.setdefault(clean_ldid, {clean_ldid})
if owner_did and owner_did.startswith("did:nostr:"):
keys.add(owner_did.lower())
pks = [lpk]
if owner_did.startswith("did:nostr:") and lc.is_hex(owner_did[10:], 64):
pks.append(owner_did[10:].lower())
for pk in pks:
if pk not in self._descriptors:
now = int(time.time())
tags = [
["class", "leaf"],
["protocol", PROTOCOL_VERSION, PROTOCOL_DIGEST],
["software", SOFTWARE_URL, "0.0.1"],
["key", "agreement", "fec01" + clean_agree],
["mediator", self.did],
["c", "https://fleetmesh.org/budget/1.0"],
["c", "https://fleetmesh.org/peering/1.0"],
["c", TEXTILE_PROTOCOL],
["expiration", str(now + 86400)],
]
self._descriptors[pk] = {
"id": det_hex(f"leaf-desc:{pk}:{clean_agree}"),
"pubkey": pk,
"created_at": now,
"kind": lc.KIND_DESCRIPTOR,
"tags": tags,
"content": "",
"sig": "",
}
def _resolve_agreement(self, pk_hex: str) -> Optional[bytes]:
pk = pk_hex.lower().replace("did:nostr:", "").split("#")[0]
if pk == self.node_pk:
return self.agreement_pk
with self._lock:
desc = self._descriptors.get(pk)
if desc:
ag = lc.agreement_of_descriptor(desc)
if ag:
return ag
ldid = f"did:nostr:{pk}"
bindings = getattr(self.engine, "_leaf_bindings", None) or getattr(self.engine, "user_leaf_bindings", None) or {}
if isinstance(bindings, Mapping):
rec = bindings.get(ldid)
if isinstance(rec, Mapping) and lc.is_hex(rec.get("agreement_pk", ""), 64):
return bytes.fromhex(str(rec["agreement_pk"]).lower())
for v in bindings.values():
if isinstance(v, Mapping) and (v.get("owner_did") == ldid or v.get("leaf_did") == ldid):
if lc.is_hex(v.get("agreement_pk", ""), 64):
return bytes.fromhex(str(v["agreement_pk"]).lower())
return None
[docs] def collect_textile_inventory(self, scope: str = "all") -> MutableMapping[str, Any]:
self.build_mediator_descriptor()
with self._lock:
descs = dict(self._descriptors)
return build_engine_textile_inventory(self.engine, self.node_pk, descs, verify_event_fn=lc.verify_event)
def _negentropy_items_for_filter(self, flt: Mapping[str, Any], scope: str = "all") -> list[tuple[int, str]]:
inv = self.collect_textile_inventory(scope)
kinds = set(flt.get("kinds") or [])
if scope == "quilts" or KIND_QUILT in kinds:
return [(int(x["timestamp"]), str(x["id"])) for x in inv["quilts"]]
if scope == "fabrics" or KIND_FABRIC in kinds:
return [(int(x["timestamp"]), str(x["id"])) for x in inv["fabrics"]]
if scope in ("strands", "catalog") or KIND_STRAND in kinds:
return [(int(x["timestamp"]), str(x["id"])) for x in inv["strands"]]
if scope == "fibers" or KIND_FIBER in kinds:
return [(int(x["timestamp"]), str(x["id"])) for x in inv["fibers"]]
if scope in ("spools", "chunks", "suits", "fits") and scope in inv:
return [(int(x["timestamp"]), str(x["id"])) for x in inv[scope]]
if scope == "descriptors" or lc.KIND_DESCRIPTOR in kinds:
return [(int(x["timestamp"]), str(x["id"])) for x in inv["descriptors"]]
all_items: list[tuple[int, str]] = []
for k in ("quilts", "fabrics", "strands", "fibers", "spools", "chunks", "suits", "fits", "descriptors"):
all_items.extend((int(x["timestamp"]), str(x["id"])) for x in inv.get(k, []))
return all_items
def _owner_of(self, leaf_did: str) -> str:
bindings = getattr(self.engine, "_leaf_bindings", None) or getattr(self.engine, "user_leaf_bindings", None) or {}
rec = bindings.get(leaf_did) if isinstance(bindings, Mapping) else None
if isinstance(rec, Mapping) and str(rec.get("owner_did", "")).startswith("did:nostr:"):
return str(rec["owner_did"]).lower()
return ""
def _keys_of(self, leaf_did: str) -> set[str]:
"""The recipient keys a leaf picks up for: its own DID, its owner's, and its keylist. Caller holds the lock."""
keys = set(self._keylists.get(leaf_did) or ())
keys.add(leaf_did)
owner = self._owner_of(leaf_did)
if owner:
keys.add(owner)
return keys
def _may_add_key(self, leaf_did: str, key: str) -> bool:
"""A leaf may add its own DID, its owner's, or a key no other leaf holds; never another did:nostr.
Caller holds the lock."""
if key in (leaf_did, self._owner_of(leaf_did)):
return True
if key.startswith("did:nostr:"):
return False
return not any(key in kl for other, kl in self._keylists.items() if other != leaf_did)
def _handle_mediation_event(self, wrap_ev: Mapping[str, Any]) -> list[MutableMapping[str, Any]]:
now = int(time.time())
# open_didcomm refuses a `from` or authcrypt skid naming anyone but the seal signer,
# so every request below acts for the seal signer and nobody else.
msg, sender_pk, _ = lc.open_didcomm(wrap_ev, self.node_sk, self.agreement_sk, self._resolve_agreement)
mtype = str(msg.get("type") or "")
leaf_did = f"did:nostr:{sender_pk}"
thid = str(msg.get("id") or "")
sender_agree = self._resolve_agreement(sender_pk)
replies: list[MutableMapping[str, Any]] = []
if mtype.endswith("/mediate-request"):
with self._lock:
self._admitted_leaves[leaf_did] = now
kl = self._keylists.setdefault(leaf_did, {leaf_did})
bindings = getattr(self.engine, "_leaf_bindings", None) or getattr(self.engine, "user_leaf_bindings", None) or {}
rec = bindings.get(leaf_did) if isinstance(bindings, Mapping) else None
if isinstance(rec, Mapping) and str(rec.get("owner_did", "")).startswith("did:nostr:"):
kl.add(str(rec["owner_did"]).lower())
if sender_agree:
grant = {
"id": "med-grant-" + os.urandom(6).hex(),
"type": "https://didcomm.org/coordinate-mediation/2.0/mediate-grant",
"from": self.did,
"to": [leaf_did],
"thid": thid,
"body": {"routing_keys": [self.did], "endpoint": self.default_endpoint()},
}
replies.append(lc.seal_didcomm(grant, self.node_sk, self.agreement_sk, sender_pk, sender_agree, now))
elif mtype.endswith("/keylist-update"):
updates = (msg.get("body") or {}).get("updates") or []
updated_out: list[dict[str, str]] = []
with self._lock:
self._admitted_leaves.setdefault(leaf_did, now)
kl = self._keylists.setdefault(leaf_did, {leaf_did})
for u in updates:
if not isinstance(u, Mapping):
continue
rk = str(u.get("recipient_key") or "").strip().lower()
act = str(u.get("action") or "")
if not rk:
continue
if act == "add":
if not self._may_add_key(leaf_did, rk):
updated_out.append({"recipient_key": rk, "action": "add", "result": "client_error"})
continue
kl.add(rk)
updated_out.append({"recipient_key": rk, "action": "add", "result": "success"})
elif act == "remove":
res = "success" if rk in kl else "no_change"
kl.discard(rk)
updated_out.append({"recipient_key": rk, "action": "remove", "result": res})
if sender_agree:
resp = {
"id": "kl-resp-" + os.urandom(6).hex(),
"type": "https://didcomm.org/coordinate-mediation/2.0/keylist-update-response",
"from": self.did,
"to": [leaf_did],
"thid": thid,
"body": {"updated": updated_out},
}
replies.append(lc.seal_didcomm(resp, self.node_sk, self.agreement_sk, sender_pk, sender_agree, now))
elif mtype.endswith("/forward"):
next_did = str((msg.get("body") or {}).get("next") or "").strip().lower()
attachments = list(msg.get("attachments") or [])
if next_did and attachments:
row_id = str(msg.get("id") or ("fwd-" + os.urandom(6).hex()))
with self._lock:
if not any(r["id"] == row_id and r["recipient_key"] == next_did for r in self._inbox):
self._inbox.append(
{
"id": row_id,
"recipient_key": next_did,
"sender": leaf_did,
"attachments": attachments,
"enqueued_at": now,
"delivered": False,
}
)
if len(self._inbox) > 1000:
self._inbox = self._inbox[-1000:]
elif mtype.endswith("/delivery-request"):
ver = "3.0" if "/3.0/" in mtype else "2.0"
body = msg.get("body") or {}
limit = max(1, min(100, int(body.get("limit") or 10)))
req_key = str(body.get("recipient_key") or "").strip().lower()
with self._lock:
keys = self._keys_of(leaf_did)
target_keys = {req_key} if (req_key and req_key in keys) else keys
rows = [
{
"id": r["id"],
"recipient_key": r["recipient_key"],
"sender": r["sender"],
"attachments": r["attachments"],
"enqueued_at": r["enqueued_at"],
}
for r in self._inbox
if not r.get("delivered") and r.get("recipient_key") in target_keys
][:limit]
if sender_agree:
deliv = {
"id": "pck-del-" + os.urandom(6).hex(),
"type": f"https://didcomm.org/messagepickup/{ver}/delivery",
"from": self.did,
"to": [leaf_did],
"thid": thid,
"body": {"messages": rows, **({"recipient_key": req_key} if req_key else {})},
}
replies.append(lc.seal_didcomm(deliv, self.node_sk, self.agreement_sk, sender_pk, sender_agree, now))
elif mtype.endswith("/messages-received"):
mids = set((msg.get("body") or {}).get("message_id_list") or [])
with self._lock:
keys = self._keys_of(leaf_did)
self._inbox = [r for r in self._inbox if not (r.get("id") in mids and r.get("recipient_key") in keys)]
for r in replies:
with self._lock:
self._remember(r)
self._broadcast_event(r)
return replies
def _broadcast_event(self, ev: Mapping[str, Any]) -> None:
with self._lock:
subs = list(self._ws_subs.values())
for send_fn, sub_map in subs:
for sid, filters in list(sub_map.items()):
if _matches_any(ev, filters):
try:
send_fn(["EVENT", sid, ev])
except Exception as exc:
_ = exc
[docs] def process_frame(
self, frame: list[Any], sub_map: Optional[dict[str, list[MutableMapping[str, Any]]]] = None, is_http: bool = True
) -> list[list[Any]]:
if not isinstance(frame, list) or not frame or not isinstance(frame[0], str):
return [["NOTICE", "invalid frame"]]
verb = frame[0].upper()
out: list[list[Any]] = []
self.build_mediator_descriptor()
if verb == "EVENT" and len(frame) >= 2 and isinstance(frame[1], Mapping):
ev = dict(frame[1])
eid = str(ev.get("id") or "")
if not lc.verify_event(ev):
return [["OK", eid, False, "invalid: signature verification failed"]]
kind = int(ev.get("kind") or 0)
with self._lock:
self._remember(ev)
if kind == lc.KIND_DESCRIPTOR:
self._remember_descriptor(ev)
ag = lc.agreement_of_descriptor(ev)
if ag:
self.register_leaf_binding(f"did:nostr:{str(ev['pubkey']).lower()}", ag.hex())
out.append(["OK", eid, True, ""])
self._broadcast_event(ev)
is_to_me = any(isinstance(t, list) and t[:2] == ["p", self.node_pk] for t in (ev.get("tags") or []))
if kind in (lc.WRAP_LIVE, lc.WRAP_STORED) and is_to_me:
try:
replies = self._handle_mediation_event(ev)
if is_http:
for rep in replies:
matched = [sid for sid, flts in (sub_map or {}).items() if _matches_any(rep, flts)]
for sid in matched or ["*"]:
out.append(["EVENT", sid, rep])
except Exception as exc:
out.append(["NOTICE", f"mediation error: {exc}"])
return out
if verb == "REQ" and len(frame) >= 2 and isinstance(frame[1], str):
sid = frame[1]
filters = [f for f in frame[2:] if isinstance(f, Mapping)]
if sub_map is not None:
sub_map[sid] = [dict(f) for f in filters]
with self._lock:
candidates = list(self._events.values())
for d in self._descriptors.values():
if d.get("sig") and d["id"] not in self._events:
candidates.append(d)
matched_evs = sorted(
[ev for ev in candidates if _matches_any(ev, filters)], key=lambda e: int(e.get("created_at") or 0)
)
for matched_ev in matched_evs[:100]:
out.append(["EVENT", sid, matched_ev])
out.append(["EOSE", sid])
return out
if verb == "CLOSE" and len(frame) >= 2 and isinstance(frame[1], str):
if sub_map is not None:
sub_map.pop(frame[1], None)
return []
if verb == "AUTH" and len(frame) >= 2 and isinstance(frame[1], Mapping):
eid = str(frame[1].get("id") or "")
return [["OK", eid, lc.verify_event(frame[1]), ""]]
if verb == "NEG-OPEN" and len(frame) >= 4:
sid = str(frame[1])
flt = frame[2] if isinstance(frame[2], Mapping) else {}
msg_hex = str(frame[3] or "")
scope = str(frame[4] if len(frame) >= 5 else flt.get("scope") or "all")
try:
srv = NegentropyServer(self._negentropy_items_for_filter(flt, scope))
with self._lock:
self._neg_sessions.pop(sid, None)
self._neg_sessions[sid] = srv
_trim(self._neg_sessions, self.MAX_NEG_SESSIONS, lambda _s: True)
reply = srv.reconcile(bytes.fromhex(msg_hex))
out.append(["NEG-MSG", sid, reply.hex()] if reply is not None else ["NEG-CLOSE", sid])
except Exception as exc:
out.append(["NEG-ERR", sid, f"ERROR: {exc}"])
return out
if verb == "NEG-MSG" and len(frame) >= 3:
sid, msg_hex = str(frame[1]), str(frame[2] or "")
with self._lock:
sess = self._neg_sessions.get(sid)
if not sess:
return [["NEG-ERR", sid, "CLOSED: unknown session"]]
try:
reply = sess.reconcile(bytes.fromhex(msg_hex))
out.append(["NEG-MSG", sid, reply.hex()] if reply is not None else ["NEG-CLOSE", sid])
except Exception as exc:
out.append(["NEG-ERR", sid, f"ERROR: {exc}"])
return out
if verb == "NEG-CLOSE" and len(frame) >= 2:
with self._lock:
self._neg_sessions.pop(str(frame[1]), None)
return []
return [["NOTICE", f"unsupported verb {verb}"]]
[docs] def handle_http_frames(self, body: Any) -> MutableMapping[str, Any]:
sub_map: dict[str, list[MutableMapping[str, Any]]] = {}
frames_in: list[Any] = []
if isinstance(body, list):
frames_in = [body] if (body and isinstance(body[0], str)) else body
elif isinstance(body, Mapping):
if isinstance(body.get("frames"), list):
frames_in = body["frames"]
elif isinstance(body.get("frame"), list):
frames_in = [body["frame"]]
out: list[list[Any]] = []
for f in frames_in:
if isinstance(f, list):
out.extend(self.process_frame(f, sub_map))
return {"ok": True, "frames": out, "mediator": self.get_mediator_config()}
[docs] def get_nip11_info(self, endpoint_override: Optional[str] = None) -> MutableMapping[str, Any]:
cfg = self.get_mediator_config(endpoint_override)
return {
"name": "FleetMesh Hosted Leaf Relay & Textile Mediator",
"description": "Fleetmesh Leaf Relay & DIDComm v2 Mediator supporting Fibers, Strands, Fabrics, and Quilts.",
"pubkey": self.node_pk,
"contact": self.did,
"supported_nips": [1, 11, 40, 42, 59, 77],
"software": SOFTWARE_URL,
"version": "0.0.1",
"mediator": cfg,
}
[docs] def handle_websocket_upgrade(self, handler: Any) -> bool:
return serve_relay_websocket(handler, self._ws_subs, self._lock, lambda f, sm: self.process_frame(f, sm, False))