"""Standalone Circle Rooms, Watch-Party Frontier & Privacy Rung Store (`node.protocols.circles.store`).
Circles are equal-peer collectives: no owner or admin, so their members are who may change them.
Every write is authorized by the request principal, never by an identity the request names:
- creating a circle makes the caller its first member; joining a public circle adds the caller,
a private one needs its invite code or an invite addressed to the caller; leaving removes them;
- posts, curation, the watch party, invites, profile, DID, UCAN, credential and treasury changes
are members-only, and act on circles that exist (never invent one).
Reads: private circles are listed to their members only; a public circle's internals (invite
code, UCAN grants, credentials, treasury, invites) are its members' alone. Membership flags are
computed for each viewer, not stored.
"""
from __future__ import annotations
import hmac
import re
import secrets
import time
from typing import Any, List, Mapping, MutableMapping, Optional, Tuple
from fleetmesh_core.textile.circle_keys import apply_circle_keys, start_new_epoch
from fleetmesh_core.textile.principal import MeshAccessError, Principal, principal_keys, require_principal
from fleetmesh_core.textile.privacy_ladder import PRIVACY_RUNG_RANK, normalize_did
from .persistence import persist_circle
_MEMBERS_ONLY_FIELDS = (
"invite_code_hint",
"ucan_grants",
"member_credentials",
"treasury",
"invites",
"invited_member_ids",
"did_web_binding",
"circle_keys",
)
_STORED_VIEWER_FLAGS = ("is_member", "is_owned_by_active", "is_equal_peer_member", "is_invited")
# Joining by code alone searches every circle, so a code is the whole secret.
MIN_INVITE_CODE_LEN = 12
def _slug(name: str) -> str:
"""A name as a slug: a-z, 0-9 and hyphens, at most 64; a generated one when nothing is left."""
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:64].strip("-")
return slug or "circle-%s" % secrets.token_hex(4)
def _code_matches(given: str, held: Any) -> bool:
return bool(given) and hmac.compare_digest(given.lower().encode(), str(held or "").lower().encode())
[docs]def is_circle_member(c_obj: Mapping[str, Any], principal: Principal) -> bool:
keys = principal_keys(principal)
return bool(keys) and any(
{str(m.get("identity_id") or "").lower(), str(m.get("did") or "").lower()} & keys
for m in c_obj.get("members") or []
)
[docs]def visible_circle(c_obj: Optional[Mapping[str, Any]], principal: Principal) -> Optional[MutableMapping[str, Any]]:
"""The circle as this viewer may see it, with their membership flags; `None` for a private circle they are not in."""
if not c_obj:
return None
member = is_circle_member(c_obj, principal)
if not member and str(c_obj.get("visibility") or "public") == "private":
return None
out = {k: v for k, v in c_obj.items() if member or k not in _MEMBERS_ONLY_FIELDS}
out.update(
{
"is_member": member,
"is_equal_peer_member": member,
"is_owned_by_active": member,
"is_invited": member
or bool(principal_keys(principal) & {str(i).lower() for i in c_obj.get("invited_member_ids") or []}),
}
)
return out
[docs]def visible_circles(eng: Any, principal: Principal) -> List[MutableMapping[str, Any]]:
return [v for v in (visible_circle(c, principal) for c in eng._circles.values()) if v]
[docs]def visible_invites(eng: Any, principal: Principal) -> List[MutableMapping[str, Any]]:
"""Invites the viewer sent or received, or that belong to a circle they are in."""
keys = principal_keys(principal)
return [
dict(i)
for i in eng._circle_invites
if keys & {str(i.get("sender_id") or "").lower(), str(i.get("recipient_id") or "").lower()}
or is_circle_member(eng._circles.get(str(i.get("circle_id") or "")) or {}, principal)
]
def _resolve_circle(eng: Any, cid: str, who: Principal) -> Optional[MutableMapping[str, Any]]:
source = getattr(eng, "circle_source", None)
viewer = str((who or {}).get("identity_id") or "") if isinstance(who, Mapping) else ""
row = (
next((c for c in source(viewer_id=viewer) if c.get("circle_id") == cid), None)
if callable(source) and cid
else None
)
if row:
c_obj = eng._circles.setdefault(
cid,
{k: row.get(k) for k in ("circle_id", "name", "slug", "visibility", "group_did", "did_web", "created_at")},
)
c_obj["members"] = [dict(m) for m in row.get("members") or []]
return eng._circles.get(cid)
[docs]def circle_access(eng: Any, cid: str, principal: Principal) -> Optional[Tuple[MutableMapping[str, Any], bool]]:
"""The circle and whether `principal` is one of its members, or `None` when there is no such circle."""
with eng._lock:
c_obj = _resolve_circle(eng, cid, principal)
return (dict(c_obj), is_circle_member(c_obj, principal)) if c_obj else None
def _member_circle(eng: Any, cid: str, who: Mapping[str, Any]) -> MutableMapping[str, Any]:
c_obj = _resolve_circle(eng, cid, who)
if c_obj is None:
raise MeshAccessError(404, "circle_not_found")
if not is_circle_member(c_obj, who):
raise MeshAccessError(403, "not_circle_member")
return c_obj
def _member_entry(who: Mapping[str, Any], handle: str, now: int) -> MutableMapping[str, Any]:
return {
"identity_id": str(who.get("identity_id") or ""),
"did": str(who.get("did") or ""),
"handle": str(who.get("handle") or handle or "Member"),
"role": "member",
"equal_peer": True,
"joined_at": now,
}
_EPHEMERAL_ROUTES = ("/api/circles/typing", "/api/circles/watch-party/telemetry")
[docs]def handle_circles_post(
eng: Any,
route: str,
body: Mapping[str, Any],
principal: Principal = None,
) -> Optional[MutableMapping[str, Any]]:
"""Circle writes as the request principal (raises `MeshAccessError` when it may not); the changed circle is persisted."""
res = _circles_post(eng, route, body, principal)
if res is not None and route not in _EPHEMERAL_ROUTES:
cid = str(
body.get("circle_id")
or ((res.get("circle") or {}) if isinstance(res.get("circle"), Mapping) else {}).get("circle_id")
or ""
)
with eng._lock:
persist_circle(eng, cid)
return res
def _circles_post(
eng: Any,
route: str,
body: Mapping[str, Any],
principal: Principal = None,
) -> Optional[MutableMapping[str, Any]]:
from ..dm.spool import record_typing_indicator as _record_typing_indicator
who = require_principal(principal)
me = str(who.get("identity_id") or "")
with eng._lock:
now = int(time.time())
if route == "/api/circles/typing":
_member_circle(eng, str(body.get("circle_id") or body.get("target_id") or "").strip(), who)
return _record_typing_indicator(eng, {**dict(body), "scope": "circle"}, who)
if route in ("/api/circles/watch-party", "/api/circles/watch-party/telemetry"):
cid = str(body.get("circle_id") or "").strip()
c_obj = _member_circle(eng, cid, who)
now_f = round(time.time(), 3)
wp = dict(c_obj.get("watch_party") or {})
uid = me or "viewer"
hnd = str(who.get("handle") or body.get("handle") or uid).strip()
media_id = str(body.get("active_media_id") or wp.get("active_media_id") or "").strip()
if not media_id:
return {"ok": True, "watch_party": {}, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route == "/api/circles/watch-party" and media_id:
apply_circle_media_privacy(eng, c_obj, media_id, body, str(who.get("did") or ""))
eff_media_id = media_id
raw_q_idx = body.get("queue_index")
q_idx = int(
raw_q_idx if raw_q_idx is not None else (wp.get("queue_index") or 0)
)
pb = max(0.0, float(body.get("playback_sec") or 0.0))
raw_tw = body.get("true_watch_sec")
tw = max(0.0, float(raw_tw if raw_tw is not None else pb))
prev_frontier = (
float(wp.get("true_frontier_sec") or wp.get("playback_sec") or 0.0)
if wp.get("active_media_id") == eff_media_id
else 0.0
)
eff_tw = pb if route == "/api/circles/watch-party" else min(pb, max(tw, min(pb, prev_frontier)))
watchers = [
dict(w)
for w in (wp.get("watchers") or [])
if isinstance(w, Mapping)
and str(w.get("identity_id") or "") != uid
and now_f - float(w.get("updated_at_f") or w.get("updated_at") or now_f) <= 45.0
and str(w.get("active_media_id") or eff_media_id) == eff_media_id
]
watchers.insert(
0,
{
"identity_id": uid,
"handle": hnd,
"active_media_id": eff_media_id,
"queue_index": q_idx,
"playback_sec": round(pb, 2),
"true_watch_sec": round(eff_tw, 2),
"effective_true_sec": round(eff_tw, 2),
"is_playing": bool(body.get("is_playing", True)),
"lock_to_frontier": bool(body.get("lock_to_frontier", True)),
"updated_at": now,
"updated_at_f": now_f,
},
)
frontier = round(
pb
if route == "/api/circles/watch-party" and "playback_sec" in body
else max([prev_frontier, *[float(w.get("effective_true_sec") or 0.0) for w in watchers]]),
2,
)
wp.update(
{
"active_media_id": media_id or eff_media_id,
"media_kind": str(body.get("media_kind") or wp.get("media_kind") or "vod"),
"title": str(body.get("title") or wp.get("title") or ""),
"host_handle": str(body.get("host_handle") or wp.get("host_handle") or "host"),
"queue_index": q_idx,
"playback_sec": frontier,
"true_frontier_sec": frontier,
"is_playing": bool(body.get("is_playing", True)),
"watchers": watchers,
"updated_at": now,
"updated_at_f": now_f,
"server_now_f": now_f,
}
)
c_obj["watch_party"] = wp
return {"ok": True, "watch_party": wp, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route == "/api/circles/post":
cid = str(body.get("circle_id") or "").strip()
c_obj = _member_circle(eng, cid, who)
_record_typing_indicator(eng, {**dict(body), "scope": "circle", "target_id": cid, "is_typing": False}, who)
if c_obj is not None:
attached_id = str(body.get("attached_vod_id") or "").strip()
eff_rung = None
if attached_id:
priv = apply_circle_media_privacy(eng, c_obj, attached_id, body, str(who.get("did") or ""))
if not priv.get("allowed"):
return {
"ok": False,
"error": priv.get("error"),
"circle": visible_circle(c_obj, who),
"circles": visible_circles(eng, who),
}
eff_rung = priv.get("effective_rung")
post_rec = {
"post_id": f"post-{now}-{secrets.token_hex(3)}",
"circle_id": cid,
"author_id": me,
"author_handle": str(who.get("handle") or body.get("author_handle") or "Member"),
"kind": str(body.get("kind") or body.get("post_kind") or "discussion"),
"body": str(body.get("body") or ""),
"strand_id": str(body.get("strand_id") or ""),
"timestamp_sec": body.get("timestamp_sec"),
"attached_vod_id": attached_id or None,
"privacy_rung": eff_rung,
"created_at": now,
}
posts = list(c_obj.get("posts") or [])
posts.insert(0, post_rec)
c_obj["posts"] = posts
return {"ok": True, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route in ("/api/circles", "/api/circles/save"):
name = str(body.get("name") or "Mesh Circle").strip()
slug = _slug(name)
cid = str(body.get("circle_id") or slug)
if cid in eng._circles:
return handle_circles_post(eng, "/api/circles/profile/update", {**dict(body), "circle_id": cid}, who)
vis = "private" if str(body.get("visibility") or "") == "private" else "public"
code = str(body.get("invite_code") or "").strip()
if code and len(code) < MIN_INVITE_CODE_LEN:
raise MeshAccessError(400, "invite_code_too_short")
if not code and vis == "private":
code = "MESH-" + secrets.token_urlsafe(12)
group_did = f"did:group:{slug}"
did_web_raw = str(body.get("did_web") or "").strip()
init_media_id = str(body.get("initial_media_id") or "").strip()
init_media_kind = str(body.get("initial_media_kind") or "vod").strip() or "vod"
raw_wp = body.get("watch_party")
wp_obj = (
dict(raw_wp)
if isinstance(raw_wp, Mapping)
else (
{
"active_media_id": init_media_id,
"media_kind": init_media_kind,
"title": f"{name} — Featured Screening",
"playback_sec": 0.0,
"is_playing": str(body.get("kind") or "watch_party") == "watch_party",
"host_handle": str(body.get("owner_handle") or "Community"),
"updated_at": now,
}
if init_media_id
else {}
)
)
raw_curated = body.get("curated_media")
curated_list = (
list(raw_curated)
if isinstance(raw_curated, list)
else (
[
{
"media_id": init_media_id,
"media_kind": init_media_kind,
"note": "Featured Selection",
"added_by": str(body.get("owner_handle") or "Member"),
}
]
if init_media_id
else []
)
)
avatar_url_raw = str(body.get("avatar_url") or "").strip()
c_obj = {
"circle_id": cid,
"name": name,
"slug": slug,
"group_did": group_did,
"did_web": did_web_raw or None,
"kind": str(body.get("kind") or "interest_theme"),
"visibility": vis,
"has_invite_code": bool(code),
"invite_code_hint": code,
"invited_member_ids": [],
"invites": [],
"tagline": str(body.get("tagline") or name),
"description": str(body.get("description") or name),
"theme_color": str(body.get("theme_color") or "#3b82f6"),
"avatar_text": str(body.get("avatar_text") or "").strip()[:3] or name[:2].upper(),
"avatar_url": avatar_url_raw or None,
"owner_id": str(body.get("owner_id") or ""),
"owner_handle": str(body.get("owner_handle") or "Equal Peer Collective (No Owner / No Council)"),
"governance_model": "egalitarian_peer_collective",
"has_no_owner": True,
"has_no_founder": True,
"has_no_council": True,
"member_count": 1,
"members": [_member_entry(who, str(body.get("owner_handle") or ""), now)],
"watch_party": wp_obj,
"curated_media": curated_list,
"strands": list(body.get("strands") or []),
"polls": list(body.get("polls") or []),
"ucan_grants": list(body.get("ucan_grants") or []),
"member_credentials": list(body.get("member_credentials") or []),
"treasury": dict(
body.get("treasury")
or {
"balance_credits": 0,
"balance_msat": 0,
"total_collected_credits": 0,
"total_spent_credits": 0,
"transactions": [],
}
),
"tags": list(body.get("tags") or []),
"posts": [],
"created_at": now,
}
eng._circles[cid] = c_obj
return {"ok": True, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route in (
"/api/circles/did/link-web",
"/api/circles/profile/update",
"/api/circles/ucan/issue",
"/api/circles/ucan/revoke",
"/api/circles/treasury/act",
"/api/circles/credentials/issue",
"/api/circles/credentials/revoke",
):
cid = str(body.get("circle_id") or "").strip()
c_obj = _member_circle(eng, cid, who)
if c_obj is not None:
if route == "/api/circles/did/link-web":
domain = str(body.get("domain") or "").strip().lower()
did_web = f"did:web:{domain}" if domain and not domain.startswith("did:web:") else domain
c_obj["did_web"] = did_web or None
c_obj["did_web_verified"] = bool(did_web)
if isinstance(body.get("did_web_binding"), Mapping):
c_obj["did_web_binding"] = dict(body["did_web_binding"])
elif route == "/api/circles/profile/update":
for field in ("name", "tagline", "description", "avatar_text", "avatar_url", "theme_color", "visibility"):
if body.get(field) is not None:
c_obj[field] = str(body[field])
if isinstance(body.get("tags"), list):
c_obj["tags"] = [str(t) for t in body["tags"]]
elif route == "/api/circles/ucan/issue" and isinstance(body.get("grant"), Mapping):
grants = [
g for g in list(c_obj.get("ucan_grants") or []) if g.get("grant_id") != body["grant"].get("grant_id")
]
grants.insert(0, dict(body["grant"]))
c_obj["ucan_grants"] = grants
elif route == "/api/circles/ucan/revoke":
gid = str(body.get("grant_id") or "").strip()
c_obj["ucan_grants"] = [
{**dict(g), "revoked": True} if g.get("grant_id") == gid else dict(g)
for g in list(c_obj.get("ucan_grants") or [])
]
elif route == "/api/circles/treasury/act" and isinstance(body.get("treasury"), Mapping):
c_obj["treasury"] = dict(body["treasury"])
elif route == "/api/circles/credentials/issue" and isinstance(body.get("credential"), Mapping):
creds = [
c
for c in list(c_obj.get("member_credentials") or [])
if c.get("credential_id") != body["credential"].get("credential_id")
]
creds.insert(0, dict(body["credential"]))
c_obj["member_credentials"] = creds
elif route == "/api/circles/credentials/revoke":
vc_id = str(body.get("credential_id") or "").strip()
c_obj["member_credentials"] = [
{**dict(c), "revoked": True} if c.get("credential_id") == vc_id else dict(c)
for c in list(c_obj.get("member_credentials") or [])
]
return {"ok": True, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route == "/api/circles/invite":
cid = str(body.get("circle_id") or "").strip()
rec_id = str(body.get("recipient_id") or body.get("recipient_handle") or "peer").strip()
c_obj = _member_circle(eng, cid, who)
inv_rec = {
"invite_id": f"inv-{now}-{secrets.token_hex(3)}",
"circle_id": cid,
"circle_slug": str(c_obj.get("slug") or cid),
"circle_name": str(c_obj.get("name") or cid),
"sender_id": me,
"sender_handle": str(who.get("handle") or body.get("sender_handle") or "Member"),
"recipient_id": rec_id,
"recipient_handle": str(body.get("recipient_handle") or rec_id),
"recipient_email": str(body.get("recipient_email") or ""),
"invite_code": str(body.get("invite_code") or c_obj.get("invite_code_hint") or "") or None,
"message": str(body.get("message") or ""),
"status": "pending",
"created_at": now,
"accepted_at": 0,
# Recorded here only: nothing in this store sends a DM.
"dm_sent": False,
"email_sent": bool(body.get("recipient_email")),
}
eng._circle_invites.insert(0, inv_rec)
if c_obj:
inv_ids = list(c_obj.get("invited_member_ids") or [])
if rec_id and rec_id not in inv_ids:
inv_ids.append(rec_id)
c_obj["invited_member_ids"] = inv_ids
c_obj["invites"] = [i for i in eng._circle_invites if i.get("circle_id") == cid]
return {"ok": True, "invite": inv_rec, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route == "/api/circles/keys":
c_obj = _member_circle(eng, str(body.get("circle_id") or "").strip(), who)
return {"ok": True, "circle_keys": apply_circle_keys(c_obj, who, body)}
if route in ("/api/circles/join", "/api/circles/redeem"):
cid = str(body.get("circle_id") or "").strip()
code = str(body.get("invite_code") or "").strip()
target_circle = eng._circles.get(cid)
if not target_circle and code:
target_circle = next(
(c for c in eng._circles.values() if _code_matches(code, c.get("invite_code_hint"))),
None,
)
if not target_circle:
raise MeshAccessError(404, "circle_not_found")
c_obj = target_circle
members = [m for m in c_obj.get("members") or [] if not is_circle_member({"members": [m]}, who)]
if str(body.get("action") or "join") == "leave" and len(members) < len(c_obj.get("members") or []):
start_new_epoch(c_obj)
if str(body.get("action") or "join") != "leave":
invited = principal_keys(who) & {
str(i.get("recipient_id") or "").lower()
for i in eng._circle_invites
if i.get("circle_id") == c_obj.get("circle_id")
}
code_ok = _code_matches(code, c_obj.get("invite_code_hint"))
if str(c_obj.get("visibility") or "public") == "private" and not (code_ok or invited):
raise MeshAccessError(403, "invite_required")
members.append(_member_entry(who, str(body.get("handle") or ""), now))
c_obj["members"], c_obj["member_count"] = members, len(members)
return {"ok": True, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
if route == "/api/circles/curate":
cid = str(body.get("circle_id") or "").strip()
c_obj = _member_circle(eng, cid, who)
if c_obj:
media_id = str(body.get("media_id") or "").strip()
eff_rung = "private_group" if str(c_obj.get("visibility") or "public") == "private" else "public_group"
if str(body.get("action") or "add") != "remove":
priv = apply_circle_media_privacy(eng, c_obj, media_id, body, str(who.get("did") or ""))
if not priv.get("allowed"):
return {
"ok": False,
"error": priv.get("error"),
"circle": visible_circle(c_obj, who),
"circles": visible_circles(eng, who),
}
eff_rung = str(priv.get("effective_rung") or eff_rung)
item = {
"media_id": media_id,
"media_kind": str(body.get("media_kind") or "vod"),
"title": str(body.get("title") or media_id),
"note": str(body.get("note") or ""),
"privacy_rung": eff_rung,
"added_at": now,
}
curated = [m for m in list(c_obj.get("curated_media") or []) if m.get("media_id") != media_id]
if str(body.get("action") or "add") != "remove":
curated.insert(0, item)
c_obj["curated_media"] = curated
return {"ok": True, "circle": visible_circle(c_obj, who), "circles": visible_circles(eng, who)}
return None