Source code for fleetmesh_auth.host_directory

"""HostDirectory: the UserDirectory over a co-hosted host application engine.

Every read of the host application's internals (`_user_conn`, `_identities`, `_sessions`,
its admin and session tables) lives here. Two `users` schemas exist: the full
host engine keyed by `identity_id`, and a minimal one keyed by `user_id`.
"""
from __future__ import annotations

import hashlib
import secrets
import threading
import time
from pathlib import Path
from typing import Any, FrozenSet, List, Optional

from fleetmesh_auth.directory import UserRecord
from fleetmesh_auth.principal import AuthPrincipal, expand_roles
from fleetmesh_auth.schema_probe import table_columns

_BIO = "Authenticated via FleetMesh Sovereign Key"


[docs]class HostDirectory:
[docs] def __init__(self, host: Any) -> None: self.host = host # Statements on the host's connection from this adapter run one at a time. self._lock = threading.RLock()
# ---- the connection -------------------------------------------------------- def _conn(self) -> Any: return getattr(self.host, "_user_conn", None) def _id_col(self, conn: Any) -> str: return "identity_id" if "identity_id" in table_columns(conn, "users") else "user_id" # ---- users ------------------------------------------------------------------
[docs] def own_pubkeys(self) -> FrozenSet[str]: return frozenset( str(getattr(self.host, attr, "") or "").lower() for attr in ("operator_pk", "node_pk") ) - {""}
[docs] def find_user(self, pubkey_hex: str) -> Optional[UserRecord]: conn = self._conn() if conn is None: return None try: with self._lock: cols = table_columns(conn, "users") id_col = self._id_col(conn) has_display_col = "display_name" in cols sel_cols = (f"{id_col}, handle, display_name, role" if has_display_col else f"{id_col}, username, handle, role") row = conn.execute( f"SELECT {sel_cols} FROM users WHERE LOWER(pubkey) = ? LIMIT 1", (pubkey_hex.lower(),), ).fetchone() except Exception: return None if not row: return None user_id = str(row[id_col] or "") if has_display_col: handle = str(row["handle"] or "") display_name = str(row["display_name"] or handle) else: handle = str(row["username"] or row["handle"] or user_id).lstrip("@") display_name = str(row["handle"] or handle) role = str(row["role"] or "creator").lower() return {"user_id": user_id, "handle": handle, "display_name": display_name, "roles": [role, "broadcaster", "creator"]}
[docs] def create_user(self, pubkey_hex: str, handle_hint: Optional[str]) -> Optional[UserRecord]: conn = self._conn() if conn is None: return None pk = pubkey_hex.lower() clean_hint = str(handle_hint or "").strip().lower().lstrip("@") handle = clean_hint if clean_hint else f"key_{pk[:8]}" display_name = str(handle_hint or handle).strip() or handle now = int(time.time()) try: with self._lock: if self._id_col(conn) == "identity_id": claimed = self._claim_identity(conn, handle, display_name, "creator", pk, f"did:nostr:{pk}", now, _BIO) if claimed is None: return None user_id = claimed else: user_id = f"usr_{secrets.token_hex(6)}" conn.execute( "INSERT INTO users (user_id, handle, display_name, password_hash, pubkey, privkey_enc, bio, avatar_color, role, created_at) " "VALUES (?, ?, ?, '', ?, '', ?, '#38bdf8', 'creator', ?)", (user_id, handle, display_name, pk, _BIO, now), ) conn.commit() except Exception: return None return {"user_id": user_id, "handle": handle, "display_name": display_name, "roles": ["creator", "broadcaster"]}
def _claim_identity(self, conn: Any, base_id: str, handle: str, role: str, pk: str, did: str, now: int, bio: str) -> Optional[str]: """An identity id for `pk`: `base_id`, else `base_id_<pk prefix>`. An id already taken by another pubkey is never handed out: that would sign this key in as someone else. None when both are taken.""" for candidate in (base_id, f"{base_id}_{pk[:6]}"): row = conn.execute("SELECT pubkey FROM users WHERE identity_id = ?", (candidate,)).fetchone() if row is not None: if str(row[0] or "").lower() == pk: return candidate continue ident_map = getattr(self.host, "_identities", None) if isinstance(ident_map, dict) and candidate in ident_map and \ str(ident_map[candidate].get("pubkey") or "").lower() != pk: continue self._insert_identity(conn, candidate, candidate, handle, role, pk, did, now, bio) return candidate return None def _insert_identity(self, conn: Any, user_id: str, username: str, handle: str, role: str, pk: str, did: str, now: int, bio: str) -> None: """A full-schema identity row and the host's in-memory copy of it. No `sk`: the user holds their own key, and the host reads an empty sk as an externally keyed identity.""" cashu_p2pk = f"02{pk}" conn.execute( "INSERT INTO users (identity_id, username, handle, bio, role, is_guest, password_hash, sk, pubkey, did, cashu_p2pk, created_at) " "VALUES (?, ?, ?, ?, ?, 0, '', '', ?, ?, ?, ?)", (user_id, username, handle, bio, role, pk, did, cashu_p2pk, now), ) ident_map = getattr(self.host, "_identities", None) if isinstance(ident_map, dict): ident_map[user_id] = { "identity_id": user_id, "username": username, "handle": handle, "bio": bio, "role": role, "is_guest": False, "password_hash": "", "sk": "", "pubkey": pk, "did": did, "cashu_p2pk": cashu_p2pk, "created_at": now, } # ---- sessions ----------------------------------------------------------------- def _user_for(self, conn: Any, principal: AuthPrincipal, now: int) -> str: """The host user this principal is: from its metadata, a row, or a new one.""" user_id = str(principal.metadata.get("identity_id") or principal.metadata.get("user_id") or "") if user_id: return user_id id_col = self._id_col(conn) row = conn.execute( f"SELECT {id_col} FROM users WHERE LOWER(pubkey) = ? LIMIT 1", (principal.pubkey_hex.lower(),) ).fetchone() # A name is only this host's to vouch for when this host checked the # password: a local login on the host. A handle from another instance or # provider could name anyone here. local_login = principal.provider_id == "host" and not principal.metadata.get("remote_instance") if row is None and local_login: row = conn.execute( f"SELECT {id_col} FROM users WHERE LOWER(handle) = ? LIMIT 1", (principal.handle.lower(),) ).fetchone() if row: return str(row[0]) role = "admin" if principal.has_role("admin") else "creator" if id_col == "identity_id": clean_handle = principal.handle.lower().lstrip("@") or f"key_{principal.pubkey_hex[:8]}" claimed = self._claim_identity(conn, clean_handle, principal.display_name or f"@{clean_handle}", role, principal.pubkey_hex.lower(), principal.did, now, "Authenticated via FleetMesh Unified Auth") if claimed is None: raise ValueError("no free host identity for %s" % clean_handle) return claimed user_id = f"usr_{secrets.token_hex(6)}" conn.execute( "INSERT OR IGNORE INTO users (user_id, handle, display_name, password_hash, pubkey, privkey_enc, bio, avatar_color, role, created_at) " "VALUES (?, ?, ?, '', ?, '', 'Authenticated via FleetMesh Auth', '#38bdf8', ?, ?)", (user_id, principal.handle.lower(), principal.display_name or principal.handle, principal.pubkey_hex.lower(), role, now), ) return user_id def _link_admin_session(self, conn: Any, admin_token: str, principal: AuthPrincipal, issued_at: int, expires_at: int, operator_pubkeys: FrozenSet[str]) -> None: """Moderators, admins and operators also get a row in the host's admin_sessions, keyed by `admin_token` (the session's separate admin credential).""" if hasattr(self.host, "_ensure_admin_tables"): try: self.host._ensure_admin_tables() except Exception: pass admin_id = str(principal.metadata.get("admin_id") or "") admin_uname = principal.handle.lower() if not admin_id: arow = conn.execute( "SELECT admin_id, username FROM admin_users WHERE LOWER(username) = ? LIMIT 1", (admin_uname,), ).fetchone() if arow: admin_id, admin_uname = str(arow["admin_id"]), str(arow["username"]) else: pk_low = (principal.pubkey or principal.pubkey_hex or "").lower() if principal.auth_method == "operator_token" or (pk_low and pk_low in operator_pubkeys): any_admin = conn.execute( "SELECT admin_id, username FROM admin_users ORDER BY created_at ASC LIMIT 1" ).fetchone() if any_admin: admin_id, admin_uname = str(any_admin["admin_id"]), str(any_admin["username"]) if not admin_id: return if {"username", "expires_at"} <= table_columns(conn, "admin_sessions"): conn.execute( "INSERT OR REPLACE INTO admin_sessions (token, admin_id, username, created_at, expires_at) VALUES (?, ?, ?, ?, ?)", (admin_token, admin_id, admin_uname, issued_at, expires_at), ) else: conn.execute( "INSERT OR REPLACE INTO admin_sessions (token, admin_id, created_at) VALUES (?, ?, ?)", (admin_token, admin_id, issued_at), ) principal.admin_token = admin_token
[docs] def has_session(self, token: str) -> bool: return token in getattr(self.host, "_sessions", {})
[docs] def resolve_session(self, token: str, now: int, ttl_sec: int) -> Optional[AuthPrincipal]: host = self.host common = dict(scopes=["*"], session_token=token, issued_at=now, expires_at=now + ttl_sec) admin = None if hasattr(host, "resolve_admin_session"): admin = host.resolve_admin_session(token) elif hasattr(host, "verify_admin_session"): admin = host.verify_admin_session(token) if admin: uname = str(admin.get("username") or "admin") pubkey = hashlib.sha256(f"fleetmesh-admin:{uname}".encode("utf-8")).hexdigest() return AuthPrincipal( principal_id=f"host:admin:{admin.get('admin_id') or uname}", did=f"did:nostr:{pubkey}", pubkey=pubkey, handle=uname, display_name=str(admin.get("display_name") or uname), provider_id="host", auth_method="service_login", roles=expand_roles([str(admin.get("role") or "admin"), "node_operator", "admin", "moderator", "broadcaster"]), admin_token=token, **common, ) if hasattr(host, "resolve_session_user"): iid = host.resolve_session_user(token) if iid: ident = getattr(host, "_identities", {}).get(iid, {}) handle = str(ident.get("username") or ident.get("handle") or iid).lstrip("@") pubkey = str(ident.get("pubkey") or hashlib.sha256(f"fleetmesh-user:{handle}".encode("utf-8")).hexdigest()).lower() return AuthPrincipal( principal_id=iid, did=str(ident.get("did") or f"did:nostr:{pubkey}"), pubkey=pubkey, handle=handle, display_name=str(ident.get("handle") or handle), provider_id="host", auth_method="service_login", roles=expand_roles([str(ident.get("role") or "creator"), "broadcaster"]), **common, ) elif hasattr(host, "verify_session"): user = host.verify_session(token) if user: handle = str(user.get("handle") or "creator") pubkey = str(user.get("pubkey") or hashlib.sha256(f"fleetmesh-user:{handle}".encode("utf-8")).hexdigest()).lower() return AuthPrincipal( principal_id=f"host:user:{user.get('user_id') or handle}", did=f"did:nostr:{pubkey}", pubkey=pubkey, handle=handle, display_name=str(user.get("display_name") or handle), provider_id="host", auth_method="service_login", roles=expand_roles([str(user.get("role") or "creator"), "broadcaster"]), **common, ) if token.startswith("fmk_") and hasattr(host, "verify_api_key"): key_info = host.verify_api_key(token) if key_info: key_id = str(key_info.get("key_id") or "apikey") label = str(key_info.get("label") or key_id) pubkey = hashlib.sha256(f"fleetmesh-apikey:{key_id}".encode("utf-8")).hexdigest() raw_scopes = key_info.get("scopes") scopes: List[str] if isinstance(raw_scopes, (list, set, tuple, frozenset)): scopes = [str(s).strip() for s in raw_scopes if str(s).strip()] elif isinstance(raw_scopes, str) and raw_scopes.strip(): scopes = [s.strip() for s in raw_scopes.split(",") if s.strip()] else: scopes = ["*"] # A key acts as its owner, a creator: any user can mint one, so # it never carries admin or operator roles (0.1 gave it both). return AuthPrincipal( principal_id=f"host:apikey:{key_id}", did=f"did:nostr:{pubkey}", pubkey=pubkey, handle=label, display_name=label, provider_id="host", auth_method="api_key", roles=expand_roles(["broadcaster", "creator"]), **{**common, "scopes": scopes}, ) return None
[docs] def revoke_session(self, token: str) -> None: conn = self._conn() if conn is None: return try: with self._lock: conn.execute("DELETE FROM sessions WHERE token = ?", (token,)) conn.execute("DELETE FROM admin_sessions WHERE token = ?", (token,)) conn.commit() except Exception: pass
[docs] def default_db_path(self) -> Optional[str]: user_db = getattr(self.host, "_user_db_path", "") if user_db and user_db != ":memory:": return str(Path(user_db).parent / "fleetmesh_auth.sqlite") if hasattr(self.host, "data_dir"): return str(Path(self.host.data_dir) / "fleetmesh_auth.sqlite") return None